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 * ======================================================
26 #include <sys/types.h>
35 #include <boost/tuple/tuple.hpp>
38 #pragma implementation
42 #include "bufferlist.h"
44 #include "lyx_gui_misc.h"
45 #include "LyXAction.h"
48 #include "tex-strings.h"
50 #include "bufferview_funcs.h"
53 #include "mathed/formulamacro.h"
54 #include "mathed/formula.h"
55 #include "insets/inset.h"
56 #include "insets/inseterror.h"
57 #include "insets/insetlabel.h"
58 #include "insets/insetref.h"
59 #include "insets/inseturl.h"
60 #include "insets/insetnote.h"
61 #include "insets/insetquotes.h"
62 #include "insets/insetlatexaccent.h"
63 #include "insets/insetbib.h"
64 #include "insets/insetcite.h"
65 #include "insets/insetexternal.h"
66 #include "insets/insetindex.h"
67 #include "insets/insetinclude.h"
68 #include "insets/insettoc.h"
69 #include "insets/insetparent.h"
70 #include "insets/insetspecialchar.h"
71 #include "insets/figinset.h"
72 #include "insets/insettext.h"
73 #include "insets/insetert.h"
74 #include "insets/insetgraphics.h"
75 #include "insets/insetfoot.h"
76 #include "insets/insetmarginal.h"
77 #include "insets/insetminipage.h"
78 #include "insets/insetfloat.h"
79 #include "insets/insettabular.h"
81 #include "insets/insettheorem.h"
82 #include "insets/insetlist.h"
84 #include "insets/insetcaption.h"
85 #include "insets/insetfloatlist.h"
86 #include "support/textutils.h"
87 #include "support/filetools.h"
88 #include "support/path.h"
89 #include "support/os.h"
94 #include "LaTeXFeatures.h"
95 #include "support/syscall.h"
96 #include "support/lyxlib.h"
97 #include "support/FileInfo.h"
98 #include "support/lyxmanip.h"
101 #include "language.h"
102 #include "lyx_gui_misc.h" // WarnReadonly()
103 #include "frontends/Dialogs.h"
104 #include "encoding.h"
105 #include "exporter.h"
106 #include "Lsstream.h"
107 #include "converter.h"
108 #include "BufferView.h"
109 #include "ParagraphParameters.h"
119 using std::make_pair;
127 // all these externs should eventually be removed.
128 extern BufferList bufferlist;
130 extern LyXAction lyxaction;
134 const int LYX_FORMAT = 220;
138 extern int tex_code_break_column;
141 Buffer::Buffer(string const & file, bool ronly)
143 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
145 filepath = OnlyPath(file);
154 if (read_only || (lyxrc.use_tempdir)) {
155 tmppath = CreateBufferTmpDir();
156 } else tmppath.erase();
162 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
163 // here the buffer should take care that it is
164 // saved properly, before it goes into the void.
166 // make sure that views using this buffer
171 if (!tmppath.empty()) {
172 DestroyBufferTmpDir(tmppath);
175 Paragraph * par = paragraph;
178 tmppar = par->next();
186 string const Buffer::getLatexName(bool no_path) const
188 string name = ChangeExtension(MakeLatexName(filename), ".tex");
190 return OnlyFilename(name);
196 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
198 string const filename = getLatexName(false);
200 if (filename.empty())
201 return make_pair(Buffer::latexlog, string());
203 string path = OnlyPath(filename);
205 if (lyxrc.use_tempdir || !IsDirWriteable(path))
208 string const fname = AddName(path,
209 OnlyFilename(ChangeExtension(filename,
212 AddName(path, OnlyFilename(
213 ChangeExtension(filename,
214 formats.extension("literate") + ".out")));
216 // If no Latex log or Build log is newer, show Build log
218 FileInfo const f_fi(fname);
219 FileInfo const b_fi(bname);
222 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
223 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
224 return make_pair(Buffer::buildlog, bname);
226 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
227 return make_pair(Buffer::latexlog, fname);
231 void Buffer::setReadonly(bool flag)
233 if (read_only != flag) {
236 users->owner()->getDialogs()->updateBufferDependent(false);
239 WarnReadonly(filename);
244 bool Buffer::saveParamsAsDefaults() // const
246 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
248 Buffer defaults = Buffer(fname);
250 // Use the current buffer's parameters as default
251 defaults.params = params;
253 // add an empty paragraph. Is this enough?
254 defaults.paragraph = new Paragraph;
256 return defaults.writeFile(defaults.filename, false);
260 /// Update window titles of all users
261 // Should work on a list
262 void Buffer::updateTitles() const
264 if (users) users->owner()->updateWindowTitle();
268 /// Reset autosave timer of all users
269 // Should work on a list
270 void Buffer::resetAutosaveTimers() const
272 if (users) users->owner()->resetAutosaveTimer();
276 void Buffer::setFileName(string const & newfile)
278 filename = MakeAbsPath(newfile);
279 filepath = OnlyPath(filename);
280 setReadonly(IsFileWriteable(filename) == 0);
285 // We'll remove this later. (Lgb)
288 string last_inset_read;
290 #ifndef NO_COMPABILITY
293 ErtComp() : active(false), in_tabular(false) {
300 std::stack<ErtComp> ert_stack;
304 #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)
321 #ifndef NO_COMPABILITY
322 ert_comp.contents.erase();
323 ert_comp.active = false;
324 ert_comp.in_tabular = false;
327 Paragraph::depth_type depth = 0;
328 bool the_end_read = false;
330 Paragraph * first_par = 0;
331 LyXFont font(LyXFont::ALL_INHERIT, params.language);
332 if (file_format < 216 && params.language->lang() == "hebrew")
333 font.setLanguage(default_language);
338 // We are inserting into an existing document
339 users->text->breakParagraph(users);
340 first_par = users->text->firstParagraph();
343 // We don't want to adopt the parameters from the
344 // document we insert, so we skip until the text begins:
347 string const pretoken = lex.getString();
348 if (pretoken == "\\layout") {
349 lex.pushToken(pretoken);
357 string const token = lex.getString();
359 if (token.empty()) continue;
361 lyxerr[Debug::PARSER] << "Handling token: `"
362 << token << "'" << endl;
365 parseSingleLyXformat2Token(lex, par, first_par,
373 paragraph = first_par;
375 if (unknown_layouts > 0) {
376 string s = _("Couldn't set the layout for ");
377 if (unknown_layouts == 1) {
378 s += _("one paragraph");
380 s += tostr(unknown_layouts);
381 s += _(" paragraphs");
383 WriteAlert(_("Textclass Loading Error!"), s,
384 _("When reading " + fileName()));
391 #ifndef NO_COMPABILITY
392 void Buffer::insertErtContents(Paragraph * par, int & pos,
393 LyXFont const & font, bool set_inactive)
395 if (!ert_comp.contents.empty()) {
396 lyxerr[Debug::INSETS] << "ERT contents:\n"
397 << ert_comp.contents << endl;
398 Inset * inset = new InsetERT(ert_comp.contents, true);
399 par->insertInset(pos++, inset, font);
400 ert_comp.contents.erase();
403 ert_comp.active = false;
410 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
411 Paragraph *& first_par,
412 string const & token, int & pos,
413 Paragraph::depth_type & depth,
417 bool the_end_read = false;
418 #ifndef NO_COMPABILITY
419 #ifndef NO_PEXTRA_REALLY
420 // This is super temporary but is needed to get the compability
421 // mode for minipages work correctly together with new tabulars.
422 static int call_depth;
424 bool checkminipage = false;
425 static Paragraph * minipar;
426 static Paragraph * parBeforeMinipage;
429 if (token[0] != '\\') {
430 #ifndef NO_COMPABILITY
431 if (ert_comp.active) {
432 ert_comp.contents += token;
435 for (string::const_iterator cit = token.begin();
436 cit != token.end(); ++cit) {
437 par->insertChar(pos, (*cit), font);
440 #ifndef NO_COMPABILITY
443 } else if (token == "\\i") {
444 Inset * inset = new InsetLatexAccent;
445 inset->read(this, lex);
446 par->insertInset(pos, inset, font);
448 } else if (token == "\\layout") {
449 #ifndef NO_COMPABILITY
450 ert_comp.in_tabular = false;
452 insertErtContents(par, pos, font);
455 string const layoutname = lex.getString();
456 pair<bool, LyXTextClass::LayoutList::size_type> pp
457 = textclasslist.NumberOfLayout(params.textclass,
460 #ifndef NO_COMPABILITY
461 if (compare_no_case(layoutname, "latex") == 0) {
462 ert_comp.active = true;
466 // The is the compability reading of layout caption.
467 // It can be removed in LyX version 1.3.0. (Lgb)
468 if (compare_no_case(layoutname, "caption") == 0) {
469 // We expect that the par we are now working on is
470 // really inside a InsetText inside a InsetFloat.
471 // We also know that captions can only be
472 // one paragraph. (Lgb)
474 // We should now read until the next "\layout"
476 // This is probably not good enough, what if the
477 // caption is the last par in the document (Lgb)
478 istream & ist = lex.getStream();
484 if (prefixIs(line, "\\layout")) {
488 if (prefixIs(line, "\\begin_inset"))
490 if (prefixIs(line, "\\end_inset")) {
501 // Now we should have the whole layout in ss
502 // we should now be able to give this to the
504 ss << "\\end_inset\n";
506 // This seems like a bug in stringstream.
507 // We really should be able to use ss
509 istringstream is(ss.str());
511 tmplex.setStream(is);
512 Inset * inset = new InsetCaption;
513 inset->Read(this, tmplex);
514 par->InsertInset(pos, inset, font);
521 par = new Paragraph(par);
525 par->layout = pp.second;
526 #ifndef NO_COMPABILITY
527 } else if (ert_comp.active) {
532 // use default layout "Standard" (0)
535 string const s = _("Layout had to be changed from\n")
536 + layoutname + _(" to ")
537 + textclasslist.NameOfLayout(params.textclass, par->layout);
538 InsetError * new_inset = new InsetError(s);
539 par->insertInset(0, new_inset);
541 // Test whether the layout is obsolete.
542 LyXLayout const & layout =
543 textclasslist.Style(params.textclass,
545 if (!layout.obsoleted_by().empty())
546 par->layout = textclasslist
547 .NumberOfLayout(params.textclass,
548 layout.obsoleted_by())
550 par->params().depth(depth);
551 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
552 if (file_format < 216
553 && params.language->lang() == "hebrew")
554 font.setLanguage(default_language);
559 #ifndef NO_COMPABILITY
560 } else if (token == "\\begin_float") {
561 insertErtContents(par, pos, font);
562 //insertErtContents(par, pos, font, false);
563 //ert_stack.push(ert_comp);
564 //ert_comp = ErtComp();
566 // This is the compability reader. It can be removed in
567 // LyX version 1.3.0. (Lgb)
569 string const tmptok = lex.getString();
570 //lyxerr << "old float: " << tmptok << endl;
573 stringstream old_float;
575 if (tmptok == "footnote") {
576 inset = new InsetFoot;
577 old_float << "collapsed true\n";
578 } else if (tmptok == "margin") {
579 inset = new InsetMarginal;
580 old_float << "collapsed true\n";
581 } else if (tmptok == "fig") {
582 inset = new InsetFloat("figure");
583 old_float << "placement htbp\n"
585 << "collapsed false\n";
586 } else if (tmptok == "tab") {
587 inset = new InsetFloat("table");
588 old_float << "placement htbp\n"
590 << "collapsed false\n";
591 } else if (tmptok == "alg") {
592 inset = new InsetFloat("algorithm");
593 old_float << "placement htbp\n"
595 << "collapsed false\n";
596 } else if (tmptok == "wide-fig") {
597 inset = new InsetFloat("figure");
598 //InsetFloat * tmp = new InsetFloat("figure");
601 old_float << "placement htbp\n"
603 << "collapsed false\n";
604 } else if (tmptok == "wide-tab") {
605 inset = new InsetFloat("table");
606 //InsetFloat * tmp = new InsetFloat("table");
609 old_float << "placement htbp\n"
611 << "collapsed false\n";
615 #ifndef NO_PEXTRA_REALLY
618 return false; // no end read yet
621 // Here we need to check for \end_deeper and handle that
622 // before we do the footnote parsing.
623 // This _is_ a hack! (Lgb)
626 string const tmp = lex.getString();
627 if (tmp == "\\end_deeper") {
628 //lyxerr << "\\end_deeper caught!" << endl;
630 lex.printError("\\end_deeper: "
631 "depth is already null");
636 old_float << tmp << ' ';
641 old_float << lex.getLongString("\\end_float")
642 << "\n\\end_inset\n";
643 //lyxerr << "Float Body:\n" << old_float.str() << endl;
644 // That this does not work seems like a bug
645 // in stringstream. (Lgb)
646 istringstream istr(old_float.str());
648 nylex.setStream(istr);
649 inset->read(this, nylex);
650 par->insertInset(pos, inset, font);
652 insertErtContents(par, pos, font);
654 } else if (token == "\\begin_deeper") {
656 } else if (token == "\\end_deeper") {
658 lex.printError("\\end_deeper: "
659 "depth is already null");
663 } else if (token == "\\begin_preamble") {
664 params.readPreamble(lex);
665 } else if (token == "\\textclass") {
667 pair<bool, LyXTextClassList::size_type> pp =
668 textclasslist.NumberOfClass(lex.getString());
670 params.textclass = pp.second;
672 WriteAlert(string(_("Textclass error")),
673 string(_("The document uses an unknown textclass \"")) +
674 lex.getString() + string("\"."),
675 string(_("LyX will not be able to produce output correctly.")));
676 params.textclass = 0;
678 if (!textclasslist.Load(params.textclass)) {
679 // if the textclass wasn't loaded properly
680 // we need to either substitute another
681 // or stop loading the file.
682 // I can substitute but I don't see how I can
683 // stop loading... ideas?? ARRae980418
684 WriteAlert(_("Textclass Loading Error!"),
685 string(_("Can't load textclass ")) +
686 textclasslist.NameOfClass(params.textclass),
687 _("-- substituting default"));
688 params.textclass = 0;
690 } else if (token == "\\options") {
692 params.options = lex.getString();
693 } else if (token == "\\language") {
694 params.readLanguage(lex);
695 } else if (token == "\\fontencoding") {
697 } else if (token == "\\inputencoding") {
699 params.inputenc = lex.getString();
700 } else if (token == "\\graphics") {
701 params.readGraphicsDriver(lex);
702 } else if (token == "\\fontscheme") {
704 params.fonts = lex.getString();
705 } else if (token == "\\noindent") {
706 par->params().noindent(true);
707 } else if (token == "\\fill_top") {
708 par->params().spaceTop(VSpace(VSpace::VFILL));
709 } else if (token == "\\fill_bottom") {
710 par->params().spaceBottom(VSpace(VSpace::VFILL));
711 } else if (token == "\\line_top") {
712 par->params().lineTop(true);
713 } else if (token == "\\line_bottom") {
714 par->params().lineBottom(true);
715 } else if (token == "\\pagebreak_top") {
716 par->params().pagebreakTop(true);
717 } else if (token == "\\pagebreak_bottom") {
718 par->params().pagebreakBottom(true);
719 } else if (token == "\\start_of_appendix") {
720 par->params().startOfAppendix(true);
721 } else if (token == "\\paragraph_separation") {
722 int tmpret = lex.findToken(string_paragraph_separation);
723 if (tmpret == -1) ++tmpret;
724 if (tmpret != LYX_LAYOUT_DEFAULT)
725 params.paragraph_separation =
726 static_cast<BufferParams::PARSEP>(tmpret);
727 } else if (token == "\\defskip") {
729 params.defskip = VSpace(lex.getString());
730 } else if (token == "\\epsfig") { // obsolete
731 // Indeed it is obsolete, but we HAVE to be backwards
732 // compatible until 0.14, because otherwise all figures
733 // in existing documents are irretrivably lost. (Asger)
734 params.readGraphicsDriver(lex);
735 } else if (token == "\\quotes_language") {
736 int tmpret = lex.findToken(string_quotes_language);
737 if (tmpret == -1) ++tmpret;
738 if (tmpret != LYX_LAYOUT_DEFAULT) {
739 InsetQuotes::quote_language tmpl =
740 InsetQuotes::EnglishQ;
743 tmpl = InsetQuotes::EnglishQ;
746 tmpl = InsetQuotes::SwedishQ;
749 tmpl = InsetQuotes::GermanQ;
752 tmpl = InsetQuotes::PolishQ;
755 tmpl = InsetQuotes::FrenchQ;
758 tmpl = InsetQuotes::DanishQ;
761 params.quotes_language = tmpl;
763 } else if (token == "\\quotes_times") {
765 switch (lex.getInteger()) {
767 params.quotes_times = InsetQuotes::SingleQ;
770 params.quotes_times = InsetQuotes::DoubleQ;
773 } else if (token == "\\papersize") {
774 int tmpret = lex.findToken(string_papersize);
778 params.papersize2 = tmpret;
779 } else if (token == "\\paperpackage") {
780 int tmpret = lex.findToken(string_paperpackages);
783 params.paperpackage = BufferParams::PACKAGE_NONE;
785 params.paperpackage = tmpret;
786 } else if (token == "\\use_geometry") {
788 params.use_geometry = lex.getInteger();
789 } else if (token == "\\use_amsmath") {
791 params.use_amsmath = lex.getInteger();
792 } else if (token == "\\use_natbib") {
794 params.use_natbib = lex.getInteger();
795 } else if (token == "\\use_numerical_citations") {
797 params.use_numerical_citations = lex.getInteger();
798 } else if (token == "\\paperorientation") {
799 int tmpret = lex.findToken(string_orientation);
800 if (tmpret == -1) ++tmpret;
801 if (tmpret != LYX_LAYOUT_DEFAULT)
802 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
803 } else if (token == "\\paperwidth") {
805 params.paperwidth = lex.getString();
806 } else if (token == "\\paperheight") {
808 params.paperheight = lex.getString();
809 } else if (token == "\\leftmargin") {
811 params.leftmargin = lex.getString();
812 } else if (token == "\\topmargin") {
814 params.topmargin = lex.getString();
815 } else if (token == "\\rightmargin") {
817 params.rightmargin = lex.getString();
818 } else if (token == "\\bottommargin") {
820 params.bottommargin = lex.getString();
821 } else if (token == "\\headheight") {
823 params.headheight = lex.getString();
824 } else if (token == "\\headsep") {
826 params.headsep = lex.getString();
827 } else if (token == "\\footskip") {
829 params.footskip = lex.getString();
830 } else if (token == "\\paperfontsize") {
832 params.fontsize = strip(lex.getString());
833 } else if (token == "\\papercolumns") {
835 params.columns = lex.getInteger();
836 } else if (token == "\\papersides") {
838 switch (lex.getInteger()) {
840 case 1: params.sides = LyXTextClass::OneSide; break;
841 case 2: params.sides = LyXTextClass::TwoSides; break;
843 } else if (token == "\\paperpagestyle") {
845 params.pagestyle = strip(lex.getString());
846 } else if (token == "\\bullet") {
848 int const index = lex.getInteger();
850 int temp_int = lex.getInteger();
851 params.user_defined_bullets[index].setFont(temp_int);
852 params.temp_bullets[index].setFont(temp_int);
854 temp_int = lex.getInteger();
855 params.user_defined_bullets[index].setCharacter(temp_int);
856 params.temp_bullets[index].setCharacter(temp_int);
858 temp_int = lex.getInteger();
859 params.user_defined_bullets[index].setSize(temp_int);
860 params.temp_bullets[index].setSize(temp_int);
862 string const temp_str = lex.getString();
863 if (temp_str != "\\end_bullet") {
864 // this element isn't really necessary for
865 // parsing but is easier for humans
866 // to understand bullets. Put it back and
867 // set a debug message?
868 lex.printError("\\end_bullet expected, got" + temp_str);
869 //how can I put it back?
871 } else if (token == "\\bulletLaTeX") {
873 int const index = lex.getInteger();
875 string temp_str = lex.getString();
877 while (temp_str != "\\end_bullet") {
878 // this loop structure is needed when user
879 // enters an empty string since the first
880 // thing returned will be the \\end_bullet
882 // if the LaTeX entry has spaces. Each element
883 // therefore needs to be read in turn
886 temp_str = lex.getString();
888 params.user_defined_bullets[index].setText(sum_str);
889 params.temp_bullets[index].setText(sum_str);
890 } else if (token == "\\secnumdepth") {
892 params.secnumdepth = lex.getInteger();
893 } else if (token == "\\tocdepth") {
895 params.tocdepth = lex.getInteger();
896 } else if (token == "\\spacing") {
898 string const tmp = strip(lex.getString());
899 Spacing::Space tmp_space = Spacing::Default;
901 if (tmp == "single") {
902 tmp_space = Spacing::Single;
903 } else if (tmp == "onehalf") {
904 tmp_space = Spacing::Onehalf;
905 } else if (tmp == "double") {
906 tmp_space = Spacing::Double;
907 } else if (tmp == "other") {
909 tmp_space = Spacing::Other;
910 tmp_val = lex.getFloat();
912 lex.printError("Unknown spacing token: '$$Token'");
914 // Small hack so that files written with klyx will be
917 par->params().spacing(Spacing(tmp_space, tmp_val));
919 params.spacing.set(tmp_space, tmp_val);
921 } else if (token == "\\paragraph_spacing") {
923 string const tmp = strip(lex.getString());
924 if (tmp == "single") {
925 par->params().spacing(Spacing(Spacing::Single));
926 } else if (tmp == "onehalf") {
927 par->params().spacing(Spacing(Spacing::Onehalf));
928 } else if (tmp == "double") {
929 par->params().spacing(Spacing(Spacing::Double));
930 } else if (tmp == "other") {
932 par->params().spacing(Spacing(Spacing::Other,
935 lex.printError("Unknown spacing token: '$$Token'");
937 } else if (token == "\\float_placement") {
939 params.float_placement = lex.getString();
940 } else if (token == "\\family") {
942 font.setLyXFamily(lex.getString());
943 } else if (token == "\\series") {
945 font.setLyXSeries(lex.getString());
946 } else if (token == "\\shape") {
948 font.setLyXShape(lex.getString());
949 } else if (token == "\\size") {
951 font.setLyXSize(lex.getString());
952 #ifndef NO_COMPABILITY
953 } else if (token == "\\latex") {
955 string const tok = lex.getString();
956 if (tok == "no_latex") {
958 insertErtContents(par, pos, font);
959 } else if (tok == "latex") {
960 ert_comp.active = true;
961 } else if (tok == "default") {
963 insertErtContents(par, pos, font);
965 lex.printError("Unknown LaTeX font flag "
969 } else if (token == "\\lang") {
971 string const tok = lex.getString();
972 Language const * lang = languages.getLanguage(tok);
974 font.setLanguage(lang);
976 font.setLanguage(params.language);
977 lex.printError("Unknown language `$$Token'");
979 } else if (token == "\\numeric") {
981 font.setNumber(font.setLyXMisc(lex.getString()));
982 } else if (token == "\\emph") {
984 font.setEmph(font.setLyXMisc(lex.getString()));
985 } else if (token == "\\bar") {
987 string const tok = lex.getString();
988 // This is dirty, but gone with LyX3. (Asger)
990 font.setUnderbar(LyXFont::ON);
991 else if (tok == "no")
992 font.setUnderbar(LyXFont::OFF);
993 else if (tok == "default")
994 font.setUnderbar(LyXFont::INHERIT);
996 lex.printError("Unknown bar font flag "
998 } else if (token == "\\noun") {
1000 font.setNoun(font.setLyXMisc(lex.getString()));
1001 } else if (token == "\\color") {
1003 font.setLyXColor(lex.getString());
1004 } else if (token == "\\align") {
1005 int tmpret = lex.findToken(string_align);
1006 if (tmpret == -1) ++tmpret;
1007 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1008 int const tmpret2 = int(pow(2.0, tmpret));
1009 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1010 par->params().align(LyXAlignment(tmpret2));
1012 } else if (token == "\\added_space_top") {
1014 par->params().spaceTop(VSpace(lex.getString()));
1015 } else if (token == "\\added_space_bottom") {
1017 par->params().spaceBottom(VSpace(lex.getString()));
1018 #ifndef NO_COMPABILITY
1019 #ifndef NO_PEXTRA_REALLY
1020 } else if (token == "\\pextra_type") {
1022 par->params().pextraType(lex.getInteger());
1023 } else if (token == "\\pextra_width") {
1025 par->params().pextraWidth(lex.getString());
1026 } else if (token == "\\pextra_widthp") {
1028 par->params().pextraWidthp(lex.getString());
1029 } else if (token == "\\pextra_alignment") {
1031 par->params().pextraAlignment(lex.getInteger());
1032 } else if (token == "\\pextra_hfill") {
1034 par->params().pextraHfill(lex.getInteger());
1035 } else if (token == "\\pextra_start_minipage") {
1037 par->params().pextraStartMinipage(lex.getInteger());
1040 } else if (token == "\\labelwidthstring") {
1042 par->params().labelWidthString(lex.getString());
1043 // do not delete this token, it is still needed!
1044 } else if (token == "\\end_inset") {
1045 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1046 << "Last inset read was: " << last_inset_read
1048 // Simply ignore this. The insets do not have
1050 // But insets should read it, it is a part of
1051 // the inset isn't it? Lgb.
1052 } else if (token == "\\begin_inset") {
1053 #ifndef NO_COMPABILITY
1054 insertErtContents(par, pos, font, false);
1055 ert_stack.push(ert_comp);
1056 ert_comp = ErtComp();
1058 readInset(lex, par, pos, font);
1059 #ifndef NO_COMPABILITY
1060 ert_comp = ert_stack.top();
1062 insertErtContents(par, pos, font);
1064 } else if (token == "\\SpecialChar") {
1065 LyXLayout const & layout =
1066 textclasslist.Style(params.textclass,
1069 // Insets don't make sense in a free-spacing context! ---Kayvan
1070 if (layout.free_spacing) {
1073 string next_token = lex.getString();
1074 if (next_token == "\\-") {
1075 par->insertChar(pos, '-', font);
1076 } else if (next_token == "\\protected_separator"
1077 || next_token == "~") {
1078 par->insertChar(pos, ' ', font);
1080 lex.printError("Token `$$Token' "
1082 "paragraph layout!");
1087 Inset * inset = new InsetSpecialChar;
1088 inset->read(this, lex);
1089 par->insertInset(pos, inset, font);
1092 } else if (token == "\\newline") {
1093 #ifndef NO_COMPABILITY
1094 if (!ert_comp.in_tabular && ert_comp.active) {
1095 ert_comp.contents += char(Paragraph::META_NEWLINE);
1097 // Since we cannot know it this is only a regular
1098 // newline or a tabular cell delimter we have to
1099 // handle the ERT here.
1100 insertErtContents(par, pos, font, false);
1102 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1106 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1109 } else if (token == "\\LyXTable") {
1110 #ifndef NO_COMPABILITY
1111 ert_comp.in_tabular = true;
1113 Inset * inset = new InsetTabular(*this);
1114 inset->read(this, lex);
1115 par->insertInset(pos, inset, font);
1117 } else if (token == "\\hfill") {
1118 par->insertChar(pos, Paragraph::META_HFILL, font);
1120 } else if (token == "\\protected_separator") { // obsolete
1121 // This is a backward compability thingie. (Lgb)
1122 // Remove it later some time...introduced with fileformat
1124 LyXLayout const & layout =
1125 textclasslist.Style(params.textclass,
1128 if (layout.free_spacing) {
1129 par->insertChar(pos, ' ', font);
1131 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1132 par->insertInset(pos, inset, font);
1135 } else if (token == "\\bibitem") { // ale970302
1137 InsetCommandParams p("bibitem", "dummy");
1138 par->bibkey = new InsetBibKey(p);
1140 par->bibkey->read(this, lex);
1141 } else if (token == "\\backslash") {
1142 #ifndef NO_COMPABILITY
1143 if (ert_comp.active) {
1144 ert_comp.contents += "\\";
1147 par->insertChar(pos, '\\', font);
1149 #ifndef NO_COMPABILITY
1152 } else if (token == "\\the_end") {
1153 #ifndef NO_COMPABILITY
1154 // If we still have some ert active here we have to insert
1155 // it so we don't loose it. (Lgb)
1156 insertErtContents(par, pos, font);
1158 the_end_read = true;
1159 #ifndef NO_COMPABILITY
1160 #ifndef NO_PEXTRA_REALLY
1161 minipar = parBeforeMinipage = 0;
1165 #ifndef NO_COMPABILITY
1166 if (ert_comp.active) {
1167 ert_comp.contents += token;
1170 // This should be insurance for the future: (Asger)
1171 lex.printError("Unknown token `$$Token'. "
1172 "Inserting as text.");
1173 string::const_iterator cit = token.begin();
1174 string::const_iterator end = token.end();
1175 for (; cit != end; ++cit) {
1176 par->insertChar(pos, (*cit), font);
1179 #ifndef NO_COMPABILITY
1184 #ifndef NO_COMPABILITY
1185 #ifndef NO_PEXTRA_REALLY
1186 // I wonder if we could use this blanket fix for all the
1187 // checkminipage cases...
1188 if (par && par->size()) {
1189 // It is possible that this will check to often,
1190 // but that should not be an correctness issue.
1191 // Only a speed issue.
1192 checkminipage = true;
1195 // now check if we have a minipage paragraph as at this
1196 // point we already read all the necessary data!
1197 // this cannot be done in layout because there we did
1198 // not read yet the paragraph PEXTRA-params (Jug)
1200 // BEGIN pextra_minipage compability
1201 // This should be removed in 1.3.x (Lgb)
1203 // This compability code is not perfect. In a couple
1204 // of rand cases it fails. When the minipage par is
1205 // the first par in the document, and when there are
1206 // none or only one regular paragraphs after the
1207 // minipage. Currently I am not investing any effort
1208 // in fixing those cases.
1210 //lyxerr << "Call depth: " << call_depth << endl;
1211 if (checkminipage && (call_depth == 1)) {
1212 checkminipage = false;
1213 if (minipar && (minipar != par) &&
1214 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1216 lyxerr << "minipages in a row" << endl;
1217 if (par->params().pextraStartMinipage()) {
1218 lyxerr << "start new minipage" << endl;
1219 // minipages in a row
1220 par->previous()->next(0);
1223 Paragraph * tmp = minipar;
1225 tmp->params().pextraType(0);
1226 tmp->params().pextraWidth(string());
1227 tmp->params().pextraWidthp(string());
1228 tmp->params().pextraAlignment(0);
1229 tmp->params().pextraHfill(false);
1230 tmp->params().pextraStartMinipage(false);
1233 // create a new paragraph to insert the
1234 // minipages in the following case
1235 if (par->params().pextraStartMinipage() &&
1236 !par->params().pextraHfill())
1238 Paragraph * p = new Paragraph;
1240 p->previous(parBeforeMinipage);
1241 parBeforeMinipage->next(p);
1243 p->params().depth(parBeforeMinipage->params().depth());
1244 parBeforeMinipage = p;
1246 InsetMinipage * mini = new InsetMinipage;
1247 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1248 mini->width(par->params().pextraWidth());
1249 if (!par->params().pextraWidthp().empty()) {
1250 lyxerr << "WP:" << mini->width() << endl;
1251 mini->width(tostr(par->params().pextraWidthp())+"%");
1253 mini->inset.paragraph(par);
1254 // Insert the minipage last in the
1255 // previous paragraph.
1256 if (par->params().pextraHfill()) {
1257 parBeforeMinipage->insertChar
1258 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1260 parBeforeMinipage->insertInset
1261 (parBeforeMinipage->size(), mini);
1265 lyxerr << "new minipage par" << endl;
1266 //nothing to do just continue reading
1269 } else if (minipar && (minipar != par)) {
1270 lyxerr << "last minipage par read" << endl;
1271 // The last paragraph read was not part of a
1272 // minipage but the par linked list is...
1273 // So we need to remove the last par from the
1275 if (par->previous())
1276 par->previous()->next(0);
1277 par->previous(parBeforeMinipage);
1278 parBeforeMinipage->next(par);
1279 Paragraph * tmp = minipar;
1281 tmp->params().pextraType(0);
1282 tmp->params().pextraWidth(string());
1283 tmp->params().pextraWidthp(string());
1284 tmp->params().pextraAlignment(0);
1285 tmp->params().pextraHfill(false);
1286 tmp->params().pextraStartMinipage(false);
1289 depth = parBeforeMinipage->params().depth();
1290 minipar = parBeforeMinipage = 0;
1291 } else if (!minipar &&
1292 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1294 // par is the first paragraph in a minipage
1295 lyxerr << "begin minipage" << endl;
1296 // To minimize problems for
1297 // the users we will insert
1298 // the first minipage in
1299 // a sequence of minipages
1300 // in its own paragraph.
1301 Paragraph * p = new Paragraph;
1303 p->previous(par->previous());
1305 p->params().depth(depth);
1306 par->params().depth(0);
1308 if (par->previous())
1309 par->previous()->next(p);
1311 parBeforeMinipage = p;
1313 if (!first_par || (first_par == par))
1316 InsetMinipage * mini = new InsetMinipage;
1317 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1318 mini->width(minipar->params().pextraWidth());
1319 if (!par->params().pextraWidthp().empty()) {
1320 lyxerr << "WP:" << mini->width() << endl;
1321 mini->width(tostr(par->params().pextraWidthp())+"%");
1323 mini->inset.paragraph(minipar);
1325 // Insert the minipage last in the
1326 // previous paragraph.
1327 if (minipar->params().pextraHfill()) {
1328 parBeforeMinipage->insertChar
1329 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1331 parBeforeMinipage->insertInset
1332 (parBeforeMinipage->size(), mini);
1335 // End of pextra_minipage compability
1339 return the_end_read;
1342 // needed to insert the selection
1343 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1344 LyXFont const & font,
1345 string const & str) const
1347 LyXLayout const & layout = textclasslist.Style(params.textclass,
1349 // insert the string, don't insert doublespace
1350 bool space_inserted = true;
1351 for(string::const_iterator cit = str.begin();
1352 cit != str.end(); ++cit) {
1354 if (par->size() || layout.keepempty) {
1355 par->breakParagraph(params, pos,
1356 layout.isEnvironment());
1359 space_inserted = true;
1363 // do not insert consecutive spaces if !free_spacing
1364 } else if ((*cit == ' ' || *cit == '\t')
1365 && space_inserted && !layout.free_spacing) {
1367 } else if (*cit == '\t') {
1368 if (!layout.free_spacing) {
1369 // tabs are like spaces here
1370 par->insertChar(pos, ' ', font);
1372 space_inserted = true;
1374 const Paragraph::value_type nb = 8 - pos % 8;
1375 for (Paragraph::size_type a = 0;
1377 par->insertChar(pos, ' ', font);
1380 space_inserted = true;
1382 } else if (!IsPrintable(*cit)) {
1383 // Ignore unprintables
1386 // just insert the character
1387 par->insertChar(pos, *cit, font);
1389 space_inserted = (*cit == ' ');
1396 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1397 int & pos, LyXFont & font)
1399 // consistency check
1400 if (lex.getString() != "\\begin_inset") {
1401 lyxerr << "Buffer::readInset: Consistency check failed."
1408 string const tmptok = lex.getString();
1409 last_inset_read = tmptok;
1411 // test the different insets
1412 if (tmptok == "LatexCommand") {
1413 InsetCommandParams inscmd;
1416 string const cmdName = inscmd.getCmdName();
1418 // This strange command allows LyX to recognize "natbib" style
1419 // citations: citet, citep, Citet etc.
1420 if (compare_no_case(cmdName, "cite", 4) == 0) {
1421 inset = new InsetCitation(inscmd);
1422 } else if (cmdName == "bibitem") {
1423 lex.printError("Wrong place for bibitem");
1424 inset = new InsetBibKey(inscmd);
1425 } else if (cmdName == "BibTeX") {
1426 inset = new InsetBibtex(inscmd);
1427 } else if (cmdName == "index") {
1428 inset = new InsetIndex(inscmd);
1429 } else if (cmdName == "include") {
1430 inset = new InsetInclude(inscmd, *this);
1431 } else if (cmdName == "label") {
1432 inset = new InsetLabel(inscmd);
1433 } else if (cmdName == "url"
1434 || cmdName == "htmlurl") {
1435 inset = new InsetUrl(inscmd);
1436 } else if (cmdName == "ref"
1437 || cmdName == "pageref"
1438 || cmdName == "vref"
1439 || cmdName == "vpageref"
1440 || cmdName == "prettyref") {
1441 if (!inscmd.getOptions().empty()
1442 || !inscmd.getContents().empty()) {
1443 inset = new InsetRef(inscmd, *this);
1445 } else if (cmdName == "tableofcontents") {
1446 inset = new InsetTOC(inscmd);
1447 } else if (cmdName == "listofalgorithms") {
1448 inset = new InsetFloatList("algorithm");
1449 } else if (cmdName == "listoffigures") {
1450 inset = new InsetFloatList("figure");
1451 } else if (cmdName == "listoftables") {
1452 inset = new InsetFloatList("table");
1453 } else if (cmdName == "printindex") {
1454 inset = new InsetPrintIndex(inscmd);
1455 } else if (cmdName == "lyxparent") {
1456 inset = new InsetParent(inscmd, *this);
1459 bool alreadyread = false;
1460 if (tmptok == "Quotes") {
1461 inset = new InsetQuotes;
1462 } else if (tmptok == "External") {
1463 inset = new InsetExternal;
1464 } else if (tmptok == "FormulaMacro") {
1465 inset = new InsetFormulaMacro;
1466 } else if (tmptok == "Formula") {
1467 inset = new InsetFormula;
1468 } else if (tmptok == "Figure") { // Backward compatibility
1469 inset = new InsetFig(100, 100, *this);
1470 //inset = new InsetGraphics;
1471 } else if (tmptok == "Graphics") {
1472 inset = new InsetGraphics;
1473 } else if (tmptok == "Info") {// backwards compatibility
1474 inset = new InsetNote(this,
1475 lex.getLongString("\\end_inset"),
1478 } else if (tmptok == "Note") {
1479 inset = new InsetNote;
1480 } else if (tmptok == "Include") {
1481 InsetCommandParams p( "Include" );
1482 inset = new InsetInclude(p, *this);
1483 } else if (tmptok == "ERT") {
1484 inset = new InsetERT;
1485 } else if (tmptok == "Tabular") {
1486 inset = new InsetTabular(*this);
1487 } else if (tmptok == "Text") {
1488 inset = new InsetText;
1489 } else if (tmptok == "Foot") {
1490 inset = new InsetFoot;
1491 } else if (tmptok == "Marginal") {
1492 inset = new InsetMarginal;
1493 } else if (tmptok == "Minipage") {
1494 inset = new InsetMinipage;
1495 } else if (tmptok == "Float") {
1497 string tmptok = lex.getString();
1498 inset = new InsetFloat(tmptok);
1500 } else if (tmptok == "List") {
1501 inset = new InsetList;
1502 } else if (tmptok == "Theorem") {
1503 inset = new InsetList;
1505 } else if (tmptok == "Caption") {
1506 inset = new InsetCaption;
1507 } else if (tmptok == "FloatList") {
1508 inset = new InsetFloatList;
1511 if (inset && !alreadyread) inset->read(this, lex);
1515 par->insertInset(pos, inset, font);
1521 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1525 string const token(lex.getString());
1526 if (token == "\\lyxformat") { // the first token _must_ be...
1528 string tmp_format = lex.getString();
1529 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1530 // if present remove ".," from string.
1531 string::size_type dot = tmp_format.find_first_of(".,");
1532 //lyxerr << " dot found at " << dot << endl;
1533 if (dot != string::npos)
1534 tmp_format.erase(dot, 1);
1535 file_format = strToInt(tmp_format);
1536 if (file_format == LYX_FORMAT) {
1538 } else if (file_format > LYX_FORMAT) {
1540 WriteAlert(_("Warning!"),
1541 _("LyX file format is newer that what"),
1542 _("is supported in this LyX version. Expect some problems."));
1544 } else if (file_format < LYX_FORMAT) {
1546 if (file_format < 200) {
1547 WriteAlert(_("ERROR!"),
1548 _("Old LyX file format found. "
1549 "Use LyX 0.10.x to read this!"));
1553 bool the_end = readLyXformat2(lex, par);
1555 // the_end was added in 213
1556 if (file_format < 213)
1560 WriteAlert(_("Warning!"),
1561 _("Reading of document is not complete"),
1562 _("Maybe the document is truncated"));
1564 } else { // "\\lyxformat" not found
1565 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1568 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1573 // Should probably be moved to somewhere else: BufferView? LyXView?
1574 bool Buffer::save() const
1576 // We don't need autosaves in the immediate future. (Asger)
1577 resetAutosaveTimers();
1581 if (lyxrc.make_backup) {
1582 s = fileName() + '~';
1583 if (!lyxrc.backupdir_path.empty())
1584 s = AddName(lyxrc.backupdir_path,
1585 subst(os::slashify_path(s),'/','!'));
1587 // Rename is the wrong way of making a backup,
1588 // this is the correct way.
1589 /* truss cp fil fil2:
1590 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1591 stat("LyXVC.lyx", 0xEFFFF688) = 0
1592 open("LyXVC.lyx", O_RDONLY) = 3
1593 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1594 fstat(4, 0xEFFFF508) = 0
1595 fstat(3, 0xEFFFF508) = 0
1596 read(3, " # T h i s f i l e w".., 8192) = 5579
1597 write(4, " # T h i s f i l e w".., 5579) = 5579
1598 read(3, 0xEFFFD4A0, 8192) = 0
1601 chmod("LyXVC3.lyx", 0100644) = 0
1602 lseek(0, 0, SEEK_CUR) = 46440
1606 // Should probably have some more error checking here.
1607 // Should be cleaned up in 0.13, at least a bit.
1608 // Doing it this way, also makes the inodes stay the same.
1609 // This is still not a very good solution, in particular we
1610 // might loose the owner of the backup.
1611 FileInfo finfo(fileName());
1612 if (finfo.exist()) {
1613 mode_t fmode = finfo.getMode();
1614 struct utimbuf times = {
1615 finfo.getAccessTime(),
1616 finfo.getModificationTime() };
1618 ifstream ifs(fileName().c_str());
1619 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1624 ::chmod(s.c_str(), fmode);
1626 if (::utime(s.c_str(), ×)) {
1627 lyxerr << "utime error." << endl;
1630 lyxerr << "LyX was not able to make "
1631 "backup copy. Beware." << endl;
1636 if (writeFile(fileName(), false)) {
1638 removeAutosaveFile(fileName());
1640 // Saving failed, so backup is not backup
1641 if (lyxrc.make_backup) {
1642 lyx::rename(s, fileName());
1650 // Returns false if unsuccesful
1651 bool Buffer::writeFile(string const & fname, bool flag) const
1653 // if flag is false writeFile will not create any GUI
1654 // warnings, only cerr.
1655 // Needed for autosave in background or panic save (Matthias 120496)
1657 if (read_only && (fname == filename)) {
1658 // Here we should come with a question if we should
1659 // perform the write anyway.
1661 lyxerr << _("Error! Document is read-only: ")
1664 WriteAlert(_("Error! Document is read-only: "),
1669 FileInfo finfo(fname);
1670 if (finfo.exist() && !finfo.writable()) {
1671 // Here we should come with a question if we should
1672 // try to do the save anyway. (i.e. do a chmod first)
1674 lyxerr << _("Error! Cannot write file: ")
1677 WriteFSAlert(_("Error! Cannot write file: "),
1682 ofstream ofs(fname.c_str());
1685 lyxerr << _("Error! Cannot open file: ")
1688 WriteFSAlert(_("Error! Cannot open file: "),
1694 // Use the standard "C" locale for file output.
1695 ofs.imbue(std::locale::classic());
1698 // The top of the file should not be written by params.
1700 // write out a comment in the top of the file
1701 ofs << '#' << LYX_DOCVERSION
1702 << " created this file. For more info see http://www.lyx.org/\n"
1703 << "\\lyxformat " << LYX_FORMAT << "\n";
1705 // now write out the buffer paramters.
1706 params.writeFile(ofs);
1708 Paragraph::depth_type depth = 0;
1710 // this will write out all the paragraphs
1711 // using recursive descent.
1712 paragraph->writeFile(this, ofs, params, depth);
1714 // Write marker that shows file is complete
1715 ofs << "\n\\the_end" << endl;
1719 // how to check if close went ok?
1720 // Following is an attempt... (BE 20001011)
1722 // good() returns false if any error occured, including some
1723 // formatting error.
1724 // bad() returns true if something bad happened in the buffer,
1725 // which should include file system full errors.
1732 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1734 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1744 string const Buffer::asciiParagraph(Paragraph const * par,
1745 unsigned int linelen) const
1747 ostringstream buffer;
1748 Paragraph::depth_type depth = 0;
1750 Paragraph::depth_type ltype_depth = 0;
1751 unsigned int currlinelen = 0;
1752 bool ref_printed = false;
1756 if (!par->previous()) {
1757 // begins or ends a deeper area ?
1758 if (depth != par->params().depth()) {
1759 if (par->params().depth() > depth) {
1760 while (par->params().depth() > depth) {
1764 while (par->params().depth() < depth) {
1770 // First write the layout
1771 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1772 if (tmp == "Itemize") {
1774 ltype_depth = depth + 1;
1775 } else if (tmp == "Enumerate") {
1777 ltype_depth = depth + 1;
1778 } else if (contains(tmp, "ection")) {
1780 ltype_depth = depth + 1;
1781 } else if (contains(tmp, "aragraph")) {
1783 ltype_depth = depth + 1;
1784 } else if (tmp == "Description") {
1786 ltype_depth = depth + 1;
1787 } else if (tmp == "Abstract") {
1790 } else if (tmp == "Bibliography") {
1798 /* maybe some vertical spaces */
1800 /* the labelwidthstring used in lists */
1804 /* some pagebreaks? */
1808 /* what about the alignment */
1810 lyxerr << "Should this ever happen?" << endl;
1813 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1814 if (!i && !noparbreak) {
1817 for (Paragraph::depth_type j = 0; j < depth; ++j)
1819 currlinelen = depth * 2;
1822 case 4: // (Sub)Paragraph
1823 case 5: // Description
1827 buffer << "Abstract\n\n";
1829 buffer << "Abstract: ";
1831 case 7: // Bibliography
1834 buffer << "References\n\n";
1836 buffer << "References: ";
1841 buffer << par->params().labelString() << " ";
1844 if (ltype_depth > depth) {
1845 for (Paragraph::depth_type j = ltype_depth - 1;
1848 currlinelen += (ltype_depth-depth)*2;
1852 char c = par->getUChar(params, i);
1856 case Paragraph::META_INSET:
1858 Inset const * inset = par->getInset(i);
1860 if (!inset->ascii(this, buffer)) {
1863 rsplit(buffer.str().c_str(),
1865 currlinelen += s.length();
1867 // to be sure it breaks paragraph
1868 currlinelen += linelen;
1874 case Paragraph::META_NEWLINE:
1877 for (Paragraph::depth_type j = 0;
1881 currlinelen = depth * 2;
1882 if (ltype_depth > depth) {
1883 for (Paragraph::depth_type j = ltype_depth;
1886 currlinelen += (ltype_depth - depth) * 2;
1890 case Paragraph::META_HFILL:
1899 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1900 (c == ' ') && ((i + 2) < par->size()))
1903 for (Paragraph::depth_type j = 0;
1906 currlinelen = depth * 2;
1907 if (ltype_depth > depth) {
1908 for (Paragraph::depth_type j = ltype_depth;
1911 currlinelen += (ltype_depth-depth)*2;
1913 } else if (c != '\0')
1916 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1921 return buffer.str().c_str();
1925 void Buffer::writeFileAscii(string const & fname, int linelen)
1927 ofstream ofs(fname.c_str());
1929 WriteFSAlert(_("Error: Cannot write file:"), fname);
1932 writeFileAscii(ofs, linelen);
1936 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1938 Paragraph * par = paragraph;
1940 ofs << asciiParagraph(par, linelen);
1948 void Buffer::makeLaTeXFile(string const & fname,
1949 string const & original_path,
1950 bool nice, bool only_body)
1952 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1954 niceFile = nice; // this will be used by Insetincludes.
1956 tex_code_break_column = lyxrc.ascii_linelen;
1958 LyXTextClass const & tclass =
1959 textclasslist.TextClass(params.textclass);
1961 ofstream ofs(fname.c_str());
1963 WriteFSAlert(_("Error: Cannot open file: "), fname);
1967 // validate the buffer.
1968 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1969 LaTeXFeatures features(params, tclass.numLayouts());
1971 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1974 // The starting paragraph of the coming rows is the
1975 // first paragraph of the document. (Asger)
1976 texrow.start(paragraph, 0);
1978 if (!only_body && nice) {
1979 ofs << "%% " LYX_DOCVERSION " created this file. "
1980 "For more info, see http://www.lyx.org/.\n"
1981 "%% Do not edit unless you really know what "
1986 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1987 // There are a few differences between nice LaTeX and usual files:
1988 // usual is \batchmode and has a
1989 // special input@path to allow the including of figures
1990 // with either \input or \includegraphics (what figinsets do).
1991 // batchmode is not set if there is a tex_code_break_column.
1992 // In this case somebody is interested in the generated LaTeX,
1993 // so this is OK. input@path is set when the actual parameter
1994 // original_path is set. This is done for usual tex-file, but not
1995 // for nice-latex-file. (Matthias 250696)
1998 // code for usual, NOT nice-latex-file
1999 ofs << "\\batchmode\n"; // changed
2000 // from \nonstopmode
2003 if (!original_path.empty()) {
2004 ofs << "\\makeatletter\n"
2005 << "\\def\\input@path{{"
2006 << os::external_path(original_path) << "/}}\n"
2007 << "\\makeatother\n";
2013 ofs << "\\documentclass";
2015 ostringstream options; // the document class options.
2017 if (tokenPos(tclass.opt_fontsize(),
2018 '|', params.fontsize) >= 0) {
2019 // only write if existing in list (and not default)
2020 options << params.fontsize << "pt,";
2024 if (!params.use_geometry &&
2025 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2026 switch (params.papersize) {
2027 case BufferParams::PAPER_A4PAPER:
2028 options << "a4paper,";
2030 case BufferParams::PAPER_USLETTER:
2031 options << "letterpaper,";
2033 case BufferParams::PAPER_A5PAPER:
2034 options << "a5paper,";
2036 case BufferParams::PAPER_B5PAPER:
2037 options << "b5paper,";
2039 case BufferParams::PAPER_EXECUTIVEPAPER:
2040 options << "executivepaper,";
2042 case BufferParams::PAPER_LEGALPAPER:
2043 options << "legalpaper,";
2049 if (params.sides != tclass.sides()) {
2050 switch (params.sides) {
2051 case LyXTextClass::OneSide:
2052 options << "oneside,";
2054 case LyXTextClass::TwoSides:
2055 options << "twoside,";
2061 if (params.columns != tclass.columns()) {
2062 if (params.columns == 2)
2063 options << "twocolumn,";
2065 options << "onecolumn,";
2068 if (!params.use_geometry
2069 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2070 options << "landscape,";
2072 // language should be a parameter to \documentclass
2074 ostringstream language_options;
2075 if (params.language->babel() == "hebrew"
2076 && default_language->babel() != "hebrew")
2077 // This seems necessary
2078 features.UsedLanguages.insert(default_language);
2080 if (lyxrc.language_use_babel ||
2081 params.language->lang() != lyxrc.default_language ||
2082 !features.UsedLanguages.empty()) {
2084 for (LaTeXFeatures::LanguageList::const_iterator cit =
2085 features.UsedLanguages.begin();
2086 cit != features.UsedLanguages.end(); ++cit)
2087 language_options << (*cit)->babel() << ',';
2088 language_options << params.language->babel();
2089 if (lyxrc.language_global_options)
2090 options << language_options.str() << ',';
2093 // the user-defined options
2094 if (!params.options.empty()) {
2095 options << params.options << ',';
2098 string strOptions(options.str().c_str());
2099 if (!strOptions.empty()){
2100 strOptions = strip(strOptions, ',');
2101 ofs << '[' << strOptions << ']';
2105 << textclasslist.LatexnameOfClass(params.textclass)
2108 // end of \documentclass defs
2110 // font selection must be done before loading fontenc.sty
2111 // The ae package is not needed when using OT1 font encoding.
2112 if (params.fonts != "default" &&
2113 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2114 ofs << "\\usepackage{" << params.fonts << "}\n";
2116 if (params.fonts == "ae") {
2117 ofs << "\\usepackage{aecompl}\n";
2121 // this one is not per buffer
2122 if (lyxrc.fontenc != "default") {
2123 ofs << "\\usepackage[" << lyxrc.fontenc
2128 if (params.inputenc == "auto") {
2129 string const doc_encoding =
2130 params.language->encoding()->LatexName();
2132 // Create a list with all the input encodings used
2134 set<string> encodings;
2135 for (LaTeXFeatures::LanguageList::const_iterator it =
2136 features.UsedLanguages.begin();
2137 it != features.UsedLanguages.end(); ++it)
2138 if ((*it)->encoding()->LatexName() != doc_encoding)
2139 encodings.insert((*it)->encoding()->LatexName());
2141 ofs << "\\usepackage[";
2142 std::copy(encodings.begin(), encodings.end(),
2143 std::ostream_iterator<string>(ofs, ","));
2144 ofs << doc_encoding << "]{inputenc}\n";
2146 } else if (params.inputenc != "default") {
2147 ofs << "\\usepackage[" << params.inputenc
2152 // At the very beginning the text parameters.
2153 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2154 switch (params.paperpackage) {
2155 case BufferParams::PACKAGE_A4:
2156 ofs << "\\usepackage{a4}\n";
2159 case BufferParams::PACKAGE_A4WIDE:
2160 ofs << "\\usepackage{a4wide}\n";
2163 case BufferParams::PACKAGE_WIDEMARGINSA4:
2164 ofs << "\\usepackage[widemargins]{a4}\n";
2169 if (params.use_geometry) {
2170 ofs << "\\usepackage{geometry}\n";
2172 ofs << "\\geometry{verbose";
2173 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2174 ofs << ",landscape";
2175 switch (params.papersize2) {
2176 case BufferParams::VM_PAPER_CUSTOM:
2177 if (!params.paperwidth.empty())
2178 ofs << ",paperwidth="
2179 << params.paperwidth;
2180 if (!params.paperheight.empty())
2181 ofs << ",paperheight="
2182 << params.paperheight;
2184 case BufferParams::VM_PAPER_USLETTER:
2185 ofs << ",letterpaper";
2187 case BufferParams::VM_PAPER_USLEGAL:
2188 ofs << ",legalpaper";
2190 case BufferParams::VM_PAPER_USEXECUTIVE:
2191 ofs << ",executivepaper";
2193 case BufferParams::VM_PAPER_A3:
2196 case BufferParams::VM_PAPER_A4:
2199 case BufferParams::VM_PAPER_A5:
2202 case BufferParams::VM_PAPER_B3:
2205 case BufferParams::VM_PAPER_B4:
2208 case BufferParams::VM_PAPER_B5:
2212 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2213 switch (lyxrc.default_papersize) {
2214 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2215 case BufferParams::PAPER_USLETTER:
2216 ofs << ",letterpaper";
2218 case BufferParams::PAPER_LEGALPAPER:
2219 ofs << ",legalpaper";
2221 case BufferParams::PAPER_EXECUTIVEPAPER:
2222 ofs << ",executivepaper";
2224 case BufferParams::PAPER_A3PAPER:
2227 case BufferParams::PAPER_A4PAPER:
2230 case BufferParams::PAPER_A5PAPER:
2233 case BufferParams::PAPER_B5PAPER:
2238 if (!params.topmargin.empty())
2239 ofs << ",tmargin=" << params.topmargin;
2240 if (!params.bottommargin.empty())
2241 ofs << ",bmargin=" << params.bottommargin;
2242 if (!params.leftmargin.empty())
2243 ofs << ",lmargin=" << params.leftmargin;
2244 if (!params.rightmargin.empty())
2245 ofs << ",rmargin=" << params.rightmargin;
2246 if (!params.headheight.empty())
2247 ofs << ",headheight=" << params.headheight;
2248 if (!params.headsep.empty())
2249 ofs << ",headsep=" << params.headsep;
2250 if (!params.footskip.empty())
2251 ofs << ",footskip=" << params.footskip;
2255 if (features.amsstyle
2256 && !tclass.provides(LyXTextClass::amsmath)) {
2257 ofs << "\\usepackage{amsmath}\n";
2261 if (tokenPos(tclass.opt_pagestyle(),
2262 '|', params.pagestyle) >= 0) {
2263 if (params.pagestyle == "fancy") {
2264 ofs << "\\usepackage{fancyhdr}\n";
2267 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2271 // We try to load babel late, in case it interferes
2272 // with other packages.
2274 string tmp = lyxrc.language_package;
2275 if (!lyxrc.language_global_options
2276 && tmp == "\\usepackage{babel}")
2277 tmp = string("\\usepackage[") +
2278 language_options.str().c_str() +
2284 if (params.secnumdepth != tclass.secnumdepth()) {
2285 ofs << "\\setcounter{secnumdepth}{"
2286 << params.secnumdepth
2290 if (params.tocdepth != tclass.tocdepth()) {
2291 ofs << "\\setcounter{tocdepth}{"
2297 if (params.paragraph_separation) {
2298 switch (params.defskip.kind()) {
2299 case VSpace::SMALLSKIP:
2300 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2302 case VSpace::MEDSKIP:
2303 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2305 case VSpace::BIGSKIP:
2306 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2308 case VSpace::LENGTH:
2309 ofs << "\\setlength\\parskip{"
2310 << params.defskip.length().asLatexString()
2313 default: // should never happen // Then delete it.
2314 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2319 ofs << "\\setlength\\parindent{0pt}\n";
2323 // Now insert the LyX specific LaTeX commands...
2325 // The optional packages;
2326 string preamble(features.getPackages());
2328 // this might be useful...
2329 preamble += "\n\\makeatletter\n";
2331 // Some macros LyX will need
2332 string tmppreamble(features.getMacros());
2334 if (!tmppreamble.empty()) {
2335 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2336 "LyX specific LaTeX commands.\n"
2337 + tmppreamble + '\n';
2340 // the text class specific preamble
2341 tmppreamble = features.getTClassPreamble();
2342 if (!tmppreamble.empty()) {
2343 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2344 "Textclass specific LaTeX commands.\n"
2345 + tmppreamble + '\n';
2348 /* the user-defined preamble */
2349 if (!params.preamble.empty()) {
2350 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2351 "User specified LaTeX commands.\n"
2352 + params.preamble + '\n';
2355 preamble += "\\makeatother\n";
2357 // Itemize bullet settings need to be last in case the user
2358 // defines their own bullets that use a package included
2359 // in the user-defined preamble -- ARRae
2360 // Actually it has to be done much later than that
2361 // since some packages like frenchb make modifications
2362 // at \begin{document} time -- JMarc
2364 for (int i = 0; i < 4; ++i) {
2365 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2366 if (bullets_def.empty())
2367 bullets_def="\\AtBeginDocument{\n";
2368 bullets_def += " \\renewcommand{\\labelitemi";
2370 // `i' is one less than the item to modify
2377 bullets_def += "ii";
2383 bullets_def += "}{" +
2384 params.user_defined_bullets[i].getText()
2389 if (!bullets_def.empty())
2390 preamble += bullets_def + "}\n\n";
2392 for (int j = countChar(preamble, '\n'); j-- ;) {
2399 ofs << "\\begin{document}\n";
2402 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2404 if (!lyxrc.language_auto_begin) {
2405 ofs << subst(lyxrc.language_command_begin, "$$lang",
2406 params.language->babel())
2411 latexParagraphs(ofs, paragraph, 0, texrow);
2413 // add this just in case after all the paragraphs
2417 if (!lyxrc.language_auto_end) {
2418 ofs << subst(lyxrc.language_command_end, "$$lang",
2419 params.language->babel())
2425 ofs << "\\end{document}\n";
2428 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2430 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2434 // Just to be sure. (Asger)
2437 // tex_code_break_column's value is used to decide
2438 // if we are in batchmode or not (within mathed_write()
2439 // in math_write.C) so we must set it to a non-zero
2440 // value when we leave otherwise we save incorrect .lyx files.
2441 tex_code_break_column = lyxrc.ascii_linelen;
2445 lyxerr << "File was not closed properly." << endl;
2448 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2453 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2455 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2456 Paragraph * endpar, TexRow & texrow) const
2458 bool was_title = false;
2459 bool already_title = false;
2462 while (par != endpar) {
2463 LyXLayout const & layout =
2464 textclasslist.Style(params.textclass,
2467 if (layout.intitle) {
2468 if (already_title) {
2469 lyxerr <<"Error in latexParagraphs: You"
2470 " should not mix title layouts"
2471 " with normal ones." << endl;
2474 } else if (was_title && !already_title) {
2475 ofs << "\\maketitle\n";
2477 already_title = true;
2481 if (layout.isEnvironment()) {
2482 par = par->TeXEnvironment(this, params, ofs, texrow);
2484 par = par->TeXOnePar(this, params, ofs, texrow, false);
2487 // It might be that we only have a title in this document
2488 if (was_title && !already_title) {
2489 ofs << "\\maketitle\n";
2495 bool Buffer::isLatex() const
2497 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2501 bool Buffer::isLinuxDoc() const
2503 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2507 bool Buffer::isLiterate() const
2509 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2513 bool Buffer::isDocBook() const
2515 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2519 bool Buffer::isSGML() const
2521 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2522 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2526 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2527 string const & latexname) const
2529 if (!latexname.empty() && latexname != "!-- --")
2530 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2531 //os << string(depth, ' ') << "<" << latexname << ">\n";
2535 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2536 string const & latexname) const
2538 if (!latexname.empty() && latexname != "!-- --")
2539 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2540 //os << string(depth, ' ') << "</" << latexname << ">\n";
2544 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2546 ofstream ofs(fname.c_str());
2549 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2553 niceFile = nice; // this will be used by included files.
2555 LyXTextClass const & tclass =
2556 textclasslist.TextClass(params.textclass);
2558 LaTeXFeatures features(params, tclass.numLayouts());
2563 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2566 string sgml_includedfiles=features.getIncludedFiles(fname);
2568 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2569 ofs << "<!doctype linuxdoc system>\n\n";
2571 ofs << "<!doctype linuxdoc system [ "
2572 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2575 if (params.options.empty())
2576 sgmlOpenTag(ofs, 0, top_element);
2578 string top = top_element;
2580 top += params.options;
2581 sgmlOpenTag(ofs, 0, top);
2585 ofs << "<!-- " << LYX_DOCVERSION
2586 << " created this file. For more info see http://www.lyx.org/"
2589 Paragraph::depth_type depth = 0; // paragraph depth
2590 Paragraph * par = paragraph;
2592 vector<string> environment_stack(5);
2595 LyXLayout const & style =
2596 textclasslist.Style(params.textclass,
2599 // treat <toc> as a special case for compatibility with old code
2600 if (par->getChar(0) == Paragraph::META_INSET) {
2601 Inset * inset = par->getInset(0);
2602 Inset::Code lyx_code = inset->lyxCode();
2603 if (lyx_code == Inset::TOC_CODE){
2604 string const temp = "toc";
2605 sgmlOpenTag(ofs, depth, temp);
2612 // environment tag closing
2613 for (; depth > par->params().depth(); --depth) {
2614 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2615 environment_stack[depth].erase();
2618 // write opening SGML tags
2619 switch (style.latextype) {
2620 case LATEX_PARAGRAPH:
2621 if (depth == par->params().depth()
2622 && !environment_stack[depth].empty()) {
2623 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2624 environment_stack[depth].erase();
2630 sgmlOpenTag(ofs, depth, style.latexname());
2635 linuxDocError(par, 0,
2636 _("Error : Wrong depth for"
2637 " LatexType Command.\n"));
2639 if (!environment_stack[depth].empty()){
2640 sgmlCloseTag(ofs, depth,
2641 environment_stack[depth]);
2645 environment_stack[depth].erase();
2646 sgmlOpenTag(ofs, depth, style.latexname());
2649 case LATEX_ENVIRONMENT:
2650 case LATEX_ITEM_ENVIRONMENT:
2651 if (depth == par->params().depth()
2652 && environment_stack[depth] != style.latexname()) {
2653 sgmlCloseTag(ofs, depth,
2654 environment_stack[depth]);
2655 environment_stack[depth].erase();
2657 if (depth < par->params().depth()) {
2658 depth = par->params().depth();
2659 environment_stack[depth].erase();
2661 if (environment_stack[depth] != style.latexname()) {
2663 sgmlOpenTag(ofs, depth, "p");
2665 sgmlOpenTag(ofs, depth, style.latexname());
2667 if (environment_stack.size() == depth + 1)
2668 environment_stack.push_back("!-- --");
2669 environment_stack[depth] = style.latexname();
2672 if (style.latexparam() == "CDATA")
2675 if (style.latextype == LATEX_ENVIRONMENT) break;
2677 if (style.labeltype == LABEL_MANUAL)
2682 sgmlOpenTag(ofs, depth + 1, item_name);
2685 sgmlOpenTag(ofs, depth, style.latexname());
2689 simpleLinuxDocOnePar(ofs, par, depth);
2694 // write closing SGML tags
2695 switch (style.latextype) {
2698 case LATEX_ENVIRONMENT:
2699 case LATEX_ITEM_ENVIRONMENT:
2700 if (style.latexparam() == "CDATA")
2704 sgmlCloseTag(ofs, depth, style.latexname());
2710 for (int i=depth; i >= 0; --i)
2711 sgmlCloseTag(ofs, depth, environment_stack[i]);
2715 sgmlCloseTag(ofs, 0, top_element);
2719 // How to check for successful close
2723 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2724 Paragraph::depth_type depth, int desc_on,
2727 Paragraph * tpar = par;
2729 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2731 tpar = tpar->next();
2734 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2735 "Caption").second) {
2736 sgmlOpenTag(os, depth + 1, inner_tag);
2738 simpleDocBookOnePar(os, extra_par, tpar,
2739 desc_on, depth + 2);
2740 sgmlCloseTag(os, depth+1, inner_tag);
2741 if (!extra_par.empty())
2747 // checks, if newcol chars should be put into this line
2748 // writes newline, if necessary.
2751 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2752 string::size_type newcol)
2755 if (colcount > lyxrc.ascii_linelen) {
2757 colcount = newcol; // assume write after this call
2772 string tag_name(PAR_TAG const & pt) {
2774 case NONE: return "!-- --";
2775 case TT: return "tt";
2776 case SF: return "sf";
2777 case BF: return "bf";
2778 case IT: return "it";
2779 case SL: return "sl";
2780 case EM: return "em";
2787 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2789 p1 = static_cast<PAR_TAG>(p1 | p2);
2794 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2796 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2804 // Handle internal paragraph parsing -- layout already processed.
2805 void Buffer::simpleLinuxDocOnePar(ostream & os,
2807 Paragraph::depth_type /*depth*/)
2809 LyXLayout const & style = textclasslist.Style(params.textclass,
2811 string::size_type char_line_count = 5; // Heuristic choice ;-)
2813 // gets paragraph main font
2816 if (style.labeltype == LABEL_MANUAL) {
2817 font_old = style.labelfont;
2820 font_old = style.font;
2824 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2825 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2826 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2829 stack<PAR_TAG> tag_state;
2830 // parsing main loop
2831 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2833 PAR_TAG tag_close = NONE;
2834 list < PAR_TAG > tag_open;
2836 LyXFont const font = par->getFont(params, i);
2838 if (font_old.family() != font.family()) {
2839 switch (family_type) {
2840 case LyXFont::SANS_FAMILY:
2843 case LyXFont::TYPEWRITER_FAMILY:
2850 family_type = font.family();
2852 switch (family_type) {
2853 case LyXFont::SANS_FAMILY:
2854 tag_open.push_back(SF);
2856 case LyXFont::TYPEWRITER_FAMILY:
2857 tag_open.push_back(TT);
2864 if (font_old.series() != font.series()) {
2865 switch (series_type) {
2866 case LyXFont::BOLD_SERIES:
2873 series_type = font.series();
2875 switch (series_type) {
2876 case LyXFont::BOLD_SERIES:
2877 tag_open.push_back(BF);
2885 if (font_old.shape() != font.shape()) {
2886 switch (shape_type) {
2887 case LyXFont::ITALIC_SHAPE:
2890 case LyXFont::SLANTED_SHAPE:
2897 shape_type = font.shape();
2899 switch (shape_type) {
2900 case LyXFont::ITALIC_SHAPE:
2901 tag_open.push_back(IT);
2903 case LyXFont::SLANTED_SHAPE:
2904 tag_open.push_back(SL);
2911 if (font_old.emph() != font.emph()) {
2912 if (font.emph() == LyXFont::ON) {
2913 tag_open.push_back(EM);
2922 list < PAR_TAG > temp;
2923 while(!tag_state.empty() && tag_close ) {
2924 PAR_TAG k = tag_state.top();
2926 os << "</" << tag_name(k) << ">";
2933 for(list< PAR_TAG >::const_iterator j = temp.begin();
2934 j != temp.end(); ++j) {
2936 os << "<" << tag_name(*j) << ">";
2939 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2940 j != tag_open.end(); ++j) {
2942 os << "<" << tag_name(*j) << ">";
2945 char c = par->getChar(i);
2947 if (c == Paragraph::META_INSET) {
2948 Inset * inset = par->getInset(i);
2949 inset->linuxdoc(this, os);
2954 if (style.latexparam() == "CDATA") {
2955 // "TeX"-Mode on == > SGML-Mode on.
2961 if (par->linuxDocConvertChar(c, sgml_string)
2962 && !style.free_spacing) {
2963 // in freespacing mode, spaces are
2964 // non-breaking characters
2965 if (desc_on) {// if char is ' ' then...
2968 linux_doc_line_break(os, char_line_count, 6);
2972 linux_doc_line_break(os, char_line_count, 1);
2977 char_line_count += sgml_string.length();
2983 while (!tag_state.empty()) {
2984 os << "</" << tag_name(tag_state.top()) << ">";
2988 // resets description flag correctly
2990 // <tag> not closed...
2991 linux_doc_line_break(os, char_line_count, 6);
2997 // Print an error message.
2998 void Buffer::linuxDocError(Paragraph * par, int pos,
2999 string const & message)
3001 // insert an error marker in text
3002 InsetError * new_inset = new InsetError(message);
3003 par->insertInset(pos, new_inset);
3007 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3009 ofstream ofs(fname.c_str());
3011 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3015 Paragraph * par = paragraph;
3017 niceFile = nice; // this will be used by Insetincludes.
3019 LyXTextClass const & tclass =
3020 textclasslist.TextClass(params.textclass);
3022 LaTeXFeatures features(params, tclass.numLayouts());
3027 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3030 string sgml_includedfiles = features.getIncludedFiles(fname);
3032 ofs << "<!doctype " << top_element
3033 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3035 if (params.preamble.empty() && sgml_includedfiles.empty())
3038 ofs << "\n [ " << params.preamble
3039 << sgml_includedfiles << " \n]>\n\n";
3042 string top = top_element;
3044 top += params.language->code();
3047 if (!params.options.empty()) {
3049 top += params.options;
3051 sgmlOpenTag(ofs, 0, top);
3053 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3054 << "\n See http://www.lyx.org/ for more information -->\n";
3056 vector<string> environment_stack(10);
3057 vector<string> environment_inner(10);
3058 vector<string> command_stack(10);
3060 bool command_flag = false;
3061 Paragraph::depth_type command_depth = 0;
3062 Paragraph::depth_type command_base = 0;
3063 Paragraph::depth_type cmd_depth = 0;
3064 Paragraph::depth_type depth = 0; // paragraph depth
3067 string command_name;
3073 int desc_on = 0; // description mode
3075 LyXLayout const & style =
3076 textclasslist.Style(params.textclass,
3079 // environment tag closing
3080 for (; depth > par->params().depth(); --depth) {
3081 if (environment_inner[depth] != "!-- --") {
3082 item_name = "listitem";
3083 sgmlCloseTag(ofs, command_depth + depth,
3085 if (environment_inner[depth] == "varlistentry")
3086 sgmlCloseTag(ofs, depth+command_depth,
3087 environment_inner[depth]);
3089 sgmlCloseTag(ofs, depth + command_depth,
3090 environment_stack[depth]);
3091 environment_stack[depth].erase();
3092 environment_inner[depth].erase();
3095 if (depth == par->params().depth()
3096 && environment_stack[depth] != style.latexname()
3097 && !environment_stack[depth].empty()) {
3098 if (environment_inner[depth] != "!-- --") {
3099 item_name= "listitem";
3100 sgmlCloseTag(ofs, command_depth+depth,
3102 if (environment_inner[depth] == "varlistentry")
3104 depth + command_depth,
3105 environment_inner[depth]);
3108 sgmlCloseTag(ofs, depth + command_depth,
3109 environment_stack[depth]);
3111 environment_stack[depth].erase();
3112 environment_inner[depth].erase();
3115 // Write opening SGML tags.
3116 switch (style.latextype) {
3117 case LATEX_PARAGRAPH:
3118 sgmlOpenTag(ofs, depth + command_depth,
3124 linuxDocError(par, 0,
3125 _("Error : Wrong depth for "
3126 "LatexType Command.\n"));
3128 command_name = style.latexname();
3130 sgmlparam = style.latexparam();
3131 c_params = split(sgmlparam, c_depth,'|');
3133 cmd_depth = lyx::atoi(c_depth);
3136 if (cmd_depth < command_base) {
3137 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3138 sgmlCloseTag(ofs, j, command_stack[j]);
3139 command_depth = command_base = cmd_depth;
3140 } else if (cmd_depth <= command_depth) {
3141 for (int j = command_depth; j >= int(cmd_depth); --j)
3142 sgmlCloseTag(ofs, j, command_stack[j]);
3143 command_depth = cmd_depth;
3145 command_depth = cmd_depth;
3147 command_depth = command_base = cmd_depth;
3148 command_flag = true;
3150 if (command_stack.size() == command_depth + 1)
3151 command_stack.push_back(string());
3152 command_stack[command_depth] = command_name;
3154 // treat label as a special case for
3155 // more WYSIWYM handling.
3156 if (par->getChar(0) == Paragraph::META_INSET) {
3157 Inset * inset = par->getInset(0);
3158 Inset::Code lyx_code = inset->lyxCode();
3159 if (lyx_code == Inset::LABEL_CODE){
3160 command_name += " id=\"";
3161 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3162 command_name += "\"";
3167 sgmlOpenTag(ofs, depth + command_depth, command_name);
3168 if (c_params.empty())
3169 item_name = "title";
3171 item_name = c_params;
3172 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3175 case LATEX_ENVIRONMENT:
3176 case LATEX_ITEM_ENVIRONMENT:
3177 if (depth < par->params().depth()) {
3178 depth = par->params().depth();
3179 environment_stack[depth].erase();
3182 if (environment_stack[depth] != style.latexname()) {
3183 if(environment_stack.size() == depth + 1) {
3184 environment_stack.push_back("!-- --");
3185 environment_inner.push_back("!-- --");
3187 environment_stack[depth] = style.latexname();
3188 environment_inner[depth] = "!-- --";
3189 sgmlOpenTag(ofs, depth + command_depth,
3190 environment_stack[depth]);
3192 if (environment_inner[depth] != "!-- --") {
3193 item_name= "listitem";
3195 command_depth + depth,
3197 if (environment_inner[depth] == "varlistentry")
3199 depth + command_depth,
3200 environment_inner[depth]);
3204 if (style.latextype == LATEX_ENVIRONMENT) {
3205 if (!style.latexparam().empty()) {
3206 if(style.latexparam() == "CDATA")
3209 sgmlOpenTag(ofs, depth + command_depth,
3210 style.latexparam());
3215 desc_on = (style.labeltype == LABEL_MANUAL);
3218 environment_inner[depth]= "varlistentry";
3220 environment_inner[depth]= "listitem";
3222 sgmlOpenTag(ofs, depth + 1 + command_depth,
3223 environment_inner[depth]);
3227 sgmlOpenTag(ofs, depth + 1 + command_depth,
3231 sgmlOpenTag(ofs, depth + 1 + command_depth,
3236 sgmlOpenTag(ofs, depth + command_depth,
3242 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3243 depth + 1 + command_depth);
3247 // write closing SGML tags
3248 switch (style.latextype) {
3250 if (c_params.empty())
3254 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3256 case LATEX_ENVIRONMENT:
3257 if (!style.latexparam().empty()) {
3258 if(style.latexparam() == "CDATA")
3261 sgmlCloseTag(ofs, depth + command_depth,
3262 style.latexparam());
3265 case LATEX_ITEM_ENVIRONMENT:
3266 if (desc_on == 1) break;
3268 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3270 case LATEX_PARAGRAPH:
3271 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3274 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3280 for (int d = depth; d >= 0; --d) {
3281 if (!environment_stack[depth].empty()) {
3282 if (environment_inner[depth] != "!-- --") {
3283 item_name = "listitem";
3284 sgmlCloseTag(ofs, command_depth + depth,
3286 if (environment_inner[depth] == "varlistentry")
3287 sgmlCloseTag(ofs, depth + command_depth,
3288 environment_inner[depth]);
3291 sgmlCloseTag(ofs, depth + command_depth,
3292 environment_stack[depth]);
3296 for (int j = command_depth; j >= 0 ; --j)
3297 if (!command_stack[j].empty())
3298 sgmlCloseTag(ofs, j, command_stack[j]);
3301 sgmlCloseTag(ofs, 0, top_element);
3304 // How to check for successful close
3308 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3309 Paragraph * par, int & desc_on,
3310 Paragraph::depth_type depth) const
3312 bool emph_flag = false;
3314 LyXLayout const & style = textclasslist.Style(params.textclass,
3317 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3319 int char_line_count = depth;
3320 //if (!style.free_spacing)
3321 // os << string(depth,' ');
3323 // parsing main loop
3324 for (Paragraph::size_type i = 0;
3325 i < par->size(); ++i) {
3326 LyXFont font = par->getFont(params, i);
3328 // handle <emphasis> tag
3329 if (font_old.emph() != font.emph()) {
3330 if (font.emph() == LyXFont::ON) {
3334 os << "</emphasis>";
3339 char c = par->getChar(i);
3341 if (c == Paragraph::META_INSET) {
3342 Inset * inset = par->getInset(i);
3344 inset->docBook(this, ost);
3345 string tmp_out = ost.str().c_str();
3348 // This code needs some explanation:
3349 // Two insets are treated specially
3350 // label if it is the first element in a command paragraph
3352 // graphics inside tables or figure floats can't go on
3353 // title (the equivalente in latex for this case is caption
3354 // and title should come first
3357 if (desc_on!= 3 || i!= 0) {
3358 if (!tmp_out.empty() && tmp_out[0] == '@') {
3360 extra += frontStrip(tmp_out, '@');
3362 os << frontStrip(tmp_out, '@');
3369 if (par->linuxDocConvertChar(c, sgml_string)
3370 && !style.free_spacing) { // in freespacing
3372 // non-breaking characters
3376 os << "\n</term><listitem><para>";
3389 os << "</emphasis>";
3392 // resets description flag correctly
3394 // <term> not closed...
3397 if(style.free_spacing) os << '\n';
3401 // This should be enabled when the Chktex class is implemented. (Asger)
3402 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3403 // Other flags: -wall -v0 -x
3404 int Buffer::runChktex()
3406 if (!users->text) return 0;
3408 users->owner()->prohibitInput();
3410 // get LaTeX-Filename
3411 string const name = getLatexName();
3412 string path = OnlyPath(filename);
3414 string const org_path = path;
3415 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3419 Path p(path); // path to LaTeX file
3420 users->owner()->message(_("Running chktex..."));
3422 // Remove all error insets
3423 bool const removedErrorInsets = users->removeAutoInsets();
3425 // Generate the LaTeX file if neccessary
3426 makeLaTeXFile(name, org_path, false);
3429 Chktex chktex(lyxrc.chktex_command, name, filepath);
3430 int res = chktex.run(terr); // run chktex
3433 WriteAlert(_("chktex did not work!"),
3434 _("Could not run with file:"), name);
3435 } else if (res > 0) {
3436 // Insert all errors as errors boxes
3437 users->insertErrors(terr);
3440 // if we removed error insets before we ran chktex or if we inserted
3441 // error insets after we ran chktex, this must be run:
3442 if (removedErrorInsets || res){
3446 users->owner()->allowInput();
3452 void Buffer::validate(LaTeXFeatures & features) const
3454 Paragraph * par = paragraph;
3455 LyXTextClass const & tclass =
3456 textclasslist.TextClass(params.textclass);
3458 // AMS Style is at document level
3459 features.amsstyle = (params.use_amsmath ||
3460 tclass.provides(LyXTextClass::amsmath));
3463 // We don't use "lyxerr.debug" because of speed. (Asger)
3464 if (lyxerr.debugging(Debug::LATEX))
3465 lyxerr << "Paragraph: " << par << endl;
3467 // Now just follow the list of paragraphs and run
3468 // validate on each of them.
3469 par->validate(features);
3471 // and then the next paragraph
3475 // the bullet shapes are buffer level not paragraph level
3476 // so they are tested here
3477 for (int i = 0; i < 4; ++i) {
3478 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3479 int const font = params.user_defined_bullets[i].getFont();
3481 int const c = params
3482 .user_defined_bullets[i]
3489 features.latexsym = true;
3491 } else if (font == 1) {
3492 features.amssymb = true;
3493 } else if ((font >= 2 && font <= 5)) {
3494 features.pifont = true;
3499 if (lyxerr.debugging(Debug::LATEX)) {
3500 features.showStruct();
3505 void Buffer::setPaperStuff()
3507 params.papersize = BufferParams::PAPER_DEFAULT;
3508 char const c1 = params.paperpackage;
3509 if (c1 == BufferParams::PACKAGE_NONE) {
3510 char const c2 = params.papersize2;
3511 if (c2 == BufferParams::VM_PAPER_USLETTER)
3512 params.papersize = BufferParams::PAPER_USLETTER;
3513 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3514 params.papersize = BufferParams::PAPER_LEGALPAPER;
3515 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3516 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3517 else if (c2 == BufferParams::VM_PAPER_A3)
3518 params.papersize = BufferParams::PAPER_A3PAPER;
3519 else if (c2 == BufferParams::VM_PAPER_A4)
3520 params.papersize = BufferParams::PAPER_A4PAPER;
3521 else if (c2 == BufferParams::VM_PAPER_A5)
3522 params.papersize = BufferParams::PAPER_A5PAPER;
3523 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3524 (c2 == BufferParams::VM_PAPER_B5))
3525 params.papersize = BufferParams::PAPER_B5PAPER;
3526 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3527 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3528 params.papersize = BufferParams::PAPER_A4PAPER;
3532 // This function should be in Buffer because it's a buffer's property (ale)
3533 string const Buffer::getIncludeonlyList(char delim)
3536 for (inset_iterator it = inset_iterator_begin();
3537 it != inset_iterator_end(); ++it) {
3538 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3539 InsetInclude * insetinc =
3540 static_cast<InsetInclude *>(*it);
3541 if (insetinc->isIncludeOnly()) {
3544 lst += insetinc->getRelFileBaseName();
3548 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3553 vector<string> const Buffer::getLabelList()
3555 /// if this is a child document and the parent is already loaded
3556 /// Use the parent's list instead [ale990407]
3557 if (!params.parentname.empty()
3558 && bufferlist.exists(params.parentname)) {
3559 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3561 return tmp->getLabelList();
3564 vector<string> label_list;
3565 for (inset_iterator it = inset_iterator_begin();
3566 it != inset_iterator_end(); ++it) {
3567 vector<string> const l = (*it)->getLabelList();
3568 label_list.insert(label_list.end(), l.begin(), l.end());
3574 Buffer::Lists const Buffer::getLists() const
3577 Paragraph * par = paragraph;
3579 LyXTextClassList::size_type cap;
3580 boost::tie(found, cap) = textclasslist
3581 .NumberOfLayout(params.textclass, "Caption");
3584 char const labeltype =
3585 textclasslist.Style(params.textclass,
3586 par->getLayout()).labeltype;
3588 if (labeltype >= LABEL_COUNTER_CHAPTER
3589 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3590 // insert this into the table of contents
3591 SingleList & item = l["TOC"];
3594 textclasslist.TextClass(params.textclass).maxcounter());
3595 item.push_back(TocItem(par, depth, par->asString(this, true)));
3597 // For each paragrph, traverse its insets and look for
3601 Paragraph::inset_iterator it =
3602 par->inset_iterator_begin();
3603 Paragraph::inset_iterator end =
3604 par->inset_iterator_end();
3606 for (; it != end; ++it) {
3607 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3609 static_cast<InsetFloat*>(*it);
3611 string const type = il->type();
3613 // Now find the caption in the float...
3614 // We now tranverse the paragraphs of
3616 Paragraph * tmp = il->inset.paragraph();
3618 if (tmp->layout == cap) {
3619 SingleList & item = l[type];
3621 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3622 item.push_back(TocItem(tmp, 0 , str));
3629 lyxerr << "caption not found" << endl;
3638 // This is also a buffer property (ale)
3639 vector<pair<string, string> > const Buffer::getBibkeyList()
3641 /// if this is a child document and the parent is already loaded
3642 /// Use the parent's list instead [ale990412]
3643 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3644 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3646 return tmp->getBibkeyList();
3649 vector<pair<string, string> > keys;
3650 Paragraph * par = paragraph;
3653 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3654 par->asString(this, false)));
3658 // Might be either using bibtex or a child has bibliography
3660 for (inset_iterator it = inset_iterator_begin();
3661 it != inset_iterator_end(); ++it) {
3662 // Search for Bibtex or Include inset
3663 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3664 vector<pair<string,string> > tmp =
3665 static_cast<InsetBibtex*>(*it)->getKeys(this);
3666 keys.insert(keys.end(), tmp.begin(), tmp.end());
3667 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3668 vector<pair<string,string> > const tmp =
3669 static_cast<InsetInclude*>(*it)->getKeys();
3670 keys.insert(keys.end(), tmp.begin(), tmp.end());
3679 bool Buffer::isDepClean(string const & name) const
3681 DEPCLEAN * item = dep_clean;
3682 while (item && item->master != name)
3684 if (!item) return true;
3689 void Buffer::markDepClean(string const & name)
3692 dep_clean = new DEPCLEAN;
3693 dep_clean->clean = true;
3694 dep_clean->master = name;
3695 dep_clean->next = 0;
3697 DEPCLEAN * item = dep_clean;
3698 while (item && item->master != name)
3703 item = new DEPCLEAN;
3705 item->master = name;
3712 bool Buffer::dispatch(string const & command)
3714 // Split command string into command and argument
3716 string line = frontStrip(command);
3717 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3719 return dispatch(lyxaction.LookupFunc(cmd), arg);
3723 bool Buffer::dispatch(int action, string const & argument)
3725 bool dispatched = true;
3728 Exporter::Export(this, argument, false);
3738 void Buffer::resizeInsets(BufferView * bv)
3740 /// then remove all LyXText in text-insets
3741 Paragraph * par = paragraph;
3742 for (; par; par = par->next()) {
3743 par->resizeInsetsLyXText(bv);
3748 void Buffer::redraw()
3755 void Buffer::changeLanguage(Language const * from, Language const * to)
3758 Paragraph * par = paragraph;
3760 par->changeLanguage(params, from, to);
3766 bool Buffer::isMultiLingual()
3768 Paragraph * par = paragraph;
3770 if (par->isMultiLingual(params))
3778 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3779 Paragraph::size_type pos)
3782 it = par->InsetIterator(pos);
3783 if (it == par->inset_iterator_end()) {
3790 void Buffer::inset_iterator::setParagraph()
3793 it = par->inset_iterator_begin();
3794 if (it != par->inset_iterator_end())
3799 // We maintain an invariant that whenever par = 0 then it = 0
3803 Inset * Buffer::getInsetFromID(int id_arg) const
3805 for (inset_iterator it = inset_const_iterator_begin();
3806 it != inset_const_iterator_end(); ++it)
3808 if ((*it)->id() == id_arg)
3810 Inset * in = (*it)->getInsetFromID(id_arg);
3818 Paragraph * Buffer::getParFromID(int id) const
3820 if (id < 0) return 0;
3821 Paragraph * par = paragraph;
3823 if (par->id() == id) {
3826 Paragraph * tmp = par->getParFromID(id);