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>
36 #pragma implementation
40 #include "bufferlist.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
46 #include "tex-strings.h"
48 #include "bufferview_funcs.h"
51 #include "mathed/formulamacro.h"
52 #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"
84 #include "support/textutils.h"
85 #include "support/filetools.h"
86 #include "support/path.h"
87 #include "support/os.h"
92 #include "LaTeXFeatures.h"
93 #include "support/syscall.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
100 #include "lyx_gui_misc.h" // WarnReadonly()
101 #include "frontends/Dialogs.h"
102 #include "encoding.h"
103 #include "exporter.h"
104 #include "Lsstream.h"
105 #include "converter.h"
106 #include "BufferView.h"
107 #include "ParagraphParameters.h"
117 using std::make_pair;
125 // all these externs should eventually be removed.
126 extern BufferList bufferlist;
128 extern LyXAction lyxaction;
132 const int LYX_FORMAT = 220;
136 extern int tex_code_break_column;
139 Buffer::Buffer(string const & file, bool ronly)
141 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
143 filepath = OnlyPath(file);
152 if (read_only || (lyxrc.use_tempdir)) {
153 tmppath = CreateBufferTmpDir();
154 } else tmppath.erase();
160 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
161 // here the buffer should take care that it is
162 // saved properly, before it goes into the void.
164 // make sure that views using this buffer
169 if (!tmppath.empty()) {
170 DestroyBufferTmpDir(tmppath);
173 Paragraph * par = paragraph;
176 tmppar = par->next();
184 string const Buffer::getLatexName(bool no_path) const
186 string name = ChangeExtension(MakeLatexName(filename), ".tex");
188 return OnlyFilename(name);
194 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
196 string const filename = getLatexName(false);
198 if (filename.empty())
199 return make_pair(Buffer::latexlog, string());
201 string path = OnlyPath(filename);
203 if (lyxrc.use_tempdir || !IsDirWriteable(path))
206 string const fname = AddName(path,
207 OnlyFilename(ChangeExtension(filename,
210 AddName(path, OnlyFilename(
211 ChangeExtension(filename,
212 formats.extension("literate") + ".out")));
214 // If no Latex log or Build log is newer, show Build log
216 FileInfo const f_fi(fname);
217 FileInfo const b_fi(bname);
220 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
221 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
222 return make_pair(Buffer::buildlog, bname);
224 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
225 return make_pair(Buffer::latexlog, fname);
229 void Buffer::setReadonly(bool flag)
231 if (read_only != flag) {
234 users->owner()->getDialogs()->updateBufferDependent(false);
237 WarnReadonly(filename);
242 bool Buffer::saveParamsAsDefaults() // const
244 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
246 Buffer defaults = Buffer(fname);
248 // Use the current buffer's parameters as default
249 defaults.params = params;
251 // add an empty paragraph. Is this enough?
252 defaults.paragraph = new Paragraph;
254 return defaults.writeFile(defaults.filename, false);
258 /// Update window titles of all users
259 // Should work on a list
260 void Buffer::updateTitles() const
262 if (users) users->owner()->updateWindowTitle();
266 /// Reset autosave timer of all users
267 // Should work on a list
268 void Buffer::resetAutosaveTimers() const
270 if (users) 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) {
298 std::stack<ErtComp> ert_stack;
305 #warning And _why_ is this here? (Lgb)
308 // candidate for move to BufferView
309 // (at least some parts in the beginning of the func)
312 // changed to be public and have one parameter
313 // if par = 0 normal behavior
314 // else insert behavior
315 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
316 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
319 #ifndef NO_COMPABILITY
320 ert_comp.contents.erase();
321 ert_comp.active = false;
322 ert_comp.in_tabular = false;
325 Paragraph::depth_type depth = 0;
326 bool the_end_read = false;
328 Paragraph * first_par = 0;
329 LyXFont font(LyXFont::ALL_INHERIT, params.language);
330 if (file_format < 216 && params.language->lang() == "hebrew")
331 font.setLanguage(default_language);
336 // We are inserting into an existing document
337 users->text->breakParagraph(users);
338 first_par = users->text->firstParagraph();
341 // We don't want to adopt the parameters from the
342 // document we insert, so we skip until the text begins:
345 string const pretoken = lex.getString();
346 if (pretoken == "\\layout") {
347 lex.pushToken(pretoken);
355 string const token = lex.getString();
357 if (token.empty()) continue;
359 lyxerr[Debug::PARSER] << "Handling token: `"
360 << token << "'" << endl;
363 parseSingleLyXformat2Token(lex, par, first_par,
371 paragraph = first_par;
373 if (unknown_layouts > 0) {
374 string s = _("Couldn't set the layout for ");
375 if (unknown_layouts == 1) {
376 s += _("one paragraph");
378 s += tostr(unknown_layouts);
379 s += _(" paragraphs");
381 WriteAlert(_("Textclass Loading Error!"), s,
382 _("When reading " + fileName()));
389 #ifndef NO_COMPABILITY
390 void Buffer::insertErtContents(Paragraph * par, int & pos,
391 LyXFont const & font, bool set_inactive)
393 if (!ert_comp.contents.empty()) {
394 lyxerr[Debug::INSETS] << "ERT contents:\n"
395 << ert_comp.contents << endl;
396 Inset * inset = new InsetERT(ert_comp.contents, true);
397 par->insertInset(pos++, inset, font);
398 ert_comp.contents.erase();
401 ert_comp.active = false;
408 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
409 Paragraph *& first_par,
410 string const & token, int & pos,
411 Paragraph::depth_type & depth,
415 bool the_end_read = false;
416 #ifndef NO_COMPABILITY
417 #ifndef NO_PEXTRA_REALLY
418 // This is super temporary but is needed to get the compability
419 // mode for minipages work correctly together with new tabulars.
420 static int call_depth;
422 bool checkminipage = false;
423 static Paragraph * minipar;
424 static Paragraph * parBeforeMinipage;
427 if (token[0] != '\\') {
428 #ifndef NO_COMPABILITY
429 if (ert_comp.active) {
430 ert_comp.contents += token;
433 for (string::const_iterator cit = token.begin();
434 cit != token.end(); ++cit) {
435 par->insertChar(pos, (*cit), font);
438 #ifndef NO_COMPABILITY
441 } else if (token == "\\i") {
442 Inset * inset = new InsetLatexAccent;
443 inset->read(this, lex);
444 par->insertInset(pos, inset, font);
446 } else if (token == "\\layout") {
447 #ifndef NO_COMPABILITY
448 ert_comp.in_tabular = false;
450 insertErtContents(par, pos, font);
453 string const layoutname = lex.getString();
454 pair<bool, LyXTextClass::LayoutList::size_type> pp
455 = textclasslist.NumberOfLayout(params.textclass,
458 #ifndef NO_COMPABILITY
459 if (compare_no_case(layoutname, "latex") == 0) {
460 ert_comp.active = true;
464 // The is the compability reading of layout caption.
465 // It can be removed in LyX version 1.3.0. (Lgb)
466 if (compare_no_case(layoutname, "caption") == 0) {
467 // We expect that the par we are now working on is
468 // really inside a InsetText inside a InsetFloat.
469 // We also know that captions can only be
470 // one paragraph. (Lgb)
472 // We should now read until the next "\layout"
474 // This is probably not good enough, what if the
475 // caption is the last par in the document (Lgb)
476 istream & ist = lex.getStream();
482 if (prefixIs(line, "\\layout")) {
486 if (prefixIs(line, "\\begin_inset"))
488 if (prefixIs(line, "\\end_inset")) {
499 // Now we should have the whole layout in ss
500 // we should now be able to give this to the
502 ss << "\\end_inset\n";
504 // This seems like a bug in stringstream.
505 // We really should be able to use ss
507 istringstream is(ss.str());
509 tmplex.setStream(is);
510 Inset * inset = new InsetCaption;
511 inset->Read(this, tmplex);
512 par->InsertInset(pos, inset, font);
519 par = new Paragraph(par);
523 par->layout = pp.second;
524 #ifndef NO_COMPABILITY
525 } else if (ert_comp.active) {
530 // use default layout "Standard" (0)
533 string const s = _("Layout had to be changed from\n")
534 + layoutname + _(" to ")
535 + textclasslist.NameOfLayout(params.textclass, par->layout);
536 InsetError * new_inset = new InsetError(s);
537 par->insertInset(0, new_inset);
539 // Test whether the layout is obsolete.
540 LyXLayout const & layout =
541 textclasslist.Style(params.textclass,
543 if (!layout.obsoleted_by().empty())
544 par->layout = textclasslist
545 .NumberOfLayout(params.textclass,
546 layout.obsoleted_by())
548 par->params().depth(depth);
549 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
550 if (file_format < 216
551 && params.language->lang() == "hebrew")
552 font.setLanguage(default_language);
557 #ifndef NO_COMPABILITY
558 } else if (token == "\\begin_float") {
559 insertErtContents(par, pos, font);
560 //insertErtContents(par, pos, font, false);
561 //ert_stack.push(ert_comp);
562 //ert_comp = ErtComp();
564 // This is the compability reader. It can be removed in
565 // LyX version 1.3.0. (Lgb)
567 string const tmptok = lex.getString();
568 //lyxerr << "old float: " << tmptok << endl;
571 stringstream old_float;
573 if (tmptok == "footnote") {
574 inset = new InsetFoot;
575 old_float << "collapsed true\n";
576 } else if (tmptok == "margin") {
577 inset = new InsetMarginal;
578 old_float << "collapsed true\n";
579 } else if (tmptok == "fig") {
580 inset = new InsetFloat("figure");
581 old_float << "placement htbp\n"
583 << "collapsed false\n";
584 } else if (tmptok == "tab") {
585 inset = new InsetFloat("table");
586 old_float << "placement htbp\n"
588 << "collapsed false\n";
589 } else if (tmptok == "alg") {
590 inset = new InsetFloat("algorithm");
591 old_float << "placement htbp\n"
593 << "collapsed false\n";
594 } else if (tmptok == "wide-fig") {
595 inset = new InsetFloat("figure");
596 //InsetFloat * tmp = new InsetFloat("figure");
599 old_float << "placement htbp\n"
601 << "collapsed false\n";
602 } else if (tmptok == "wide-tab") {
603 inset = new InsetFloat("table");
604 //InsetFloat * tmp = new InsetFloat("table");
607 old_float << "placement htbp\n"
609 << "collapsed false\n";
613 #ifndef NO_PEXTRA_REALLY
616 return false; // no end read yet
619 // Here we need to check for \end_deeper and handle that
620 // before we do the footnote parsing.
621 // This _is_ a hack! (Lgb)
624 string const tmp = lex.getString();
625 if (tmp == "\\end_deeper") {
626 //lyxerr << "\\end_deeper caught!" << endl;
628 lex.printError("\\end_deeper: "
629 "depth is already null");
634 old_float << tmp << ' ';
639 old_float << lex.getLongString("\\end_float")
640 << "\n\\end_inset\n";
641 //lyxerr << "Float Body:\n" << old_float.str() << endl;
642 // That this does not work seems like a bug
643 // in stringstream. (Lgb)
644 istringstream istr(old_float.str());
646 nylex.setStream(istr);
647 inset->read(this, nylex);
648 par->insertInset(pos, inset, font);
650 insertErtContents(par, pos, font);
652 } else if (token == "\\begin_deeper") {
654 } else if (token == "\\end_deeper") {
656 lex.printError("\\end_deeper: "
657 "depth is already null");
661 } else if (token == "\\begin_preamble") {
662 params.readPreamble(lex);
663 } else if (token == "\\textclass") {
665 pair<bool, LyXTextClassList::size_type> pp =
666 textclasslist.NumberOfClass(lex.getString());
668 params.textclass = pp.second;
670 WriteAlert(string(_("Textclass error")),
671 string(_("The document uses an unknown textclass \"")) +
672 lex.getString() + string("\"."),
673 string(_("LyX will not be able to produce output correctly.")));
674 params.textclass = 0;
676 if (!textclasslist.Load(params.textclass)) {
677 // if the textclass wasn't loaded properly
678 // we need to either substitute another
679 // or stop loading the file.
680 // I can substitute but I don't see how I can
681 // stop loading... ideas?? ARRae980418
682 WriteAlert(_("Textclass Loading Error!"),
683 string(_("Can't load textclass ")) +
684 textclasslist.NameOfClass(params.textclass),
685 _("-- substituting default"));
686 params.textclass = 0;
688 } else if (token == "\\options") {
690 params.options = lex.getString();
691 } else if (token == "\\language") {
692 params.readLanguage(lex);
693 } else if (token == "\\fontencoding") {
695 } else if (token == "\\inputencoding") {
697 params.inputenc = lex.getString();
698 } else if (token == "\\graphics") {
699 params.readGraphicsDriver(lex);
700 } else if (token == "\\fontscheme") {
702 params.fonts = lex.getString();
703 } else if (token == "\\noindent") {
704 par->params().noindent(true);
705 } else if (token == "\\fill_top") {
706 par->params().spaceTop(VSpace(VSpace::VFILL));
707 } else if (token == "\\fill_bottom") {
708 par->params().spaceBottom(VSpace(VSpace::VFILL));
709 } else if (token == "\\line_top") {
710 par->params().lineTop(true);
711 } else if (token == "\\line_bottom") {
712 par->params().lineBottom(true);
713 } else if (token == "\\pagebreak_top") {
714 par->params().pagebreakTop(true);
715 } else if (token == "\\pagebreak_bottom") {
716 par->params().pagebreakBottom(true);
717 } else if (token == "\\start_of_appendix") {
718 par->params().startOfAppendix(true);
719 } else if (token == "\\paragraph_separation") {
720 int tmpret = lex.findToken(string_paragraph_separation);
721 if (tmpret == -1) ++tmpret;
722 if (tmpret != LYX_LAYOUT_DEFAULT)
723 params.paragraph_separation =
724 static_cast<BufferParams::PARSEP>(tmpret);
725 } else if (token == "\\defskip") {
727 params.defskip = VSpace(lex.getString());
728 } else if (token == "\\epsfig") { // obsolete
729 // Indeed it is obsolete, but we HAVE to be backwards
730 // compatible until 0.14, because otherwise all figures
731 // in existing documents are irretrivably lost. (Asger)
732 params.readGraphicsDriver(lex);
733 } else if (token == "\\quotes_language") {
734 int tmpret = lex.findToken(string_quotes_language);
735 if (tmpret == -1) ++tmpret;
736 if (tmpret != LYX_LAYOUT_DEFAULT) {
737 InsetQuotes::quote_language tmpl =
738 InsetQuotes::EnglishQ;
741 tmpl = InsetQuotes::EnglishQ;
744 tmpl = InsetQuotes::SwedishQ;
747 tmpl = InsetQuotes::GermanQ;
750 tmpl = InsetQuotes::PolishQ;
753 tmpl = InsetQuotes::FrenchQ;
756 tmpl = InsetQuotes::DanishQ;
759 params.quotes_language = tmpl;
761 } else if (token == "\\quotes_times") {
763 switch (lex.getInteger()) {
765 params.quotes_times = InsetQuotes::SingleQ;
768 params.quotes_times = InsetQuotes::DoubleQ;
771 } else if (token == "\\papersize") {
772 int tmpret = lex.findToken(string_papersize);
776 params.papersize2 = tmpret;
777 } else if (token == "\\paperpackage") {
778 int tmpret = lex.findToken(string_paperpackages);
781 params.paperpackage = BufferParams::PACKAGE_NONE;
783 params.paperpackage = tmpret;
784 } else if (token == "\\use_geometry") {
786 params.use_geometry = lex.getInteger();
787 } else if (token == "\\use_amsmath") {
789 params.use_amsmath = lex.getInteger();
790 } else if (token == "\\use_natbib") {
792 params.use_natbib = lex.getInteger();
793 } else if (token == "\\use_numerical_citations") {
795 params.use_numerical_citations = lex.getInteger();
796 } else if (token == "\\paperorientation") {
797 int tmpret = lex.findToken(string_orientation);
798 if (tmpret == -1) ++tmpret;
799 if (tmpret != LYX_LAYOUT_DEFAULT)
800 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
801 } else if (token == "\\paperwidth") {
803 params.paperwidth = lex.getString();
804 } else if (token == "\\paperheight") {
806 params.paperheight = lex.getString();
807 } else if (token == "\\leftmargin") {
809 params.leftmargin = lex.getString();
810 } else if (token == "\\topmargin") {
812 params.topmargin = lex.getString();
813 } else if (token == "\\rightmargin") {
815 params.rightmargin = lex.getString();
816 } else if (token == "\\bottommargin") {
818 params.bottommargin = lex.getString();
819 } else if (token == "\\headheight") {
821 params.headheight = lex.getString();
822 } else if (token == "\\headsep") {
824 params.headsep = lex.getString();
825 } else if (token == "\\footskip") {
827 params.footskip = lex.getString();
828 } else if (token == "\\paperfontsize") {
830 params.fontsize = strip(lex.getString());
831 } else if (token == "\\papercolumns") {
833 params.columns = lex.getInteger();
834 } else if (token == "\\papersides") {
836 switch (lex.getInteger()) {
838 case 1: params.sides = LyXTextClass::OneSide; break;
839 case 2: params.sides = LyXTextClass::TwoSides; break;
841 } else if (token == "\\paperpagestyle") {
843 params.pagestyle = strip(lex.getString());
844 } else if (token == "\\bullet") {
846 int const index = lex.getInteger();
848 int temp_int = lex.getInteger();
849 params.user_defined_bullets[index].setFont(temp_int);
850 params.temp_bullets[index].setFont(temp_int);
852 temp_int = lex.getInteger();
853 params.user_defined_bullets[index].setCharacter(temp_int);
854 params.temp_bullets[index].setCharacter(temp_int);
856 temp_int = lex.getInteger();
857 params.user_defined_bullets[index].setSize(temp_int);
858 params.temp_bullets[index].setSize(temp_int);
860 string const temp_str = lex.getString();
861 if (temp_str != "\\end_bullet") {
862 // this element isn't really necessary for
863 // parsing but is easier for humans
864 // to understand bullets. Put it back and
865 // set a debug message?
866 lex.printError("\\end_bullet expected, got" + temp_str);
867 //how can I put it back?
869 } else if (token == "\\bulletLaTeX") {
871 int const index = lex.getInteger();
873 string temp_str = lex.getString();
875 while (temp_str != "\\end_bullet") {
876 // this loop structure is needed when user
877 // enters an empty string since the first
878 // thing returned will be the \\end_bullet
880 // if the LaTeX entry has spaces. Each element
881 // therefore needs to be read in turn
884 temp_str = lex.getString();
886 params.user_defined_bullets[index].setText(sum_str);
887 params.temp_bullets[index].setText(sum_str);
888 } else if (token == "\\secnumdepth") {
890 params.secnumdepth = lex.getInteger();
891 } else if (token == "\\tocdepth") {
893 params.tocdepth = lex.getInteger();
894 } else if (token == "\\spacing") {
896 string const tmp = strip(lex.getString());
897 Spacing::Space tmp_space = Spacing::Default;
899 if (tmp == "single") {
900 tmp_space = Spacing::Single;
901 } else if (tmp == "onehalf") {
902 tmp_space = Spacing::Onehalf;
903 } else if (tmp == "double") {
904 tmp_space = Spacing::Double;
905 } else if (tmp == "other") {
907 tmp_space = Spacing::Other;
908 tmp_val = lex.getFloat();
910 lex.printError("Unknown spacing token: '$$Token'");
912 // Small hack so that files written with klyx will be
915 par->params().spacing(Spacing(tmp_space, tmp_val));
917 params.spacing.set(tmp_space, tmp_val);
919 } else if (token == "\\paragraph_spacing") {
921 string const tmp = strip(lex.getString());
922 if (tmp == "single") {
923 par->params().spacing(Spacing(Spacing::Single));
924 } else if (tmp == "onehalf") {
925 par->params().spacing(Spacing(Spacing::Onehalf));
926 } else if (tmp == "double") {
927 par->params().spacing(Spacing(Spacing::Double));
928 } else if (tmp == "other") {
930 par->params().spacing(Spacing(Spacing::Other,
933 lex.printError("Unknown spacing token: '$$Token'");
935 } else if (token == "\\float_placement") {
937 params.float_placement = lex.getString();
938 } else if (token == "\\family") {
940 font.setLyXFamily(lex.getString());
941 } else if (token == "\\series") {
943 font.setLyXSeries(lex.getString());
944 } else if (token == "\\shape") {
946 font.setLyXShape(lex.getString());
947 } else if (token == "\\size") {
949 font.setLyXSize(lex.getString());
950 #ifndef NO_COMPABILITY
951 } else if (token == "\\latex") {
953 string const tok = lex.getString();
954 if (tok == "no_latex") {
956 insertErtContents(par, pos, font);
957 } else if (tok == "latex") {
958 ert_comp.active = true;
959 } else if (tok == "default") {
961 insertErtContents(par, pos, font);
963 lex.printError("Unknown LaTeX font flag "
967 } else if (token == "\\lang") {
969 string const tok = lex.getString();
970 Language const * lang = languages.getLanguage(tok);
972 font.setLanguage(lang);
974 font.setLanguage(params.language);
975 lex.printError("Unknown language `$$Token'");
977 } else if (token == "\\numeric") {
979 font.setNumber(font.setLyXMisc(lex.getString()));
980 } else if (token == "\\emph") {
982 font.setEmph(font.setLyXMisc(lex.getString()));
983 } else if (token == "\\bar") {
985 string const tok = lex.getString();
986 // This is dirty, but gone with LyX3. (Asger)
988 font.setUnderbar(LyXFont::ON);
989 else if (tok == "no")
990 font.setUnderbar(LyXFont::OFF);
991 else if (tok == "default")
992 font.setUnderbar(LyXFont::INHERIT);
994 lex.printError("Unknown bar font flag "
996 } else if (token == "\\noun") {
998 font.setNoun(font.setLyXMisc(lex.getString()));
999 } else if (token == "\\color") {
1001 font.setLyXColor(lex.getString());
1002 } else if (token == "\\align") {
1003 int tmpret = lex.findToken(string_align);
1004 if (tmpret == -1) ++tmpret;
1005 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1006 int const tmpret2 = int(pow(2.0, tmpret));
1007 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1008 par->params().align(LyXAlignment(tmpret2));
1010 } else if (token == "\\added_space_top") {
1012 par->params().spaceTop(VSpace(lex.getString()));
1013 } else if (token == "\\added_space_bottom") {
1015 par->params().spaceBottom(VSpace(lex.getString()));
1016 #ifndef NO_COMPABILITY
1017 #ifndef NO_PEXTRA_REALLY
1018 } else if (token == "\\pextra_type") {
1020 par->params().pextraType(lex.getInteger());
1021 } else if (token == "\\pextra_width") {
1023 par->params().pextraWidth(lex.getString());
1024 } else if (token == "\\pextra_widthp") {
1026 par->params().pextraWidthp(lex.getString());
1027 } else if (token == "\\pextra_alignment") {
1029 par->params().pextraAlignment(lex.getInteger());
1030 } else if (token == "\\pextra_hfill") {
1032 par->params().pextraHfill(lex.getInteger());
1033 } else if (token == "\\pextra_start_minipage") {
1035 par->params().pextraStartMinipage(lex.getInteger());
1038 } else if (token == "\\labelwidthstring") {
1040 par->params().labelWidthString(lex.getString());
1041 // do not delete this token, it is still needed!
1042 } else if (token == "\\end_inset") {
1043 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1044 << "Last inset read was: " << last_inset_read
1046 // Simply ignore this. The insets do not have
1048 // But insets should read it, it is a part of
1049 // the inset isn't it? Lgb.
1050 } else if (token == "\\begin_inset") {
1051 #ifndef NO_COMPABILITY
1052 insertErtContents(par, pos, font, false);
1053 ert_stack.push(ert_comp);
1054 ert_comp = ErtComp();
1056 readInset(lex, par, pos, font);
1057 #ifndef NO_COMPABILITY
1058 ert_comp = ert_stack.top();
1060 insertErtContents(par, pos, font);
1062 } else if (token == "\\SpecialChar") {
1063 LyXLayout const & layout =
1064 textclasslist.Style(params.textclass,
1067 // Insets don't make sense in a free-spacing context! ---Kayvan
1068 if (layout.free_spacing) {
1071 string next_token = lex.getString();
1072 if (next_token == "\\-") {
1073 par->insertChar(pos, '-', font);
1074 } else if (next_token == "\\protected_separator"
1075 || next_token == "~") {
1076 par->insertChar(pos, ' ', font);
1078 lex.printError("Token `$$Token' "
1080 "paragraph layout!");
1085 Inset * inset = new InsetSpecialChar;
1086 inset->read(this, lex);
1087 par->insertInset(pos, inset, font);
1090 } else if (token == "\\newline") {
1091 #ifndef NO_COMPABILITY
1092 if (!ert_comp.in_tabular && ert_comp.active) {
1093 ert_comp.contents += char(Paragraph::META_NEWLINE);
1095 // Since we cannot know it this is only a regular
1096 // newline or a tabular cell delimter we have to
1097 // handle the ERT here.
1098 insertErtContents(par, pos, font, false);
1100 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1104 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1107 } else if (token == "\\LyXTable") {
1108 #ifndef NO_COMPABILITY
1109 ert_comp.in_tabular = true;
1111 Inset * inset = new InsetTabular(*this);
1112 inset->read(this, lex);
1113 par->insertInset(pos, inset, font);
1115 } else if (token == "\\hfill") {
1116 par->insertChar(pos, Paragraph::META_HFILL, font);
1118 } else if (token == "\\protected_separator") { // obsolete
1119 // This is a backward compability thingie. (Lgb)
1120 // Remove it later some time...introduced with fileformat
1122 LyXLayout const & layout =
1123 textclasslist.Style(params.textclass,
1126 if (layout.free_spacing) {
1127 par->insertChar(pos, ' ', font);
1129 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1130 par->insertInset(pos, inset, font);
1133 } else if (token == "\\bibitem") { // ale970302
1135 InsetCommandParams p("bibitem", "dummy");
1136 par->bibkey = new InsetBibKey(p);
1138 par->bibkey->read(this, lex);
1139 } else if (token == "\\backslash") {
1140 #ifndef NO_COMPABILITY
1141 if (ert_comp.active) {
1142 ert_comp.contents += "\\";
1145 par->insertChar(pos, '\\', font);
1147 #ifndef NO_COMPABILITY
1150 } else if (token == "\\the_end") {
1151 #ifndef NO_COMPABILITY
1152 // If we still have some ert active here we have to insert
1153 // it so we don't loose it. (Lgb)
1154 insertErtContents(par, pos, font);
1156 the_end_read = true;
1157 #ifndef NO_COMPABILITY
1158 #ifndef NO_PEXTRA_REALLY
1159 minipar = parBeforeMinipage = 0;
1163 #ifndef NO_COMPABILITY
1164 if (ert_comp.active) {
1165 ert_comp.contents += token;
1168 // This should be insurance for the future: (Asger)
1169 lex.printError("Unknown token `$$Token'. "
1170 "Inserting as text.");
1171 string::const_iterator cit = token.begin();
1172 string::const_iterator end = token.end();
1173 for (; cit != end; ++cit) {
1174 par->insertChar(pos, (*cit), font);
1177 #ifndef NO_COMPABILITY
1182 #ifndef NO_COMPABILITY
1183 #ifndef NO_PEXTRA_REALLY
1184 // I wonder if we could use this blanket fix for all the
1185 // checkminipage cases...
1186 if (par && par->size()) {
1187 // It is possible that this will check to often,
1188 // but that should not be an correctness issue.
1189 // Only a speed issue.
1190 checkminipage = true;
1193 // now check if we have a minipage paragraph as at this
1194 // point we already read all the necessary data!
1195 // this cannot be done in layout because there we did
1196 // not read yet the paragraph PEXTRA-params (Jug)
1198 // BEGIN pextra_minipage compability
1199 // This should be removed in 1.3.x (Lgb)
1201 // This compability code is not perfect. In a couple
1202 // of rand cases it fails. When the minipage par is
1203 // the first par in the document, and when there are
1204 // none or only one regular paragraphs after the
1205 // minipage. Currently I am not investing any effort
1206 // in fixing those cases.
1208 //lyxerr << "Call depth: " << call_depth << endl;
1209 if (checkminipage && (call_depth == 1)) {
1210 checkminipage = false;
1211 if (minipar && (minipar != par) &&
1212 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1214 lyxerr << "minipages in a row" << endl;
1215 if (par->params().pextraStartMinipage()) {
1216 lyxerr << "start new minipage" << endl;
1217 // minipages in a row
1218 par->previous()->next(0);
1221 Paragraph * tmp = minipar;
1223 tmp->params().pextraType(0);
1224 tmp->params().pextraWidth(string());
1225 tmp->params().pextraWidthp(string());
1226 tmp->params().pextraAlignment(0);
1227 tmp->params().pextraHfill(false);
1228 tmp->params().pextraStartMinipage(false);
1231 // create a new paragraph to insert the
1232 // minipages in the following case
1233 if (par->params().pextraStartMinipage() &&
1234 !par->params().pextraHfill())
1236 Paragraph * p = new Paragraph;
1238 p->previous(parBeforeMinipage);
1239 parBeforeMinipage->next(p);
1241 p->params().depth(parBeforeMinipage->params().depth());
1242 parBeforeMinipage = p;
1244 InsetMinipage * mini = new InsetMinipage;
1245 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1246 mini->width(par->params().pextraWidth());
1247 if (!par->params().pextraWidthp().empty()) {
1248 lyxerr << "WP:" << mini->width() << endl;
1249 mini->width(tostr(par->params().pextraWidthp())+"%");
1251 mini->inset.paragraph(par);
1252 // Insert the minipage last in the
1253 // previous paragraph.
1254 if (par->params().pextraHfill()) {
1255 parBeforeMinipage->insertChar
1256 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1258 parBeforeMinipage->insertInset
1259 (parBeforeMinipage->size(), mini);
1263 lyxerr << "new minipage par" << endl;
1264 //nothing to do just continue reading
1267 } else if (minipar && (minipar != par)) {
1268 lyxerr << "last minipage par read" << endl;
1269 // The last paragraph read was not part of a
1270 // minipage but the par linked list is...
1271 // So we need to remove the last par from the
1273 if (par->previous())
1274 par->previous()->next(0);
1275 par->previous(parBeforeMinipage);
1276 parBeforeMinipage->next(par);
1277 Paragraph * tmp = minipar;
1279 tmp->params().pextraType(0);
1280 tmp->params().pextraWidth(string());
1281 tmp->params().pextraWidthp(string());
1282 tmp->params().pextraAlignment(0);
1283 tmp->params().pextraHfill(false);
1284 tmp->params().pextraStartMinipage(false);
1287 depth = parBeforeMinipage->params().depth();
1288 minipar = parBeforeMinipage = 0;
1289 } else if (!minipar &&
1290 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1292 // par is the first paragraph in a minipage
1293 lyxerr << "begin minipage" << endl;
1294 // To minimize problems for
1295 // the users we will insert
1296 // the first minipage in
1297 // a sequence of minipages
1298 // in its own paragraph.
1299 Paragraph * p = new Paragraph;
1301 p->previous(par->previous());
1303 p->params().depth(depth);
1304 par->params().depth(0);
1306 if (par->previous())
1307 par->previous()->next(p);
1309 parBeforeMinipage = p;
1311 if (!first_par || (first_par == par))
1314 InsetMinipage * mini = new InsetMinipage;
1315 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1316 mini->width(minipar->params().pextraWidth());
1317 if (!par->params().pextraWidthp().empty()) {
1318 lyxerr << "WP:" << mini->width() << endl;
1319 mini->width(tostr(par->params().pextraWidthp())+"%");
1321 mini->inset.paragraph(minipar);
1323 // Insert the minipage last in the
1324 // previous paragraph.
1325 if (minipar->params().pextraHfill()) {
1326 parBeforeMinipage->insertChar
1327 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1329 parBeforeMinipage->insertInset
1330 (parBeforeMinipage->size(), mini);
1333 // End of pextra_minipage compability
1337 return the_end_read;
1340 // needed to insert the selection
1341 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1342 LyXFont const & font,
1343 string const & str) const
1345 LyXLayout const & layout = textclasslist.Style(params.textclass,
1347 // insert the string, don't insert doublespace
1348 bool space_inserted = true;
1349 for(string::const_iterator cit = str.begin();
1350 cit != str.end(); ++cit) {
1352 if (par->size() || layout.keepempty) {
1353 par->breakParagraph(params, pos,
1354 layout.isEnvironment());
1357 space_inserted = true;
1361 // do not insert consecutive spaces if !free_spacing
1362 } else if ((*cit == ' ' || *cit == '\t')
1363 && space_inserted && !layout.free_spacing) {
1365 } else if (*cit == '\t') {
1366 if (!layout.free_spacing) {
1367 // tabs are like spaces here
1368 par->insertChar(pos, ' ', font);
1370 space_inserted = true;
1372 const Paragraph::value_type nb = 8 - pos % 8;
1373 for (Paragraph::size_type a = 0;
1375 par->insertChar(pos, ' ', font);
1378 space_inserted = true;
1380 } else if (!IsPrintable(*cit)) {
1381 // Ignore unprintables
1384 // just insert the character
1385 par->insertChar(pos, *cit, font);
1387 space_inserted = (*cit == ' ');
1394 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1395 int & pos, LyXFont & font)
1397 // consistency check
1398 if (lex.getString() != "\\begin_inset") {
1399 lyxerr << "Buffer::readInset: Consistency check failed."
1406 string const tmptok = lex.getString();
1407 last_inset_read = tmptok;
1409 // test the different insets
1410 if (tmptok == "LatexCommand") {
1411 InsetCommandParams inscmd;
1414 string const cmdName = inscmd.getCmdName();
1416 // This strange command allows LyX to recognize "natbib" style
1417 // citations: citet, citep, Citet etc.
1418 if (compare_no_case(cmdName, "cite", 4) == 0) {
1419 inset = new InsetCitation(inscmd);
1420 } else if (cmdName == "bibitem") {
1421 lex.printError("Wrong place for bibitem");
1422 inset = new InsetBibKey(inscmd);
1423 } else if (cmdName == "BibTeX") {
1424 inset = new InsetBibtex(inscmd);
1425 } else if (cmdName == "index") {
1426 inset = new InsetIndex(inscmd);
1427 } else if (cmdName == "include") {
1428 inset = new InsetInclude(inscmd, *this);
1429 } else if (cmdName == "label") {
1430 inset = new InsetLabel(inscmd);
1431 } else if (cmdName == "url"
1432 || cmdName == "htmlurl") {
1433 inset = new InsetUrl(inscmd);
1434 } else if (cmdName == "ref"
1435 || cmdName == "pageref"
1436 || cmdName == "vref"
1437 || cmdName == "vpageref"
1438 || cmdName == "prettyref") {
1439 if (!inscmd.getOptions().empty()
1440 || !inscmd.getContents().empty()) {
1441 inset = new InsetRef(inscmd, *this);
1443 } else if (cmdName == "tableofcontents") {
1444 inset = new InsetTOC(inscmd);
1445 } else if (cmdName == "listofalgorithms") {
1446 inset = new InsetFloatList("algorithm");
1447 } else if (cmdName == "listoffigures") {
1448 inset = new InsetFloatList("figure");
1449 } else if (cmdName == "listoftables") {
1450 inset = new InsetFloatList("table");
1451 } else if (cmdName == "printindex") {
1452 inset = new InsetPrintIndex(inscmd);
1453 } else if (cmdName == "lyxparent") {
1454 inset = new InsetParent(inscmd, *this);
1457 bool alreadyread = false;
1458 if (tmptok == "Quotes") {
1459 inset = new InsetQuotes;
1460 } else if (tmptok == "External") {
1461 inset = new InsetExternal;
1462 } else if (tmptok == "FormulaMacro") {
1463 inset = new InsetFormulaMacro;
1464 } else if (tmptok == "Formula") {
1465 inset = new InsetFormula;
1466 } else if (tmptok == "Figure") { // Backward compatibility
1467 inset = new InsetFig(100, 100, *this);
1468 //inset = new InsetGraphics;
1469 } else if (tmptok == "Graphics") {
1470 inset = new InsetGraphics;
1471 } else if (tmptok == "Info") {// backwards compatibility
1472 inset = new InsetNote(this,
1473 lex.getLongString("\\end_inset"),
1476 } else if (tmptok == "Note") {
1477 inset = new InsetNote;
1478 } else if (tmptok == "Include") {
1479 InsetCommandParams p( "Include" );
1480 inset = new InsetInclude(p, *this);
1481 } else if (tmptok == "ERT") {
1482 inset = new InsetERT;
1483 } else if (tmptok == "Tabular") {
1484 inset = new InsetTabular(*this);
1485 } else if (tmptok == "Text") {
1486 inset = new InsetText;
1487 } else if (tmptok == "Foot") {
1488 inset = new InsetFoot;
1489 } else if (tmptok == "Marginal") {
1490 inset = new InsetMarginal;
1491 } else if (tmptok == "Minipage") {
1492 inset = new InsetMinipage;
1493 } else if (tmptok == "Float") {
1495 string tmptok = lex.getString();
1496 inset = new InsetFloat(tmptok);
1498 } else if (tmptok == "List") {
1499 inset = new InsetList;
1500 } else if (tmptok == "Theorem") {
1501 inset = new InsetList;
1503 } else if (tmptok == "Caption") {
1504 inset = new InsetCaption;
1505 } else if (tmptok == "FloatList") {
1506 inset = new InsetFloatList;
1509 if (inset && !alreadyread) inset->read(this, lex);
1513 par->insertInset(pos, inset, font);
1519 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1523 string const token(lex.getString());
1524 if (token == "\\lyxformat") { // the first token _must_ be...
1526 string tmp_format = lex.getString();
1527 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1528 // if present remove ".," from string.
1529 string::size_type dot = tmp_format.find_first_of(".,");
1530 //lyxerr << " dot found at " << dot << endl;
1531 if (dot != string::npos)
1532 tmp_format.erase(dot, 1);
1533 file_format = strToInt(tmp_format);
1534 if (file_format == LYX_FORMAT) {
1536 } else if (file_format > LYX_FORMAT) {
1538 WriteAlert(_("Warning!"),
1539 _("LyX file format is newer that what"),
1540 _("is supported in this LyX version. Expect some problems."));
1542 } else if (file_format < LYX_FORMAT) {
1544 if (file_format < 200) {
1545 WriteAlert(_("ERROR!"),
1546 _("Old LyX file format found. "
1547 "Use LyX 0.10.x to read this!"));
1551 bool the_end = readLyXformat2(lex, par);
1553 // the_end was added in 213
1554 if (file_format < 213)
1558 WriteAlert(_("Warning!"),
1559 _("Reading of document is not complete"),
1560 _("Maybe the document is truncated"));
1562 } else { // "\\lyxformat" not found
1563 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1566 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1571 // Should probably be moved to somewhere else: BufferView? LyXView?
1572 bool Buffer::save() const
1574 // We don't need autosaves in the immediate future. (Asger)
1575 resetAutosaveTimers();
1579 if (lyxrc.make_backup) {
1580 s = fileName() + '~';
1581 if (!lyxrc.backupdir_path.empty())
1582 s = AddName(lyxrc.backupdir_path,
1583 subst(os::slashify_path(s),'/','!'));
1585 // Rename is the wrong way of making a backup,
1586 // this is the correct way.
1587 /* truss cp fil fil2:
1588 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1589 stat("LyXVC.lyx", 0xEFFFF688) = 0
1590 open("LyXVC.lyx", O_RDONLY) = 3
1591 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1592 fstat(4, 0xEFFFF508) = 0
1593 fstat(3, 0xEFFFF508) = 0
1594 read(3, " # T h i s f i l e w".., 8192) = 5579
1595 write(4, " # T h i s f i l e w".., 5579) = 5579
1596 read(3, 0xEFFFD4A0, 8192) = 0
1599 chmod("LyXVC3.lyx", 0100644) = 0
1600 lseek(0, 0, SEEK_CUR) = 46440
1604 // Should probably have some more error checking here.
1605 // Should be cleaned up in 0.13, at least a bit.
1606 // Doing it this way, also makes the inodes stay the same.
1607 // This is still not a very good solution, in particular we
1608 // might loose the owner of the backup.
1609 FileInfo finfo(fileName());
1610 if (finfo.exist()) {
1611 mode_t fmode = finfo.getMode();
1612 struct utimbuf times = {
1613 finfo.getAccessTime(),
1614 finfo.getModificationTime() };
1616 ifstream ifs(fileName().c_str());
1617 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1622 ::chmod(s.c_str(), fmode);
1624 if (::utime(s.c_str(), ×)) {
1625 lyxerr << "utime error." << endl;
1628 lyxerr << "LyX was not able to make "
1629 "backup copy. Beware." << endl;
1634 if (writeFile(fileName(), false)) {
1636 removeAutosaveFile(fileName());
1638 // Saving failed, so backup is not backup
1639 if (lyxrc.make_backup) {
1640 lyx::rename(s, fileName());
1648 // Returns false if unsuccesful
1649 bool Buffer::writeFile(string const & fname, bool flag) const
1651 // if flag is false writeFile will not create any GUI
1652 // warnings, only cerr.
1653 // Needed for autosave in background or panic save (Matthias 120496)
1655 if (read_only && (fname == filename)) {
1656 // Here we should come with a question if we should
1657 // perform the write anyway.
1659 lyxerr << _("Error! Document is read-only: ")
1662 WriteAlert(_("Error! Document is read-only: "),
1667 FileInfo finfo(fname);
1668 if (finfo.exist() && !finfo.writable()) {
1669 // Here we should come with a question if we should
1670 // try to do the save anyway. (i.e. do a chmod first)
1672 lyxerr << _("Error! Cannot write file: ")
1675 WriteFSAlert(_("Error! Cannot write file: "),
1680 ofstream ofs(fname.c_str());
1683 lyxerr << _("Error! Cannot open file: ")
1686 WriteFSAlert(_("Error! Cannot open file: "),
1692 // Use the standard "C" locale for file output.
1693 ofs.imbue(std::locale::classic());
1696 // The top of the file should not be written by params.
1698 // write out a comment in the top of the file
1699 ofs << '#' << LYX_DOCVERSION
1700 << " created this file. For more info see http://www.lyx.org/\n"
1701 << "\\lyxformat " << LYX_FORMAT << "\n";
1703 // now write out the buffer paramters.
1704 params.writeFile(ofs);
1706 Paragraph::depth_type depth = 0;
1708 // this will write out all the paragraphs
1709 // using recursive descent.
1710 paragraph->writeFile(this, ofs, params, depth);
1712 // Write marker that shows file is complete
1713 ofs << "\n\\the_end" << endl;
1717 // how to check if close went ok?
1718 // Following is an attempt... (BE 20001011)
1720 // good() returns false if any error occured, including some
1721 // formatting error.
1722 // bad() returns true if something bad happened in the buffer,
1723 // which should include file system full errors.
1730 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1732 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1742 string const Buffer::asciiParagraph(Paragraph const * par,
1743 unsigned int linelen) const
1745 ostringstream buffer;
1746 Paragraph::depth_type depth = 0;
1748 Paragraph::depth_type ltype_depth = 0;
1749 unsigned int currlinelen = 0;
1750 bool ref_printed = false;
1754 if (!par->previous()) {
1755 // begins or ends a deeper area ?
1756 if (depth != par->params().depth()) {
1757 if (par->params().depth() > depth) {
1758 while (par->params().depth() > depth) {
1762 while (par->params().depth() < depth) {
1768 // First write the layout
1769 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1770 if (tmp == "Itemize") {
1772 ltype_depth = depth + 1;
1773 } else if (tmp == "Enumerate") {
1775 ltype_depth = depth + 1;
1776 } else if (contains(tmp, "ection")) {
1778 ltype_depth = depth + 1;
1779 } else if (contains(tmp, "aragraph")) {
1781 ltype_depth = depth + 1;
1782 } else if (tmp == "Description") {
1784 ltype_depth = depth + 1;
1785 } else if (tmp == "Abstract") {
1788 } else if (tmp == "Bibliography") {
1796 /* maybe some vertical spaces */
1798 /* the labelwidthstring used in lists */
1802 /* some pagebreaks? */
1806 /* what about the alignment */
1808 lyxerr << "Should this ever happen?" << endl;
1811 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1812 if (!i && !noparbreak) {
1815 for (Paragraph::depth_type j = 0; j < depth; ++j)
1817 currlinelen = depth * 2;
1820 case 4: // (Sub)Paragraph
1821 case 5: // Description
1825 buffer << "Abstract\n\n";
1827 buffer << "Abstract: ";
1829 case 7: // Bibliography
1832 buffer << "References\n\n";
1834 buffer << "References: ";
1839 buffer << par->params().labelString() << " ";
1842 if (ltype_depth > depth) {
1843 for (Paragraph::depth_type j = ltype_depth - 1;
1846 currlinelen += (ltype_depth-depth)*2;
1850 char c = par->getUChar(params, i);
1854 case Paragraph::META_INSET:
1856 Inset const * inset = par->getInset(i);
1858 if (!inset->ascii(this, buffer)) {
1861 rsplit(buffer.str().c_str(),
1863 currlinelen += s.length();
1865 // to be sure it breaks paragraph
1866 currlinelen += linelen;
1872 case Paragraph::META_NEWLINE:
1875 for (Paragraph::depth_type j = 0;
1879 currlinelen = depth * 2;
1880 if (ltype_depth > depth) {
1881 for (Paragraph::depth_type j = ltype_depth;
1884 currlinelen += (ltype_depth - depth) * 2;
1888 case Paragraph::META_HFILL:
1897 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1898 (c == ' ') && ((i + 2) < par->size()))
1901 for (Paragraph::depth_type j = 0;
1904 currlinelen = depth * 2;
1905 if (ltype_depth > depth) {
1906 for (Paragraph::depth_type j = ltype_depth;
1909 currlinelen += (ltype_depth-depth)*2;
1911 } else if (c != '\0')
1914 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1919 return buffer.str().c_str();
1923 void Buffer::writeFileAscii(string const & fname, int linelen)
1925 ofstream ofs(fname.c_str());
1927 WriteFSAlert(_("Error: Cannot write file:"), fname);
1930 writeFileAscii(ofs, linelen);
1934 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1936 Paragraph * par = paragraph;
1938 ofs << asciiParagraph(par, linelen);
1946 void Buffer::makeLaTeXFile(string const & fname,
1947 string const & original_path,
1948 bool nice, bool only_body)
1950 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1952 niceFile = nice; // this will be used by Insetincludes.
1954 tex_code_break_column = lyxrc.ascii_linelen;
1956 LyXTextClass const & tclass =
1957 textclasslist.TextClass(params.textclass);
1959 ofstream ofs(fname.c_str());
1961 WriteFSAlert(_("Error: Cannot open file: "), fname);
1965 // validate the buffer.
1966 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1967 LaTeXFeatures features(params, tclass.numLayouts());
1969 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1972 // The starting paragraph of the coming rows is the
1973 // first paragraph of the document. (Asger)
1974 texrow.start(paragraph, 0);
1976 if (!only_body && nice) {
1977 ofs << "%% " LYX_DOCVERSION " created this file. "
1978 "For more info, see http://www.lyx.org/.\n"
1979 "%% Do not edit unless you really know what "
1984 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1985 // There are a few differences between nice LaTeX and usual files:
1986 // usual is \batchmode and has a
1987 // special input@path to allow the including of figures
1988 // with either \input or \includegraphics (what figinsets do).
1989 // batchmode is not set if there is a tex_code_break_column.
1990 // In this case somebody is interested in the generated LaTeX,
1991 // so this is OK. input@path is set when the actual parameter
1992 // original_path is set. This is done for usual tex-file, but not
1993 // for nice-latex-file. (Matthias 250696)
1996 // code for usual, NOT nice-latex-file
1997 ofs << "\\batchmode\n"; // changed
1998 // from \nonstopmode
2001 if (!original_path.empty()) {
2002 ofs << "\\makeatletter\n"
2003 << "\\def\\input@path{{"
2004 << os::external_path(original_path) << "/}}\n"
2005 << "\\makeatother\n";
2011 ofs << "\\documentclass";
2013 ostringstream options; // the document class options.
2015 if (tokenPos(tclass.opt_fontsize(),
2016 '|', params.fontsize) >= 0) {
2017 // only write if existing in list (and not default)
2018 options << params.fontsize << "pt,";
2022 if (!params.use_geometry &&
2023 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2024 switch (params.papersize) {
2025 case BufferParams::PAPER_A4PAPER:
2026 options << "a4paper,";
2028 case BufferParams::PAPER_USLETTER:
2029 options << "letterpaper,";
2031 case BufferParams::PAPER_A5PAPER:
2032 options << "a5paper,";
2034 case BufferParams::PAPER_B5PAPER:
2035 options << "b5paper,";
2037 case BufferParams::PAPER_EXECUTIVEPAPER:
2038 options << "executivepaper,";
2040 case BufferParams::PAPER_LEGALPAPER:
2041 options << "legalpaper,";
2047 if (params.sides != tclass.sides()) {
2048 switch (params.sides) {
2049 case LyXTextClass::OneSide:
2050 options << "oneside,";
2052 case LyXTextClass::TwoSides:
2053 options << "twoside,";
2059 if (params.columns != tclass.columns()) {
2060 if (params.columns == 2)
2061 options << "twocolumn,";
2063 options << "onecolumn,";
2066 if (!params.use_geometry
2067 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2068 options << "landscape,";
2070 // language should be a parameter to \documentclass
2072 ostringstream language_options;
2073 if (params.language->babel() == "hebrew"
2074 && default_language->babel() != "hebrew")
2075 // This seems necessary
2076 features.UsedLanguages.insert(default_language);
2078 if (lyxrc.language_use_babel ||
2079 params.language->lang() != lyxrc.default_language ||
2080 !features.UsedLanguages.empty()) {
2082 for (LaTeXFeatures::LanguageList::const_iterator cit =
2083 features.UsedLanguages.begin();
2084 cit != features.UsedLanguages.end(); ++cit)
2085 language_options << (*cit)->babel() << ',';
2086 language_options << params.language->babel();
2087 if (lyxrc.language_global_options)
2088 options << language_options.str() << ',';
2091 // the user-defined options
2092 if (!params.options.empty()) {
2093 options << params.options << ',';
2096 string strOptions(options.str().c_str());
2097 if (!strOptions.empty()){
2098 strOptions = strip(strOptions, ',');
2099 ofs << '[' << strOptions << ']';
2103 << textclasslist.LatexnameOfClass(params.textclass)
2106 // end of \documentclass defs
2108 // font selection must be done before loading fontenc.sty
2109 // The ae package is not needed when using OT1 font encoding.
2110 if (params.fonts != "default" &&
2111 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2112 ofs << "\\usepackage{" << params.fonts << "}\n";
2114 if (params.fonts == "ae") {
2115 ofs << "\\usepackage{aecompl}\n";
2119 // this one is not per buffer
2120 if (lyxrc.fontenc != "default") {
2121 ofs << "\\usepackage[" << lyxrc.fontenc
2126 if (params.inputenc == "auto") {
2127 string const doc_encoding =
2128 params.language->encoding()->LatexName();
2130 // Create a list with all the input encodings used
2132 set<string> encodings;
2133 for (LaTeXFeatures::LanguageList::const_iterator it =
2134 features.UsedLanguages.begin();
2135 it != features.UsedLanguages.end(); ++it)
2136 if ((*it)->encoding()->LatexName() != doc_encoding)
2137 encodings.insert((*it)->encoding()->LatexName());
2139 ofs << "\\usepackage[";
2140 std::copy(encodings.begin(), encodings.end(),
2141 std::ostream_iterator<string>(ofs, ","));
2142 ofs << doc_encoding << "]{inputenc}\n";
2144 } else if (params.inputenc != "default") {
2145 ofs << "\\usepackage[" << params.inputenc
2150 // At the very beginning the text parameters.
2151 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2152 switch (params.paperpackage) {
2153 case BufferParams::PACKAGE_A4:
2154 ofs << "\\usepackage{a4}\n";
2157 case BufferParams::PACKAGE_A4WIDE:
2158 ofs << "\\usepackage{a4wide}\n";
2161 case BufferParams::PACKAGE_WIDEMARGINSA4:
2162 ofs << "\\usepackage[widemargins]{a4}\n";
2167 if (params.use_geometry) {
2168 ofs << "\\usepackage{geometry}\n";
2170 ofs << "\\geometry{verbose";
2171 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2172 ofs << ",landscape";
2173 switch (params.papersize2) {
2174 case BufferParams::VM_PAPER_CUSTOM:
2175 if (!params.paperwidth.empty())
2176 ofs << ",paperwidth="
2177 << params.paperwidth;
2178 if (!params.paperheight.empty())
2179 ofs << ",paperheight="
2180 << params.paperheight;
2182 case BufferParams::VM_PAPER_USLETTER:
2183 ofs << ",letterpaper";
2185 case BufferParams::VM_PAPER_USLEGAL:
2186 ofs << ",legalpaper";
2188 case BufferParams::VM_PAPER_USEXECUTIVE:
2189 ofs << ",executivepaper";
2191 case BufferParams::VM_PAPER_A3:
2194 case BufferParams::VM_PAPER_A4:
2197 case BufferParams::VM_PAPER_A5:
2200 case BufferParams::VM_PAPER_B3:
2203 case BufferParams::VM_PAPER_B4:
2206 case BufferParams::VM_PAPER_B5:
2210 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2211 switch (lyxrc.default_papersize) {
2212 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2213 case BufferParams::PAPER_USLETTER:
2214 ofs << ",letterpaper";
2216 case BufferParams::PAPER_LEGALPAPER:
2217 ofs << ",legalpaper";
2219 case BufferParams::PAPER_EXECUTIVEPAPER:
2220 ofs << ",executivepaper";
2222 case BufferParams::PAPER_A3PAPER:
2225 case BufferParams::PAPER_A4PAPER:
2228 case BufferParams::PAPER_A5PAPER:
2231 case BufferParams::PAPER_B5PAPER:
2236 if (!params.topmargin.empty())
2237 ofs << ",tmargin=" << params.topmargin;
2238 if (!params.bottommargin.empty())
2239 ofs << ",bmargin=" << params.bottommargin;
2240 if (!params.leftmargin.empty())
2241 ofs << ",lmargin=" << params.leftmargin;
2242 if (!params.rightmargin.empty())
2243 ofs << ",rmargin=" << params.rightmargin;
2244 if (!params.headheight.empty())
2245 ofs << ",headheight=" << params.headheight;
2246 if (!params.headsep.empty())
2247 ofs << ",headsep=" << params.headsep;
2248 if (!params.footskip.empty())
2249 ofs << ",footskip=" << params.footskip;
2253 if (features.amsstyle
2254 && !tclass.provides(LyXTextClass::amsmath)) {
2255 ofs << "\\usepackage{amsmath}\n";
2259 if (tokenPos(tclass.opt_pagestyle(),
2260 '|', params.pagestyle) >= 0) {
2261 if (params.pagestyle == "fancy") {
2262 ofs << "\\usepackage{fancyhdr}\n";
2265 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2269 // We try to load babel late, in case it interferes
2270 // with other packages.
2272 string tmp = lyxrc.language_package;
2273 if (!lyxrc.language_global_options
2274 && tmp == "\\usepackage{babel}")
2275 tmp = string("\\usepackage[") +
2276 language_options.str().c_str() +
2282 if (params.secnumdepth != tclass.secnumdepth()) {
2283 ofs << "\\setcounter{secnumdepth}{"
2284 << params.secnumdepth
2288 if (params.tocdepth != tclass.tocdepth()) {
2289 ofs << "\\setcounter{tocdepth}{"
2295 if (params.paragraph_separation) {
2296 switch (params.defskip.kind()) {
2297 case VSpace::SMALLSKIP:
2298 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2300 case VSpace::MEDSKIP:
2301 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2303 case VSpace::BIGSKIP:
2304 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2306 case VSpace::LENGTH:
2307 ofs << "\\setlength\\parskip{"
2308 << params.defskip.length().asLatexString()
2311 default: // should never happen // Then delete it.
2312 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2317 ofs << "\\setlength\\parindent{0pt}\n";
2321 // Now insert the LyX specific LaTeX commands...
2323 // The optional packages;
2324 string preamble(features.getPackages());
2326 // this might be useful...
2327 preamble += "\n\\makeatletter\n";
2329 // Some macros LyX will need
2330 string tmppreamble(features.getMacros());
2332 if (!tmppreamble.empty()) {
2333 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2334 "LyX specific LaTeX commands.\n"
2335 + tmppreamble + '\n';
2338 // the text class specific preamble
2339 tmppreamble = features.getTClassPreamble();
2340 if (!tmppreamble.empty()) {
2341 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2342 "Textclass specific LaTeX commands.\n"
2343 + tmppreamble + '\n';
2346 /* the user-defined preamble */
2347 if (!params.preamble.empty()) {
2348 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2349 "User specified LaTeX commands.\n"
2350 + params.preamble + '\n';
2353 preamble += "\\makeatother\n";
2355 // Itemize bullet settings need to be last in case the user
2356 // defines their own bullets that use a package included
2357 // in the user-defined preamble -- ARRae
2358 // Actually it has to be done much later than that
2359 // since some packages like frenchb make modifications
2360 // at \begin{document} time -- JMarc
2362 for (int i = 0; i < 4; ++i) {
2363 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2364 if (bullets_def.empty())
2365 bullets_def="\\AtBeginDocument{\n";
2366 bullets_def += " \\renewcommand{\\labelitemi";
2368 // `i' is one less than the item to modify
2375 bullets_def += "ii";
2381 bullets_def += "}{" +
2382 params.user_defined_bullets[i].getText()
2387 if (!bullets_def.empty())
2388 preamble += bullets_def + "}\n\n";
2390 for (int j = countChar(preamble, '\n'); j-- ;) {
2397 ofs << "\\begin{document}\n";
2400 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2402 if (!lyxrc.language_auto_begin) {
2403 ofs << subst(lyxrc.language_command_begin, "$$lang",
2404 params.language->babel())
2409 latexParagraphs(ofs, paragraph, 0, texrow);
2411 // add this just in case after all the paragraphs
2415 if (!lyxrc.language_auto_end) {
2416 ofs << subst(lyxrc.language_command_end, "$$lang",
2417 params.language->babel())
2423 ofs << "\\end{document}\n";
2426 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2428 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2432 // Just to be sure. (Asger)
2435 // tex_code_break_column's value is used to decide
2436 // if we are in batchmode or not (within mathed_write()
2437 // in math_write.C) so we must set it to a non-zero
2438 // value when we leave otherwise we save incorrect .lyx files.
2439 tex_code_break_column = lyxrc.ascii_linelen;
2443 lyxerr << "File was not closed properly." << endl;
2446 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2451 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2453 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2454 Paragraph * endpar, TexRow & texrow) const
2456 bool was_title = false;
2457 bool already_title = false;
2460 while (par != endpar) {
2461 LyXLayout const & layout =
2462 textclasslist.Style(params.textclass,
2465 if (layout.intitle) {
2466 if (already_title) {
2467 lyxerr <<"Error in latexParagraphs: You"
2468 " should not mix title layouts"
2469 " with normal ones." << endl;
2472 } else if (was_title && !already_title) {
2473 ofs << "\\maketitle\n";
2475 already_title = true;
2479 if (layout.isEnvironment()) {
2480 par = par->TeXEnvironment(this, params, ofs, texrow);
2482 par = par->TeXOnePar(this, params, ofs, texrow, false);
2485 // It might be that we only have a title in this document
2486 if (was_title && !already_title) {
2487 ofs << "\\maketitle\n";
2493 bool Buffer::isLatex() const
2495 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2499 bool Buffer::isLinuxDoc() const
2501 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2505 bool Buffer::isLiterate() const
2507 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2511 bool Buffer::isDocBook() const
2513 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2517 bool Buffer::isSGML() const
2519 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2520 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2524 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2525 string const & latexname) const
2527 if (!latexname.empty() && latexname != "!-- --")
2528 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2529 //os << string(depth, ' ') << "<" << latexname << ">\n";
2533 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2534 string const & latexname) const
2536 if (!latexname.empty() && latexname != "!-- --")
2537 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2538 //os << string(depth, ' ') << "</" << latexname << ">\n";
2542 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2544 ofstream ofs(fname.c_str());
2547 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2551 niceFile = nice; // this will be used by included files.
2553 LyXTextClass const & tclass =
2554 textclasslist.TextClass(params.textclass);
2556 LaTeXFeatures features(params, tclass.numLayouts());
2561 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2564 string sgml_includedfiles=features.getIncludedFiles(fname);
2566 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2567 ofs << "<!doctype linuxdoc system>\n\n";
2569 ofs << "<!doctype linuxdoc system [ "
2570 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2573 if (params.options.empty())
2574 sgmlOpenTag(ofs, 0, top_element);
2576 string top = top_element;
2578 top += params.options;
2579 sgmlOpenTag(ofs, 0, top);
2583 ofs << "<!-- " << LYX_DOCVERSION
2584 << " created this file. For more info see http://www.lyx.org/"
2587 Paragraph::depth_type depth = 0; // paragraph depth
2588 Paragraph * par = paragraph;
2590 vector<string> environment_stack(5);
2593 LyXLayout const & style =
2594 textclasslist.Style(params.textclass,
2597 // treat <toc> as a special case for compatibility with old code
2598 if (par->getChar(0) == Paragraph::META_INSET) {
2599 Inset * inset = par->getInset(0);
2600 Inset::Code lyx_code = inset->lyxCode();
2601 if (lyx_code == Inset::TOC_CODE){
2602 string const temp = "toc";
2603 sgmlOpenTag(ofs, depth, temp);
2610 // environment tag closing
2611 for (; depth > par->params().depth(); --depth) {
2612 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2613 environment_stack[depth].erase();
2616 // write opening SGML tags
2617 switch (style.latextype) {
2618 case LATEX_PARAGRAPH:
2619 if (depth == par->params().depth()
2620 && !environment_stack[depth].empty()) {
2621 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2622 environment_stack[depth].erase();
2628 sgmlOpenTag(ofs, depth, style.latexname());
2633 linuxDocError(par, 0,
2634 _("Error : Wrong depth for"
2635 " LatexType Command.\n"));
2637 if (!environment_stack[depth].empty()){
2638 sgmlCloseTag(ofs, depth,
2639 environment_stack[depth]);
2643 environment_stack[depth].erase();
2644 sgmlOpenTag(ofs, depth, style.latexname());
2647 case LATEX_ENVIRONMENT:
2648 case LATEX_ITEM_ENVIRONMENT:
2649 if (depth == par->params().depth()
2650 && environment_stack[depth] != style.latexname()) {
2651 sgmlCloseTag(ofs, depth,
2652 environment_stack[depth]);
2653 environment_stack[depth].erase();
2655 if (depth < par->params().depth()) {
2656 depth = par->params().depth();
2657 environment_stack[depth].erase();
2659 if (environment_stack[depth] != style.latexname()) {
2661 sgmlOpenTag(ofs, depth, "p");
2663 sgmlOpenTag(ofs, depth, style.latexname());
2665 if (environment_stack.size() == depth + 1)
2666 environment_stack.push_back("!-- --");
2667 environment_stack[depth] = style.latexname();
2670 if (style.latexparam() == "CDATA")
2673 if (style.latextype == LATEX_ENVIRONMENT) break;
2675 if (style.labeltype == LABEL_MANUAL)
2680 sgmlOpenTag(ofs, depth + 1, item_name);
2683 sgmlOpenTag(ofs, depth, style.latexname());
2687 simpleLinuxDocOnePar(ofs, par, depth);
2692 // write closing SGML tags
2693 switch (style.latextype) {
2696 case LATEX_ENVIRONMENT:
2697 case LATEX_ITEM_ENVIRONMENT:
2698 if (style.latexparam() == "CDATA")
2702 sgmlCloseTag(ofs, depth, style.latexname());
2708 for (int i=depth; i >= 0; --i)
2709 sgmlCloseTag(ofs, depth, environment_stack[i]);
2713 sgmlCloseTag(ofs, 0, top_element);
2717 // How to check for successful close
2721 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2722 Paragraph::depth_type depth, int desc_on,
2725 Paragraph * tpar = par;
2727 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2729 tpar = tpar->next();
2732 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2733 "Caption").second) {
2734 sgmlOpenTag(os, depth + 1, inner_tag);
2736 simpleDocBookOnePar(os, extra_par, tpar,
2737 desc_on, depth + 2);
2738 sgmlCloseTag(os, depth+1, inner_tag);
2739 if (!extra_par.empty())
2745 // checks, if newcol chars should be put into this line
2746 // writes newline, if necessary.
2749 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2750 string::size_type newcol)
2753 if (colcount > lyxrc.ascii_linelen) {
2755 colcount = newcol; // assume write after this call
2770 string tag_name(PAR_TAG const & pt) {
2772 case NONE: return "!-- --";
2773 case TT: return "tt";
2774 case SF: return "sf";
2775 case BF: return "bf";
2776 case IT: return "it";
2777 case SL: return "sl";
2778 case EM: return "em";
2785 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2787 p1 = static_cast<PAR_TAG>(p1 | p2);
2792 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2794 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2802 // Handle internal paragraph parsing -- layout already processed.
2803 void Buffer::simpleLinuxDocOnePar(ostream & os,
2805 Paragraph::depth_type /*depth*/)
2807 LyXLayout const & style = textclasslist.Style(params.textclass,
2809 string::size_type char_line_count = 5; // Heuristic choice ;-)
2811 // gets paragraph main font
2814 if (style.labeltype == LABEL_MANUAL) {
2815 font_old = style.labelfont;
2818 font_old = style.font;
2822 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2823 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2824 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2827 stack<PAR_TAG> tag_state;
2828 // parsing main loop
2829 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2831 PAR_TAG tag_close = NONE;
2832 list < PAR_TAG > tag_open;
2834 LyXFont const font = par->getFont(params, i);
2836 if (font_old.family() != font.family()) {
2837 switch (family_type) {
2838 case LyXFont::SANS_FAMILY:
2841 case LyXFont::TYPEWRITER_FAMILY:
2848 family_type = font.family();
2850 switch (family_type) {
2851 case LyXFont::SANS_FAMILY:
2852 tag_open.push_back(SF);
2854 case LyXFont::TYPEWRITER_FAMILY:
2855 tag_open.push_back(TT);
2862 if (font_old.series() != font.series()) {
2863 switch (series_type) {
2864 case LyXFont::BOLD_SERIES:
2871 series_type = font.series();
2873 switch (series_type) {
2874 case LyXFont::BOLD_SERIES:
2875 tag_open.push_back(BF);
2883 if (font_old.shape() != font.shape()) {
2884 switch (shape_type) {
2885 case LyXFont::ITALIC_SHAPE:
2888 case LyXFont::SLANTED_SHAPE:
2895 shape_type = font.shape();
2897 switch (shape_type) {
2898 case LyXFont::ITALIC_SHAPE:
2899 tag_open.push_back(IT);
2901 case LyXFont::SLANTED_SHAPE:
2902 tag_open.push_back(SL);
2909 if (font_old.emph() != font.emph()) {
2910 if (font.emph() == LyXFont::ON) {
2911 tag_open.push_back(EM);
2920 list < PAR_TAG > temp;
2921 while(!tag_state.empty() && tag_close ) {
2922 PAR_TAG k = tag_state.top();
2924 os << "</" << tag_name(k) << ">";
2931 for(list< PAR_TAG >::const_iterator j = temp.begin();
2932 j != temp.end(); ++j) {
2934 os << "<" << tag_name(*j) << ">";
2937 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2938 j != tag_open.end(); ++j) {
2940 os << "<" << tag_name(*j) << ">";
2943 char c = par->getChar(i);
2945 if (c == Paragraph::META_INSET) {
2946 Inset * inset = par->getInset(i);
2947 inset->linuxdoc(this, os);
2952 if (style.latexparam() == "CDATA") {
2953 // "TeX"-Mode on == > SGML-Mode on.
2959 if (par->linuxDocConvertChar(c, sgml_string)
2960 && !style.free_spacing) {
2961 // in freespacing mode, spaces are
2962 // non-breaking characters
2963 if (desc_on) {// if char is ' ' then...
2966 linux_doc_line_break(os, char_line_count, 6);
2970 linux_doc_line_break(os, char_line_count, 1);
2975 char_line_count += sgml_string.length();
2981 while (!tag_state.empty()) {
2982 os << "</" << tag_name(tag_state.top()) << ">";
2986 // resets description flag correctly
2988 // <tag> not closed...
2989 linux_doc_line_break(os, char_line_count, 6);
2995 // Print an error message.
2996 void Buffer::linuxDocError(Paragraph * par, int pos,
2997 string const & message)
2999 // insert an error marker in text
3000 InsetError * new_inset = new InsetError(message);
3001 par->insertInset(pos, new_inset);
3005 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3007 ofstream ofs(fname.c_str());
3009 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3013 Paragraph * par = paragraph;
3015 niceFile = nice; // this will be used by Insetincludes.
3017 LyXTextClass const & tclass =
3018 textclasslist.TextClass(params.textclass);
3020 LaTeXFeatures features(params, tclass.numLayouts());
3025 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3028 string sgml_includedfiles = features.getIncludedFiles(fname);
3030 ofs << "<!doctype " << top_element
3031 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3033 if (params.preamble.empty() && sgml_includedfiles.empty())
3036 ofs << "\n [ " << params.preamble
3037 << sgml_includedfiles << " \n]>\n\n";
3040 string top = top_element;
3042 top += params.language->code();
3045 if (!params.options.empty()) {
3047 top += params.options;
3049 sgmlOpenTag(ofs, 0, top);
3051 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3052 << "\n See http://www.lyx.org/ for more information -->\n";
3054 vector<string> environment_stack(10);
3055 vector<string> environment_inner(10);
3056 vector<string> command_stack(10);
3058 bool command_flag = false;
3059 Paragraph::depth_type command_depth = 0;
3060 Paragraph::depth_type command_base = 0;
3061 Paragraph::depth_type cmd_depth = 0;
3062 Paragraph::depth_type depth = 0; // paragraph depth
3065 string command_name;
3071 int desc_on = 0; // description mode
3073 LyXLayout const & style =
3074 textclasslist.Style(params.textclass,
3077 // environment tag closing
3078 for (; depth > par->params().depth(); --depth) {
3079 if (environment_inner[depth] != "!-- --") {
3080 item_name = "listitem";
3081 sgmlCloseTag(ofs, command_depth + depth,
3083 if (environment_inner[depth] == "varlistentry")
3084 sgmlCloseTag(ofs, depth+command_depth,
3085 environment_inner[depth]);
3087 sgmlCloseTag(ofs, depth + command_depth,
3088 environment_stack[depth]);
3089 environment_stack[depth].erase();
3090 environment_inner[depth].erase();
3093 if (depth == par->params().depth()
3094 && environment_stack[depth] != style.latexname()
3095 && !environment_stack[depth].empty()) {
3096 if (environment_inner[depth] != "!-- --") {
3097 item_name= "listitem";
3098 sgmlCloseTag(ofs, command_depth+depth,
3100 if (environment_inner[depth] == "varlistentry")
3102 depth + command_depth,
3103 environment_inner[depth]);
3106 sgmlCloseTag(ofs, depth + command_depth,
3107 environment_stack[depth]);
3109 environment_stack[depth].erase();
3110 environment_inner[depth].erase();
3113 // Write opening SGML tags.
3114 switch (style.latextype) {
3115 case LATEX_PARAGRAPH:
3116 sgmlOpenTag(ofs, depth + command_depth,
3122 linuxDocError(par, 0,
3123 _("Error : Wrong depth for "
3124 "LatexType Command.\n"));
3126 command_name = style.latexname();
3128 sgmlparam = style.latexparam();
3129 c_params = split(sgmlparam, c_depth,'|');
3131 cmd_depth = lyx::atoi(c_depth);
3134 if (cmd_depth < command_base) {
3135 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3136 sgmlCloseTag(ofs, j, command_stack[j]);
3137 command_depth = command_base = cmd_depth;
3138 } else if (cmd_depth <= command_depth) {
3139 for (int j = command_depth; j >= int(cmd_depth); --j)
3140 sgmlCloseTag(ofs, j, command_stack[j]);
3141 command_depth = cmd_depth;
3143 command_depth = cmd_depth;
3145 command_depth = command_base = cmd_depth;
3146 command_flag = true;
3148 if (command_stack.size() == command_depth + 1)
3149 command_stack.push_back(string());
3150 command_stack[command_depth] = command_name;
3152 // treat label as a special case for
3153 // more WYSIWYM handling.
3154 if (par->getChar(0) == Paragraph::META_INSET) {
3155 Inset * inset = par->getInset(0);
3156 Inset::Code lyx_code = inset->lyxCode();
3157 if (lyx_code == Inset::LABEL_CODE){
3158 command_name += " id=\"";
3159 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3160 command_name += "\"";
3165 sgmlOpenTag(ofs, depth + command_depth, command_name);
3166 if (c_params.empty())
3167 item_name = "title";
3169 item_name = c_params;
3170 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3173 case LATEX_ENVIRONMENT:
3174 case LATEX_ITEM_ENVIRONMENT:
3175 if (depth < par->params().depth()) {
3176 depth = par->params().depth();
3177 environment_stack[depth].erase();
3180 if (environment_stack[depth] != style.latexname()) {
3181 if(environment_stack.size() == depth + 1) {
3182 environment_stack.push_back("!-- --");
3183 environment_inner.push_back("!-- --");
3185 environment_stack[depth] = style.latexname();
3186 environment_inner[depth] = "!-- --";
3187 sgmlOpenTag(ofs, depth + command_depth,
3188 environment_stack[depth]);
3190 if (environment_inner[depth] != "!-- --") {
3191 item_name= "listitem";
3193 command_depth + depth,
3195 if (environment_inner[depth] == "varlistentry")
3197 depth + command_depth,
3198 environment_inner[depth]);
3202 if (style.latextype == LATEX_ENVIRONMENT) {
3203 if (!style.latexparam().empty()) {
3204 if(style.latexparam() == "CDATA")
3207 sgmlOpenTag(ofs, depth + command_depth,
3208 style.latexparam());
3213 desc_on = (style.labeltype == LABEL_MANUAL);
3216 environment_inner[depth]= "varlistentry";
3218 environment_inner[depth]= "listitem";
3220 sgmlOpenTag(ofs, depth + 1 + command_depth,
3221 environment_inner[depth]);
3225 sgmlOpenTag(ofs, depth + 1 + command_depth,
3229 sgmlOpenTag(ofs, depth + 1 + command_depth,
3234 sgmlOpenTag(ofs, depth + command_depth,
3240 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3241 depth + 1 + command_depth);
3245 // write closing SGML tags
3246 switch (style.latextype) {
3248 if (c_params.empty())
3252 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3254 case LATEX_ENVIRONMENT:
3255 if (!style.latexparam().empty()) {
3256 if(style.latexparam() == "CDATA")
3259 sgmlCloseTag(ofs, depth + command_depth,
3260 style.latexparam());
3263 case LATEX_ITEM_ENVIRONMENT:
3264 if (desc_on == 1) break;
3266 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3268 case LATEX_PARAGRAPH:
3269 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3272 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3278 for (int d = depth; d >= 0; --d) {
3279 if (!environment_stack[depth].empty()) {
3280 if (environment_inner[depth] != "!-- --") {
3281 item_name = "listitem";
3282 sgmlCloseTag(ofs, command_depth + depth,
3284 if (environment_inner[depth] == "varlistentry")
3285 sgmlCloseTag(ofs, depth + command_depth,
3286 environment_inner[depth]);
3289 sgmlCloseTag(ofs, depth + command_depth,
3290 environment_stack[depth]);
3294 for (int j = command_depth; j >= 0 ; --j)
3295 if (!command_stack[j].empty())
3296 sgmlCloseTag(ofs, j, command_stack[j]);
3299 sgmlCloseTag(ofs, 0, top_element);
3302 // How to check for successful close
3306 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3307 Paragraph * par, int & desc_on,
3308 Paragraph::depth_type depth) const
3310 bool emph_flag = false;
3312 LyXLayout const & style = textclasslist.Style(params.textclass,
3315 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3317 int char_line_count = depth;
3318 //if (!style.free_spacing)
3319 // os << string(depth,' ');
3321 // parsing main loop
3322 for (Paragraph::size_type i = 0;
3323 i < par->size(); ++i) {
3324 LyXFont font = par->getFont(params, i);
3326 // handle <emphasis> tag
3327 if (font_old.emph() != font.emph()) {
3328 if (font.emph() == LyXFont::ON) {
3332 os << "</emphasis>";
3337 char c = par->getChar(i);
3339 if (c == Paragraph::META_INSET) {
3340 Inset * inset = par->getInset(i);
3342 inset->docBook(this, ost);
3343 string tmp_out = ost.str().c_str();
3346 // This code needs some explanation:
3347 // Two insets are treated specially
3348 // label if it is the first element in a command paragraph
3350 // graphics inside tables or figure floats can't go on
3351 // title (the equivalente in latex for this case is caption
3352 // and title should come first
3355 if (desc_on!= 3 || i!= 0) {
3356 if (!tmp_out.empty() && tmp_out[0] == '@') {
3358 extra += frontStrip(tmp_out, '@');
3360 os << frontStrip(tmp_out, '@');
3367 if (par->linuxDocConvertChar(c, sgml_string)
3368 && !style.free_spacing) { // in freespacing
3370 // non-breaking characters
3374 os << "\n</term><listitem><para>";
3387 os << "</emphasis>";
3390 // resets description flag correctly
3392 // <term> not closed...
3395 if(style.free_spacing) os << '\n';
3399 // This should be enabled when the Chktex class is implemented. (Asger)
3400 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3401 // Other flags: -wall -v0 -x
3402 int Buffer::runChktex()
3404 if (!users->text) return 0;
3406 users->owner()->prohibitInput();
3408 // get LaTeX-Filename
3409 string const name = getLatexName();
3410 string path = OnlyPath(filename);
3412 string const org_path = path;
3413 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3417 Path p(path); // path to LaTeX file
3418 users->owner()->message(_("Running chktex..."));
3420 // Remove all error insets
3421 bool const removedErrorInsets = users->removeAutoInsets();
3423 // Generate the LaTeX file if neccessary
3424 makeLaTeXFile(name, org_path, false);
3427 Chktex chktex(lyxrc.chktex_command, name, filepath);
3428 int res = chktex.run(terr); // run chktex
3431 WriteAlert(_("chktex did not work!"),
3432 _("Could not run with file:"), name);
3433 } else if (res > 0) {
3434 // Insert all errors as errors boxes
3435 users->insertErrors(terr);
3438 // if we removed error insets before we ran chktex or if we inserted
3439 // error insets after we ran chktex, this must be run:
3440 if (removedErrorInsets || res){
3444 users->owner()->allowInput();
3450 void Buffer::validate(LaTeXFeatures & features) const
3452 Paragraph * par = paragraph;
3453 LyXTextClass const & tclass =
3454 textclasslist.TextClass(params.textclass);
3456 // AMS Style is at document level
3457 features.amsstyle = (params.use_amsmath ||
3458 tclass.provides(LyXTextClass::amsmath));
3461 // We don't use "lyxerr.debug" because of speed. (Asger)
3462 if (lyxerr.debugging(Debug::LATEX))
3463 lyxerr << "Paragraph: " << par << endl;
3465 // Now just follow the list of paragraphs and run
3466 // validate on each of them.
3467 par->validate(features);
3469 // and then the next paragraph
3473 // the bullet shapes are buffer level not paragraph level
3474 // so they are tested here
3475 for (int i = 0; i < 4; ++i) {
3476 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3477 int const font = params.user_defined_bullets[i].getFont();
3479 int const c = params
3480 .user_defined_bullets[i]
3487 features.latexsym = true;
3489 } else if (font == 1) {
3490 features.amssymb = true;
3491 } else if ((font >= 2 && font <= 5)) {
3492 features.pifont = true;
3497 if (lyxerr.debugging(Debug::LATEX)) {
3498 features.showStruct();
3503 void Buffer::setPaperStuff()
3505 params.papersize = BufferParams::PAPER_DEFAULT;
3506 char const c1 = params.paperpackage;
3507 if (c1 == BufferParams::PACKAGE_NONE) {
3508 char const c2 = params.papersize2;
3509 if (c2 == BufferParams::VM_PAPER_USLETTER)
3510 params.papersize = BufferParams::PAPER_USLETTER;
3511 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3512 params.papersize = BufferParams::PAPER_LEGALPAPER;
3513 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3514 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3515 else if (c2 == BufferParams::VM_PAPER_A3)
3516 params.papersize = BufferParams::PAPER_A3PAPER;
3517 else if (c2 == BufferParams::VM_PAPER_A4)
3518 params.papersize = BufferParams::PAPER_A4PAPER;
3519 else if (c2 == BufferParams::VM_PAPER_A5)
3520 params.papersize = BufferParams::PAPER_A5PAPER;
3521 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3522 (c2 == BufferParams::VM_PAPER_B5))
3523 params.papersize = BufferParams::PAPER_B5PAPER;
3524 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3525 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3526 params.papersize = BufferParams::PAPER_A4PAPER;
3530 // This function should be in Buffer because it's a buffer's property (ale)
3531 string const Buffer::getIncludeonlyList(char delim)
3534 for (inset_iterator it = inset_iterator_begin();
3535 it != inset_iterator_end(); ++it) {
3536 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3537 InsetInclude * insetinc =
3538 static_cast<InsetInclude *>(*it);
3539 if (insetinc->isIncludeOnly()) {
3542 lst += insetinc->getRelFileBaseName();
3546 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3551 vector<string> const Buffer::getLabelList()
3553 /// if this is a child document and the parent is already loaded
3554 /// Use the parent's list instead [ale990407]
3555 if (!params.parentname.empty()
3556 && bufferlist.exists(params.parentname)) {
3557 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3559 return tmp->getLabelList();
3562 vector<string> label_list;
3563 for (inset_iterator it = inset_iterator_begin();
3564 it != inset_iterator_end(); ++it) {
3565 vector<string> const l = (*it)->getLabelList();
3566 label_list.insert(label_list.end(), l.begin(), l.end());
3572 Buffer::Lists const Buffer::getLists() const
3575 Paragraph * par = paragraph;
3577 LyXTextClassList::size_type cap;
3578 boost::tie(found, cap) = textclasslist
3579 .NumberOfLayout(params.textclass, "Caption");
3582 char const labeltype =
3583 textclasslist.Style(params.textclass,
3584 par->getLayout()).labeltype;
3586 if (labeltype >= LABEL_COUNTER_CHAPTER
3587 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3588 // insert this into the table of contents
3589 SingleList & item = l["TOC"];
3592 textclasslist.TextClass(params.textclass).maxcounter());
3593 item.push_back(TocItem(par, depth, par->asString(this, true)));
3595 // For each paragrph, traverse its insets and look for
3599 Paragraph::inset_iterator it =
3600 par->inset_iterator_begin();
3601 Paragraph::inset_iterator end =
3602 par->inset_iterator_end();
3604 for (; it != end; ++it) {
3605 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3607 static_cast<InsetFloat*>(*it);
3609 string const type = il->type();
3611 // Now find the caption in the float...
3612 // We now tranverse the paragraphs of
3614 Paragraph * tmp = il->inset.paragraph();
3616 if (tmp->layout == cap) {
3617 SingleList & item = l[type];
3619 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3620 item.push_back(TocItem(tmp, 0 , str));
3627 lyxerr << "caption not found" << endl;
3636 // This is also a buffer property (ale)
3637 vector<pair<string, string> > const Buffer::getBibkeyList()
3639 /// if this is a child document and the parent is already loaded
3640 /// Use the parent's list instead [ale990412]
3641 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3642 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3644 return tmp->getBibkeyList();
3647 vector<pair<string, string> > keys;
3648 Paragraph * par = paragraph;
3651 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3652 par->asString(this, false)));
3656 // Might be either using bibtex or a child has bibliography
3658 for (inset_iterator it = inset_iterator_begin();
3659 it != inset_iterator_end(); ++it) {
3660 // Search for Bibtex or Include inset
3661 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3662 vector<pair<string,string> > tmp =
3663 static_cast<InsetBibtex*>(*it)->getKeys(this);
3664 keys.insert(keys.end(), tmp.begin(), tmp.end());
3665 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3666 vector<pair<string,string> > const tmp =
3667 static_cast<InsetInclude*>(*it)->getKeys();
3668 keys.insert(keys.end(), tmp.begin(), tmp.end());
3677 bool Buffer::isDepClean(string const & name) const
3679 DEPCLEAN * item = dep_clean;
3680 while (item && item->master != name)
3682 if (!item) return true;
3687 void Buffer::markDepClean(string const & name)
3690 dep_clean = new DEPCLEAN;
3691 dep_clean->clean = true;
3692 dep_clean->master = name;
3693 dep_clean->next = 0;
3695 DEPCLEAN * item = dep_clean;
3696 while (item && item->master != name)
3701 item = new DEPCLEAN;
3703 item->master = name;
3710 bool Buffer::dispatch(string const & command)
3712 // Split command string into command and argument
3714 string line = frontStrip(command);
3715 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3717 return dispatch(lyxaction.LookupFunc(cmd), arg);
3721 bool Buffer::dispatch(int action, string const & argument)
3723 bool dispatched = true;
3726 Exporter::Export(this, argument, false);
3736 void Buffer::resizeInsets(BufferView * bv)
3738 /// then remove all LyXText in text-insets
3739 Paragraph * par = paragraph;
3740 for (; par; par = par->next()) {
3741 par->resizeInsetsLyXText(bv);
3746 void Buffer::redraw()
3753 void Buffer::changeLanguage(Language const * from, Language const * to)
3756 Paragraph * par = paragraph;
3758 par->changeLanguage(params, from, to);
3764 bool Buffer::isMultiLingual()
3766 Paragraph * par = paragraph;
3768 if (par->isMultiLingual(params))
3776 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3777 Paragraph::size_type pos)
3780 it = par->InsetIterator(pos);
3781 if (it == par->inset_iterator_end()) {
3788 void Buffer::inset_iterator::setParagraph()
3791 it = par->inset_iterator_begin();
3792 if (it != par->inset_iterator_end())
3797 // We maintain an invariant that whenever par = 0 then it = 0
3801 Inset * Buffer::getInsetFromID(int id_arg) const
3803 for (inset_iterator it = inset_const_iterator_begin();
3804 it != inset_const_iterator_end(); ++it)
3806 if ((*it)->id() == id_arg)
3808 Inset * in = (*it)->getInsetFromID(id_arg);
3816 Paragraph * Buffer::getParFromID(int id) const
3818 if (id < 0) return 0;
3819 Paragraph * par = paragraph;
3821 if (par->id() == id) {
3824 Paragraph * tmp = par->getParFromID(id);