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/insetinfo.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/insetlist.h"
78 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82 #include "support/filetools.h"
83 #include "support/path.h"
84 #include "support/os.h"
89 #include "LaTeXFeatures.h"
90 #include "support/syscall.h"
91 #include "support/lyxlib.h"
92 #include "support/FileInfo.h"
93 #include "support/lyxmanip.h"
97 #include "lyx_gui_misc.h" // WarnReadonly()
98 #include "frontends/Dialogs.h"
100 #include "exporter.h"
101 #include "Lsstream.h"
102 #include "converter.h"
103 #include "BufferView.h"
104 #include "ParagraphParameters.h"
106 using std::stringstream;
115 using std::make_pair;
123 // all these externs should eventually be removed.
124 extern BufferList bufferlist;
126 extern LyXAction lyxaction;
130 const int LYX_FORMAT = 218;
134 extern int tex_code_break_column;
137 Buffer::Buffer(string const & file, bool ronly)
139 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
141 filepath = OnlyPath(file);
150 if (read_only || (lyxrc.use_tempdir)) {
151 tmppath = CreateBufferTmpDir();
152 } else tmppath.erase();
158 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
159 // here the buffer should take care that it is
160 // saved properly, before it goes into the void.
162 // make sure that views using this buffer
167 if (!tmppath.empty()) {
168 DestroyBufferTmpDir(tmppath);
171 Paragraph * par = paragraph;
174 tmppar = par->next();
182 string const Buffer::getLatexName(bool no_path) const
184 string name = ChangeExtension(MakeLatexName(filename), ".tex");
186 return OnlyFilename(name);
192 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
194 string const filename = getLatexName(false);
196 if (filename.empty())
197 return make_pair(Buffer::latexlog, string());
199 string path = OnlyPath(filename);
201 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
204 string const fname = AddName(path,
205 OnlyFilename(ChangeExtension(filename,
208 AddName(path, OnlyFilename(
209 ChangeExtension(filename,
210 formats.Extension("literate") + ".out")));
212 // If no Latex log or Build log is newer, show Build log
214 FileInfo const f_fi(fname);
215 FileInfo const b_fi(bname);
218 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
219 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
220 return make_pair(Buffer::buildlog, bname);
222 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
223 return make_pair(Buffer::latexlog, fname);
227 void Buffer::setReadonly(bool flag)
229 if (read_only != flag) {
232 users->owner()->getDialogs()->updateBufferDependent(false);
235 WarnReadonly(filename);
240 bool Buffer::saveParamsAsDefaults() // const
242 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
244 Buffer defaults = Buffer(fname);
246 // Use the current buffer's parameters as default
247 defaults.params = params;
249 // add an empty paragraph. Is this enough?
250 defaults.paragraph = new Paragraph;
252 return defaults.writeFile(defaults.filename, false);
256 /// Update window titles of all users
257 // Should work on a list
258 void Buffer::updateTitles() const
260 if (users) users->owner()->updateWindowTitle();
264 /// Reset autosave timer of all users
265 // Should work on a list
266 void Buffer::resetAutosaveTimers() const
268 if (users) users->owner()->resetAutosaveTimer();
272 void Buffer::setFileName(string const & newfile)
274 filename = MakeAbsPath(newfile);
275 filepath = OnlyPath(filename);
276 setReadonly(IsFileWriteable(filename) == 0);
281 // candidate for move to BufferView
282 // (at least some parts in the beginning of the func)
285 // changed to be public and have one parameter
286 // if par = 0 normal behavior
287 // else insert behavior
288 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
289 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
292 Paragraph::depth_type depth = 0;
293 bool the_end_read = false;
295 Paragraph * return_par = 0;
296 LyXFont font(LyXFont::ALL_INHERIT, params.language);
297 if (file_format < 216 && params.language->lang() == "hebrew")
298 font.setLanguage(default_language);
299 // If we are inserting, we cheat and get a token in advance
300 bool has_token = false;
306 // We are inserting into an existing document
307 users->text->breakParagraph(users);
308 return_par = users->text->firstParagraph();
311 // We don't want to adopt the parameters from the
312 // document we insert, so we skip until the text begins:
315 pretoken = lex.GetString();
316 if (pretoken == "\\layout") {
328 pretoken = lex.GetString();
331 if (pretoken.empty()) continue;
334 parseSingleLyXformat2Token(lex, par, return_par,
335 pretoken, pos, depth,
343 paragraph = return_par;
349 // We'll remove this later. (Lgb)
352 string last_inset_read;
358 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
359 Paragraph *& return_par,
360 string const & token, int & pos,
361 Paragraph::depth_type & depth,
365 bool the_end_read = false;
366 #ifndef NO_PEXTRA_REALLY
367 // This is super temporary but is needed to get the compability
368 // mode for minipages work correctly together with new tabulars.
369 static int call_depth;
371 bool checkminipage = false;
372 static Paragraph * minipar;
373 static Paragraph * parBeforeMinipage;
376 if (token[0] != '\\') {
377 for (string::const_iterator cit = token.begin();
378 cit != token.end(); ++cit) {
379 par->insertChar(pos, (*cit), font);
382 checkminipage = true;
383 } else if (token == "\\i") {
384 Inset * inset = new InsetLatexAccent;
385 inset->Read(this, lex);
386 par->insertInset(pos, inset, font);
388 } else if (token == "\\layout") {
390 string const layoutname = lex.GetString();
391 pair<bool, LyXTextClass::LayoutList::size_type> pp
392 = textclasslist.NumberOfLayout(params.textclass,
396 // The is the compability reading of layout caption.
397 // It can be removed in LyX version 1.3.0. (Lgb)
398 if (compare_no_case(layoutname, "caption") == 0) {
399 // We expect that the par we are now working on is
400 // really inside a InsetText inside a InsetFloat.
401 // We also know that captions can only be
402 // one paragraph. (Lgb)
404 // We should now read until the next "\layout"
406 // This is probably not good enough, what if the
407 // caption is the last par in the document (Lgb)
408 istream & ist = lex.getStream();
414 if (prefixIs(line, "\\layout")) {
418 if (prefixIs(line, "\\begin_inset"))
420 if (prefixIs(line, "\\end_inset")) {
431 // Now we should have the whole layout in ss
432 // we should now be able to give this to the
434 ss << "\\end_inset\n";
436 // This seems like a bug in stringstream.
437 // We really should be able to use ss
439 istringstream is(ss.str());
441 tmplex.setStream(is);
442 Inset * inset = new InsetCaption;
443 inset->Read(this, tmplex);
444 par->InsertInset(pos, inset, font);
451 par = new Paragraph(par);
455 par->layout = pp.second;
458 // use default layout "Standard" (0)
461 // Test whether the layout is obsolete.
462 LyXLayout const & layout =
463 textclasslist.Style(params.textclass,
465 if (!layout.obsoleted_by().empty())
466 par->layout = textclasslist
467 .NumberOfLayout(params.textclass,
468 layout.obsoleted_by())
470 par->params().depth(depth);
471 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
472 if (file_format < 216
473 && params.language->lang() == "hebrew")
474 font.setLanguage(default_language);
479 } else if (token == "\\begin_float") {
480 // This is the compability reader. It can be removed in
481 // LyX version 1.3.0. (Lgb)
483 string const tmptok = lex.GetString();
484 //lyxerr << "old float: " << tmptok << endl;
487 stringstream old_float;
489 if (tmptok == "footnote") {
490 inset = new InsetFoot;
491 } else if (tmptok == "margin") {
492 inset = new InsetMarginal;
493 } else if (tmptok == "fig") {
494 inset = new InsetFloat("figure");
495 old_float << "placement htbp\n"
497 } else if (tmptok == "tab") {
498 inset = new InsetFloat("table");
499 old_float << "placement htbp\n"
501 } else if (tmptok == "alg") {
502 inset = new InsetFloat("algorithm");
503 old_float << "placement htbp\n"
505 } else if (tmptok == "wide-fig") {
506 inset = new InsetFloat("figure");
507 //InsetFloat * tmp = new InsetFloat("figure");
510 old_float << "placement htbp\n"
512 } else if (tmptok == "wide-tab") {
513 inset = new InsetFloat("table");
514 //InsetFloat * tmp = new InsetFloat("table");
517 old_float << "placement htbp\n"
523 return false; // no end read yet
526 old_float << "collapsed true\n";
528 // Here we need to check for \end_deeper and handle that
529 // before we do the footnote parsing.
530 // This _is_ a hack! (Lgb)
533 string const tmp = lex.GetString();
534 if (tmp == "\\end_deeper") {
535 //lyxerr << "\\end_deeper caught!" << endl;
537 lex.printError("\\end_deeper: "
538 "depth is already null");
543 old_float << tmp << ' ';
548 old_float << lex.getLongString("\\end_float")
549 << "\n\\end_inset\n";
550 //lyxerr << "Float Body:\n" << old_float.str() << endl;
551 // That this does not work seems like a bug
552 // in stringstream. (Lgb)
553 istringstream istr(old_float.str());
555 nylex.setStream(istr);
556 inset->Read(this, nylex);
557 par->insertInset(pos, inset, font);
559 } else if (token == "\\begin_deeper") {
561 } else if (token == "\\end_deeper") {
563 lex.printError("\\end_deeper: "
564 "depth is already null");
568 } else if (token == "\\begin_preamble") {
569 params.readPreamble(lex);
570 } else if (token == "\\textclass") {
572 pair<bool, LyXTextClassList::size_type> pp =
573 textclasslist.NumberOfClass(lex.GetString());
575 params.textclass = pp.second;
577 WriteAlert(string(_("Textclass error")),
578 string(_("The document uses an unknown textclass \"")) +
579 lex.GetString() + string("\"."),
580 string(_("LyX will not be able to produce output correctly.")));
581 params.textclass = 0;
583 if (!textclasslist.Load(params.textclass)) {
584 // if the textclass wasn't loaded properly
585 // we need to either substitute another
586 // or stop loading the file.
587 // I can substitute but I don't see how I can
588 // stop loading... ideas?? ARRae980418
589 WriteAlert(_("Textclass Loading Error!"),
590 string(_("Can't load textclass ")) +
591 textclasslist.NameOfClass(params.textclass),
592 _("-- substituting default"));
593 params.textclass = 0;
595 } else if (token == "\\options") {
597 params.options = lex.GetString();
598 } else if (token == "\\language") {
599 params.readLanguage(lex);
600 } else if (token == "\\fontencoding") {
602 } else if (token == "\\inputencoding") {
604 params.inputenc = lex.GetString();
605 } else if (token == "\\graphics") {
606 params.readGraphicsDriver(lex);
607 } else if (token == "\\fontscheme") {
609 params.fonts = lex.GetString();
610 } else if (token == "\\noindent") {
611 par->params().noindent(true);
612 } else if (token == "\\fill_top") {
613 par->params().spaceTop(VSpace(VSpace::VFILL));
614 } else if (token == "\\fill_bottom") {
615 par->params().spaceBottom(VSpace(VSpace::VFILL));
616 } else if (token == "\\line_top") {
617 par->params().lineTop(true);
618 } else if (token == "\\line_bottom") {
619 par->params().lineBottom(true);
620 } else if (token == "\\pagebreak_top") {
621 par->params().pagebreakTop(true);
622 } else if (token == "\\pagebreak_bottom") {
623 par->params().pagebreakBottom(true);
624 } else if (token == "\\start_of_appendix") {
625 par->params().startOfAppendix(true);
626 } else if (token == "\\paragraph_separation") {
627 int tmpret = lex.FindToken(string_paragraph_separation);
628 if (tmpret == -1) ++tmpret;
629 if (tmpret != LYX_LAYOUT_DEFAULT)
630 params.paragraph_separation =
631 static_cast<BufferParams::PARSEP>(tmpret);
632 } else if (token == "\\defskip") {
634 params.defskip = VSpace(lex.GetString());
635 } else if (token == "\\epsfig") { // obsolete
636 // Indeed it is obsolete, but we HAVE to be backwards
637 // compatible until 0.14, because otherwise all figures
638 // in existing documents are irretrivably lost. (Asger)
639 params.readGraphicsDriver(lex);
640 } else if (token == "\\quotes_language") {
641 int tmpret = lex.FindToken(string_quotes_language);
642 if (tmpret == -1) ++tmpret;
643 if (tmpret != LYX_LAYOUT_DEFAULT) {
644 InsetQuotes::quote_language tmpl =
645 InsetQuotes::EnglishQ;
648 tmpl = InsetQuotes::EnglishQ;
651 tmpl = InsetQuotes::SwedishQ;
654 tmpl = InsetQuotes::GermanQ;
657 tmpl = InsetQuotes::PolishQ;
660 tmpl = InsetQuotes::FrenchQ;
663 tmpl = InsetQuotes::DanishQ;
666 params.quotes_language = tmpl;
668 } else if (token == "\\quotes_times") {
670 switch (lex.GetInteger()) {
672 params.quotes_times = InsetQuotes::SingleQ;
675 params.quotes_times = InsetQuotes::DoubleQ;
678 } else if (token == "\\papersize") {
679 int tmpret = lex.FindToken(string_papersize);
683 params.papersize2 = tmpret;
684 } else if (token == "\\paperpackage") {
685 int tmpret = lex.FindToken(string_paperpackages);
688 params.paperpackage = BufferParams::PACKAGE_NONE;
690 params.paperpackage = tmpret;
691 } else if (token == "\\use_geometry") {
693 params.use_geometry = lex.GetInteger();
694 } else if (token == "\\use_amsmath") {
696 params.use_amsmath = lex.GetInteger();
697 } else if (token == "\\paperorientation") {
698 int tmpret = lex.FindToken(string_orientation);
699 if (tmpret == -1) ++tmpret;
700 if (tmpret != LYX_LAYOUT_DEFAULT)
701 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
702 } else if (token == "\\paperwidth") {
704 params.paperwidth = lex.GetString();
705 } else if (token == "\\paperheight") {
707 params.paperheight = lex.GetString();
708 } else if (token == "\\leftmargin") {
710 params.leftmargin = lex.GetString();
711 } else if (token == "\\topmargin") {
713 params.topmargin = lex.GetString();
714 } else if (token == "\\rightmargin") {
716 params.rightmargin = lex.GetString();
717 } else if (token == "\\bottommargin") {
719 params.bottommargin = lex.GetString();
720 } else if (token == "\\headheight") {
722 params.headheight = lex.GetString();
723 } else if (token == "\\headsep") {
725 params.headsep = lex.GetString();
726 } else if (token == "\\footskip") {
728 params.footskip = lex.GetString();
729 } else if (token == "\\paperfontsize") {
731 params.fontsize = strip(lex.GetString());
732 } else if (token == "\\papercolumns") {
734 params.columns = lex.GetInteger();
735 } else if (token == "\\papersides") {
737 switch (lex.GetInteger()) {
739 case 1: params.sides = LyXTextClass::OneSide; break;
740 case 2: params.sides = LyXTextClass::TwoSides; break;
742 } else if (token == "\\paperpagestyle") {
744 params.pagestyle = strip(lex.GetString());
745 } else if (token == "\\bullet") {
747 int const index = lex.GetInteger();
749 int temp_int = lex.GetInteger();
750 params.user_defined_bullets[index].setFont(temp_int);
751 params.temp_bullets[index].setFont(temp_int);
753 temp_int = lex.GetInteger();
754 params.user_defined_bullets[index].setCharacter(temp_int);
755 params.temp_bullets[index].setCharacter(temp_int);
757 temp_int = lex.GetInteger();
758 params.user_defined_bullets[index].setSize(temp_int);
759 params.temp_bullets[index].setSize(temp_int);
761 string const temp_str = lex.GetString();
762 if (temp_str != "\\end_bullet") {
763 // this element isn't really necessary for
764 // parsing but is easier for humans
765 // to understand bullets. Put it back and
766 // set a debug message?
767 lex.printError("\\end_bullet expected, got" + temp_str);
768 //how can I put it back?
770 } else if (token == "\\bulletLaTeX") {
772 int const index = lex.GetInteger();
774 string temp_str = lex.GetString();
776 while (temp_str != "\\end_bullet") {
777 // this loop structure is needed when user
778 // enters an empty string since the first
779 // thing returned will be the \\end_bullet
781 // if the LaTeX entry has spaces. Each element
782 // therefore needs to be read in turn
785 temp_str = lex.GetString();
787 params.user_defined_bullets[index].setText(sum_str);
788 params.temp_bullets[index].setText(sum_str);
789 } else if (token == "\\secnumdepth") {
791 params.secnumdepth = lex.GetInteger();
792 } else if (token == "\\tocdepth") {
794 params.tocdepth = lex.GetInteger();
795 } else if (token == "\\spacing") {
797 string const tmp = strip(lex.GetString());
798 Spacing::Space tmp_space = Spacing::Default;
800 if (tmp == "single") {
801 tmp_space = Spacing::Single;
802 } else if (tmp == "onehalf") {
803 tmp_space = Spacing::Onehalf;
804 } else if (tmp == "double") {
805 tmp_space = Spacing::Double;
806 } else if (tmp == "other") {
808 tmp_space = Spacing::Other;
809 tmp_val = lex.GetFloat();
811 lex.printError("Unknown spacing token: '$$Token'");
813 // Small hack so that files written with klyx will be
816 par->params().spacing(Spacing(tmp_space, tmp_val));
818 params.spacing.set(tmp_space, tmp_val);
820 } else if (token == "\\paragraph_spacing") {
822 string const tmp = strip(lex.GetString());
823 if (tmp == "single") {
824 par->params().spacing(Spacing(Spacing::Single));
825 } else if (tmp == "onehalf") {
826 par->params().spacing(Spacing(Spacing::Onehalf));
827 } else if (tmp == "double") {
828 par->params().spacing(Spacing(Spacing::Double));
829 } else if (tmp == "other") {
831 par->params().spacing(Spacing(Spacing::Other,
834 lex.printError("Unknown spacing token: '$$Token'");
836 } else if (token == "\\float_placement") {
838 params.float_placement = lex.GetString();
839 } else if (token == "\\family") {
841 font.setLyXFamily(lex.GetString());
842 } else if (token == "\\series") {
844 font.setLyXSeries(lex.GetString());
845 } else if (token == "\\shape") {
847 font.setLyXShape(lex.GetString());
848 } else if (token == "\\size") {
850 font.setLyXSize(lex.GetString());
851 } else if (token == "\\latex") {
853 string const tok = lex.GetString();
854 // This is dirty, but gone with LyX3. (Asger)
855 if (tok == "no_latex")
856 font.setLatex(LyXFont::OFF);
857 else if (tok == "latex")
858 font.setLatex(LyXFont::ON);
859 else if (tok == "default")
860 font.setLatex(LyXFont::INHERIT);
862 lex.printError("Unknown LaTeX font flag "
864 } else if (token == "\\lang") {
866 string const tok = lex.GetString();
867 Language const * lang = languages.getLanguage(tok);
869 font.setLanguage(lang);
871 font.setLanguage(params.language);
872 lex.printError("Unknown language `$$Token'");
874 } else if (token == "\\numeric") {
876 font.setNumber(font.setLyXMisc(lex.GetString()));
877 } else if (token == "\\emph") {
879 font.setEmph(font.setLyXMisc(lex.GetString()));
880 } else if (token == "\\bar") {
882 string const tok = lex.GetString();
883 // This is dirty, but gone with LyX3. (Asger)
885 font.setUnderbar(LyXFont::ON);
886 else if (tok == "no")
887 font.setUnderbar(LyXFont::OFF);
888 else if (tok == "default")
889 font.setUnderbar(LyXFont::INHERIT);
891 lex.printError("Unknown bar font flag "
893 } else if (token == "\\noun") {
895 font.setNoun(font.setLyXMisc(lex.GetString()));
896 } else if (token == "\\color") {
898 font.setLyXColor(lex.GetString());
899 } else if (token == "\\align") {
900 int tmpret = lex.FindToken(string_align);
901 if (tmpret == -1) ++tmpret;
902 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
903 int const tmpret2 = int(pow(2.0, tmpret));
904 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
905 par->params().align(LyXAlignment(tmpret2));
907 } else if (token == "\\added_space_top") {
909 par->params().spaceTop(VSpace(lex.GetString()));
910 } else if (token == "\\added_space_bottom") {
912 par->params().spaceBottom(VSpace(lex.GetString()));
913 #ifndef NO_PEXTRA_REALLY
914 } else if (token == "\\pextra_type") {
916 par->params().pextraType(lex.GetInteger());
917 } else if (token == "\\pextra_width") {
919 par->params().pextraWidth(lex.GetString());
920 } else if (token == "\\pextra_widthp") {
922 par->params().pextraWidthp(lex.GetString());
923 } else if (token == "\\pextra_alignment") {
925 par->params().pextraAlignment(lex.GetInteger());
926 } else if (token == "\\pextra_hfill") {
928 par->params().pextraHfill(lex.GetInteger());
929 } else if (token == "\\pextra_start_minipage") {
931 par->params().pextraStartMinipage(lex.GetInteger());
933 } else if (token == "\\labelwidthstring") {
935 par->params().labelWidthString(lex.GetString());
936 // do not delete this token, it is still needed!
937 } else if (token == "\\end_inset") {
938 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
939 << "Last inset read was: " << last_inset_read
941 // Simply ignore this. The insets do not have
943 // But insets should read it, it is a part of
944 // the inset isn't it? Lgb.
945 } else if (token == "\\begin_inset") {
946 readInset(lex, par, pos, font);
947 } else if (token == "\\SpecialChar") {
948 LyXLayout const & layout =
949 textclasslist.Style(params.textclass,
952 // Insets don't make sense in a free-spacing context! ---Kayvan
953 if (layout.free_spacing) {
956 string next_token = lex.GetString();
957 if (next_token == "\\-") {
958 par->insertChar(pos, '-', font);
959 } else if (next_token == "\\protected_separator"
960 || next_token == "~") {
961 par->insertChar(pos, ' ', font);
963 lex.printError("Token `$$Token' "
965 "paragraph layout!");
970 Inset * inset = new InsetSpecialChar;
971 inset->Read(this, lex);
972 par->insertInset(pos, inset, font);
975 } else if (token == "\\newline") {
976 par->insertChar(pos, Paragraph::META_NEWLINE, font);
978 } else if (token == "\\LyXTable") {
979 Inset * inset = new InsetTabular(*this);
980 inset->Read(this, lex);
981 par->insertInset(pos, inset, font);
983 // because of OLD_TABULAR_READ where tabulars have been
985 checkminipage = true;
986 } else if (token == "\\hfill") {
987 par->insertChar(pos, Paragraph::META_HFILL, font);
989 } else if (token == "\\protected_separator") { // obsolete
990 // This is a backward compability thingie. (Lgb)
991 // Remove it later some time...introduced with fileformat
993 LyXLayout const & layout =
994 textclasslist.Style(params.textclass,
997 if (layout.free_spacing) {
998 par->insertChar(pos, ' ', font);
1000 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1001 par->insertInset(pos, inset, font);
1004 } else if (token == "\\bibitem") { // ale970302
1006 InsetCommandParams p("bibitem", "dummy");
1007 par->bibkey = new InsetBibKey(p);
1009 par->bibkey->Read(this, lex);
1010 } else if (token == "\\backslash") {
1011 par->insertChar(pos, '\\', font);
1013 } else if (token == "\\the_end") {
1014 the_end_read = true;
1015 minipar = parBeforeMinipage = 0;
1017 // This should be insurance for the future: (Asger)
1018 lex.printError("Unknown token `$$Token'. "
1019 "Inserting as text.");
1020 string::const_iterator cit = token.begin();
1021 string::const_iterator end = token.end();
1022 for (; cit != end; ++cit) {
1023 par->insertChar(pos, (*cit), font);
1027 #ifndef NO_PEXTRA_REALLY
1028 // now check if we have a minipage paragraph as at this
1029 // point we already read all the necessary data!
1030 // this cannot be done in layout because there we did
1031 // not read yet the paragraph PEXTRA-params (Jug)
1033 // BEGIN pextra_minipage compability
1034 // This should be removed in 1.3.x (Lgb)
1036 // This compability code is not perfect. In a couple
1037 // of rand cases it fails. When the minipage par is
1038 // the first par in the document, and when there are
1039 // none or only one regular paragraphs after the
1040 // minipage. Currently I am not investing any effort
1041 // in fixing those cases.
1043 //lyxerr << "Call depth: " << call_depth << endl;
1044 if (checkminipage && (call_depth == 1)) {
1045 checkminipage = false;
1046 if (minipar && (minipar != par) &&
1047 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1049 lyxerr << "minipages in a row" << endl;
1050 if (par->params().pextraStartMinipage()) {
1051 lyxerr << "start new minipage" << endl;
1052 // minipages in a row
1053 par->previous()->next(0);
1056 Paragraph * tmp = minipar;
1058 tmp->params().pextraType(0);
1059 tmp->params().pextraWidth(string());
1060 tmp->params().pextraWidthp(string());
1061 tmp->params().pextraAlignment(0);
1062 tmp->params().pextraHfill(false);
1063 tmp->params().pextraStartMinipage(false);
1066 // create a new paragraph to insert the
1067 // minipages in the following case
1068 if (par->params().pextraStartMinipage() &&
1069 !par->params().pextraHfill())
1071 Paragraph * p = new Paragraph;
1073 p->previous(parBeforeMinipage);
1074 parBeforeMinipage->next(p);
1076 p->params().depth(parBeforeMinipage->params().depth());
1077 parBeforeMinipage = p;
1079 InsetMinipage * mini = new InsetMinipage;
1080 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1081 mini->width(par->params().pextraWidth());
1082 if (!par->params().pextraWidthp().empty()) {
1083 lyxerr << "WP:" << mini->width() << endl;
1084 mini->width(tostr(par->params().pextraWidthp())+"%");
1086 mini->inset.par = par;
1087 // Insert the minipage last in the
1088 // previous paragraph.
1089 if (par->params().pextraHfill()) {
1090 parBeforeMinipage->insertChar
1091 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1093 parBeforeMinipage->insertInset
1094 (parBeforeMinipage->size(), mini);
1098 lyxerr << "new minipage par" << endl;
1099 //nothing to do just continue reading
1102 } else if (minipar && (minipar != par)) {
1103 lyxerr << "last minipage par read" << endl;
1104 // The last paragraph read was not part of a
1105 // minipage but the par linked list is...
1106 // So we need to remove the last par from the
1108 if (par->previous())
1109 par->previous()->next(0);
1110 par->previous(parBeforeMinipage);
1111 parBeforeMinipage->next(par);
1112 Paragraph * tmp = minipar;
1114 tmp->params().pextraType(0);
1115 tmp->params().pextraWidth(string());
1116 tmp->params().pextraWidthp(string());
1117 tmp->params().pextraAlignment(0);
1118 tmp->params().pextraHfill(false);
1119 tmp->params().pextraStartMinipage(false);
1122 depth = parBeforeMinipage->params().depth();
1123 minipar = parBeforeMinipage = 0;
1124 } else if (!minipar &&
1125 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1127 // par is the first paragraph in a minipage
1128 lyxerr << "begin minipage" << endl;
1129 // To minimize problems for
1130 // the users we will insert
1131 // the first minipage in
1132 // a sequence of minipages
1133 // in its own paragraph.
1134 Paragraph * p = new Paragraph;
1136 p->previous(par->previous());
1138 p->params().depth(depth);
1139 par->params().depth(0);
1141 if (par->previous())
1142 par->previous()->next(p);
1144 parBeforeMinipage = p;
1146 if (!return_par || (return_par == par))
1149 InsetMinipage * mini = new InsetMinipage;
1150 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1151 mini->width(minipar->params().pextraWidth());
1152 if (!par->params().pextraWidthp().empty()) {
1153 lyxerr << "WP:" << mini->width() << endl;
1154 mini->width(tostr(par->params().pextraWidthp())+"%");
1156 mini->inset.par = minipar;
1158 // Insert the minipage last in the
1159 // previous paragraph.
1160 if (minipar->params().pextraHfill()) {
1161 parBeforeMinipage->insertChar
1162 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1164 parBeforeMinipage->insertInset
1165 (parBeforeMinipage->size(), mini);
1168 // End of pextra_minipage compability
1171 return the_end_read;
1175 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1176 int & pos, LyXFont & font)
1178 // consistency check
1179 if (lex.GetString() != "\\begin_inset") {
1180 lyxerr << "Buffer::readInset: Consistency check failed."
1187 string const tmptok = lex.GetString();
1188 last_inset_read = tmptok;
1190 // test the different insets
1191 if (tmptok == "LatexCommand") {
1192 InsetCommandParams inscmd;
1195 string const cmdName = inscmd.getCmdName();
1197 if (cmdName == "cite") {
1198 inset = new InsetCitation(inscmd);
1199 } else if (cmdName == "bibitem") {
1200 lex.printError("Wrong place for bibitem");
1201 inset = new InsetBibKey(inscmd);
1202 } else if (cmdName == "BibTeX") {
1203 inset = new InsetBibtex(inscmd);
1204 } else if (cmdName == "index") {
1205 inset = new InsetIndex(inscmd);
1206 } else if (cmdName == "include") {
1207 inset = new InsetInclude(inscmd, *this);
1208 } else if (cmdName == "label") {
1209 inset = new InsetLabel(inscmd);
1210 } else if (cmdName == "url"
1211 || cmdName == "htmlurl") {
1212 inset = new InsetUrl(inscmd);
1213 } else if (cmdName == "ref"
1214 || cmdName == "pageref"
1215 || cmdName == "vref"
1216 || cmdName == "vpageref"
1217 || cmdName == "prettyref") {
1218 if (!inscmd.getOptions().empty()
1219 || !inscmd.getContents().empty()) {
1220 inset = new InsetRef(inscmd, *this);
1222 } else if (cmdName == "tableofcontents") {
1223 inset = new InsetTOC(inscmd);
1224 } else if (cmdName == "listofalgorithms") {
1225 inset = new InsetFloatList("algorithm");
1226 } else if (cmdName == "listoffigures") {
1227 inset = new InsetFloatList("figure");
1228 } else if (cmdName == "listoftables") {
1229 inset = new InsetFloatList("table");
1230 } else if (cmdName == "printindex") {
1231 inset = new InsetPrintIndex(inscmd);
1232 } else if (cmdName == "lyxparent") {
1233 inset = new InsetParent(inscmd, *this);
1236 if (tmptok == "Quotes") {
1237 inset = new InsetQuotes;
1238 } else if (tmptok == "External") {
1239 inset = new InsetExternal;
1240 } else if (tmptok == "FormulaMacro") {
1241 inset = new InsetFormulaMacro;
1242 } else if (tmptok == "Formula") {
1243 inset = new InsetFormula;
1244 } else if (tmptok == "Figure") {
1245 inset = new InsetFig(100, 100, *this);
1246 } else if (tmptok == "Info") {
1247 inset = new InsetInfo;
1248 } else if (tmptok == "Include") {
1249 InsetCommandParams p( "Include" );
1250 inset = new InsetInclude(p, *this);
1251 } else if (tmptok == "ERT") {
1252 inset = new InsetERT;
1253 } else if (tmptok == "Tabular") {
1254 inset = new InsetTabular(*this);
1255 } else if (tmptok == "Text") {
1256 inset = new InsetText;
1257 } else if (tmptok == "Foot") {
1258 inset = new InsetFoot;
1259 } else if (tmptok == "Marginal") {
1260 inset = new InsetMarginal;
1261 } else if (tmptok == "Minipage") {
1262 inset = new InsetMinipage;
1263 } else if (tmptok == "Float") {
1265 string tmptok = lex.GetString();
1266 inset = new InsetFloat(tmptok);
1267 } else if (tmptok == "List") {
1268 inset = new InsetList;
1269 } else if (tmptok == "Theorem") {
1270 inset = new InsetList;
1271 } else if (tmptok == "Caption") {
1272 inset = new InsetCaption;
1273 } else if (tmptok == "GRAPHICS") {
1274 inset = new InsetGraphics;
1275 } else if (tmptok == "FloatList") {
1276 inset = new InsetFloatList;
1279 if (inset) inset->Read(this, lex);
1283 par->insertInset(pos, inset, font);
1289 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1293 string const token(lex.GetString());
1294 if (token == "\\lyxformat") { // the first token _must_ be...
1296 string tmp_format = lex.GetString();
1297 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1298 // if present remove ".," from string.
1299 string::size_type dot = tmp_format.find_first_of(".,");
1300 //lyxerr << " dot found at " << dot << endl;
1301 if (dot != string::npos)
1302 tmp_format.erase(dot, 1);
1303 file_format = strToInt(tmp_format);
1304 if (file_format == LYX_FORMAT) {
1306 } else if (file_format > LYX_FORMAT) {
1308 WriteAlert(_("Warning!"),
1309 _("LyX file format is newer that what"),
1310 _("is supported in this LyX version. Expect some problems."));
1312 } else if (file_format < LYX_FORMAT) {
1314 if (file_format < 200) {
1315 WriteAlert(_("ERROR!"),
1316 _("Old LyX file format found. "
1317 "Use LyX 0.10.x to read this!"));
1321 bool the_end = readLyXformat2(lex, par);
1323 // the_end was added in 213
1324 if (file_format < 213)
1328 WriteAlert(_("Warning!"),
1329 _("Reading of document is not complete"),
1330 _("Maybe the document is truncated"));
1332 } else { // "\\lyxformat" not found
1333 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1336 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1341 // Should probably be moved to somewhere else: BufferView? LyXView?
1342 bool Buffer::save() const
1344 // We don't need autosaves in the immediate future. (Asger)
1345 resetAutosaveTimers();
1349 if (lyxrc.make_backup) {
1350 s = fileName() + '~';
1351 if (!lyxrc.backupdir_path.empty())
1352 s = AddName(lyxrc.backupdir_path,
1353 subst(os::slashify_path(s),'/','!'));
1355 // Rename is the wrong way of making a backup,
1356 // this is the correct way.
1357 /* truss cp fil fil2:
1358 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1359 stat("LyXVC.lyx", 0xEFFFF688) = 0
1360 open("LyXVC.lyx", O_RDONLY) = 3
1361 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1362 fstat(4, 0xEFFFF508) = 0
1363 fstat(3, 0xEFFFF508) = 0
1364 read(3, " # T h i s f i l e w".., 8192) = 5579
1365 write(4, " # T h i s f i l e w".., 5579) = 5579
1366 read(3, 0xEFFFD4A0, 8192) = 0
1369 chmod("LyXVC3.lyx", 0100644) = 0
1370 lseek(0, 0, SEEK_CUR) = 46440
1374 // Should probably have some more error checking here.
1375 // Should be cleaned up in 0.13, at least a bit.
1376 // Doing it this way, also makes the inodes stay the same.
1377 // This is still not a very good solution, in particular we
1378 // might loose the owner of the backup.
1379 FileInfo finfo(fileName());
1380 if (finfo.exist()) {
1381 mode_t fmode = finfo.getMode();
1382 struct utimbuf times = {
1383 finfo.getAccessTime(),
1384 finfo.getModificationTime() };
1386 ifstream ifs(fileName().c_str());
1387 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1392 ::chmod(s.c_str(), fmode);
1394 if (::utime(s.c_str(), ×)) {
1395 lyxerr << "utime error." << endl;
1398 lyxerr << "LyX was not able to make "
1399 "backup copy. Beware." << endl;
1404 if (writeFile(fileName(), false)) {
1406 removeAutosaveFile(fileName());
1408 // Saving failed, so backup is not backup
1409 if (lyxrc.make_backup) {
1410 lyx::rename(s, fileName());
1418 // Returns false if unsuccesful
1419 bool Buffer::writeFile(string const & fname, bool flag) const
1421 // if flag is false writeFile will not create any GUI
1422 // warnings, only cerr.
1423 // Needed for autosave in background or panic save (Matthias 120496)
1425 if (read_only && (fname == filename)) {
1426 // Here we should come with a question if we should
1427 // perform the write anyway.
1429 lyxerr << _("Error! Document is read-only: ")
1432 WriteAlert(_("Error! Document is read-only: "),
1437 FileInfo finfo(fname);
1438 if (finfo.exist() && !finfo.writable()) {
1439 // Here we should come with a question if we should
1440 // try to do the save anyway. (i.e. do a chmod first)
1442 lyxerr << _("Error! Cannot write file: ")
1445 WriteFSAlert(_("Error! Cannot write file: "),
1450 ofstream ofs(fname.c_str());
1453 lyxerr << _("Error! Cannot open file: ")
1456 WriteFSAlert(_("Error! Cannot open file: "),
1462 // Use the standard "C" locale for file output.
1463 ofs.imbue(std::locale::classic());
1466 // The top of the file should not be written by params.
1468 // write out a comment in the top of the file
1469 ofs << '#' << LYX_DOCVERSION
1470 << " created this file. For more info see http://www.lyx.org/\n"
1471 << "\\lyxformat " << LYX_FORMAT << "\n";
1473 // now write out the buffer paramters.
1474 params.writeFile(ofs);
1476 Paragraph::depth_type depth = 0;
1478 // this will write out all the paragraphs
1479 // using recursive descent.
1480 paragraph->writeFile(this, ofs, params, depth);
1482 // Write marker that shows file is complete
1483 ofs << "\n\\the_end" << endl;
1487 // how to check if close went ok?
1488 // Following is an attempt... (BE 20001011)
1490 // good() returns false if any error occured, including some
1491 // formatting error.
1492 // bad() returns true if something bad happened in the buffer,
1493 // which should include file system full errors.
1500 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1502 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1512 string const Buffer::asciiParagraph(Paragraph const * par,
1513 unsigned int linelen) const
1515 ostringstream buffer;
1516 Paragraph::depth_type depth = 0;
1518 Paragraph::depth_type ltype_depth = 0;
1519 unsigned int currlinelen = 0;
1520 bool ref_printed = false;
1524 if (!par->previous()) {
1525 // begins or ends a deeper area ?
1526 if (depth != par->params().depth()) {
1527 if (par->params().depth() > depth) {
1528 while (par->params().depth() > depth) {
1532 while (par->params().depth() < depth) {
1538 // First write the layout
1539 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1540 if (tmp == "Itemize") {
1542 ltype_depth = depth + 1;
1543 } else if (tmp == "Enumerate") {
1545 ltype_depth = depth + 1;
1546 } else if (contains(tmp, "ection")) {
1548 ltype_depth = depth + 1;
1549 } else if (contains(tmp, "aragraph")) {
1551 ltype_depth = depth + 1;
1552 } else if (tmp == "Description") {
1554 ltype_depth = depth + 1;
1555 } else if (tmp == "Abstract") {
1558 } else if (tmp == "Bibliography") {
1566 /* maybe some vertical spaces */
1568 /* the labelwidthstring used in lists */
1572 /* some pagebreaks? */
1576 /* what about the alignment */
1578 lyxerr << "Should this ever happen?" << endl;
1581 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1582 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1583 if (!i && !noparbreak) {
1586 for (Paragraph::depth_type j = 0; j < depth; ++j)
1588 currlinelen = depth * 2;
1591 case 4: // (Sub)Paragraph
1592 case 5: // Description
1596 buffer << "Abstract\n\n";
1598 buffer << "Abstract: ";
1600 case 7: // Bibliography
1603 buffer << "References\n\n";
1605 buffer << "References: ";
1610 buffer << par->params().labelString() << " ";
1613 if (ltype_depth > depth) {
1614 for (Paragraph::depth_type j = ltype_depth - 1;
1617 currlinelen += (ltype_depth-depth)*2;
1620 LyXFont const font2 = par->getFontSettings(params, i);
1621 if (font1.latex() != font2.latex()) {
1622 if (font2.latex() == LyXFont::OFF)
1630 char c = par->getUChar(params, i);
1634 case Paragraph::META_INSET:
1636 Inset const * inset = par->getInset(i);
1638 if (!inset->Ascii(this, buffer)) {
1641 rsplit(buffer.str().c_str(),
1643 currlinelen += s.length();
1645 // to be sure it breaks paragraph
1646 currlinelen += linelen;
1652 case Paragraph::META_NEWLINE:
1655 for (Paragraph::depth_type j = 0;
1659 currlinelen = depth * 2;
1660 if (ltype_depth > depth) {
1661 for (Paragraph::depth_type j = ltype_depth;
1664 currlinelen += (ltype_depth - depth) * 2;
1668 case Paragraph::META_HFILL:
1677 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1678 (c == ' ') && ((i + 2) < par->size()))
1681 for (Paragraph::depth_type j = 0;
1684 currlinelen = depth * 2;
1685 if (ltype_depth > depth) {
1686 for (Paragraph::depth_type j = ltype_depth;
1689 currlinelen += (ltype_depth-depth)*2;
1691 } else if (c != '\0')
1694 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1699 return buffer.str().c_str();
1703 void Buffer::writeFileAscii(string const & fname, int linelen)
1705 ofstream ofs(fname.c_str());
1707 WriteFSAlert(_("Error: Cannot write file:"), fname);
1710 writeFileAscii(ofs, linelen);
1714 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1716 Paragraph * par = paragraph;
1718 ofs << asciiParagraph(par, linelen);
1726 void Buffer::makeLaTeXFile(string const & fname,
1727 string const & original_path,
1728 bool nice, bool only_body)
1730 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1732 niceFile = nice; // this will be used by Insetincludes.
1734 tex_code_break_column = lyxrc.ascii_linelen;
1736 LyXTextClass const & tclass =
1737 textclasslist.TextClass(params.textclass);
1739 ofstream ofs(fname.c_str());
1741 WriteFSAlert(_("Error: Cannot open file: "), fname);
1745 // validate the buffer.
1746 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1747 LaTeXFeatures features(params, tclass.numLayouts());
1749 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1752 // The starting paragraph of the coming rows is the
1753 // first paragraph of the document. (Asger)
1754 texrow.start(paragraph, 0);
1756 if (!only_body && nice) {
1757 ofs << "%% " LYX_DOCVERSION " created this file. "
1758 "For more info, see http://www.lyx.org/.\n"
1759 "%% Do not edit unless you really know what "
1764 lyxerr.debug() << "lyx header finished" << endl;
1765 // There are a few differences between nice LaTeX and usual files:
1766 // usual is \batchmode and has a
1767 // special input@path to allow the including of figures
1768 // with either \input or \includegraphics (what figinsets do).
1769 // batchmode is not set if there is a tex_code_break_column.
1770 // In this case somebody is interested in the generated LaTeX,
1771 // so this is OK. input@path is set when the actual parameter
1772 // original_path is set. This is done for usual tex-file, but not
1773 // for nice-latex-file. (Matthias 250696)
1776 // code for usual, NOT nice-latex-file
1777 ofs << "\\batchmode\n"; // changed
1778 // from \nonstopmode
1781 if (!original_path.empty()) {
1782 ofs << "\\makeatletter\n"
1783 << "\\def\\input@path{{"
1784 << os::external_path(original_path) << "/}}\n"
1785 << "\\makeatother\n";
1791 ofs << "\\documentclass";
1793 ostringstream options; // the document class options.
1795 if (tokenPos(tclass.opt_fontsize(),
1796 '|', params.fontsize) >= 0) {
1797 // only write if existing in list (and not default)
1798 options << params.fontsize << "pt,";
1802 if (!params.use_geometry &&
1803 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1804 switch (params.papersize) {
1805 case BufferParams::PAPER_A4PAPER:
1806 options << "a4paper,";
1808 case BufferParams::PAPER_USLETTER:
1809 options << "letterpaper,";
1811 case BufferParams::PAPER_A5PAPER:
1812 options << "a5paper,";
1814 case BufferParams::PAPER_B5PAPER:
1815 options << "b5paper,";
1817 case BufferParams::PAPER_EXECUTIVEPAPER:
1818 options << "executivepaper,";
1820 case BufferParams::PAPER_LEGALPAPER:
1821 options << "legalpaper,";
1827 if (params.sides != tclass.sides()) {
1828 switch (params.sides) {
1829 case LyXTextClass::OneSide:
1830 options << "oneside,";
1832 case LyXTextClass::TwoSides:
1833 options << "twoside,";
1839 if (params.columns != tclass.columns()) {
1840 if (params.columns == 2)
1841 options << "twocolumn,";
1843 options << "onecolumn,";
1846 if (!params.use_geometry
1847 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1848 options << "landscape,";
1850 // language should be a parameter to \documentclass
1852 ostringstream language_options;
1853 if (params.language->babel() == "hebrew"
1854 && default_language->babel() != "hebrew")
1855 // This seems necessary
1856 features.UsedLanguages.insert(default_language);
1858 if (lyxrc.language_use_babel ||
1859 params.language->lang() != lyxrc.default_language ||
1860 !features.UsedLanguages.empty()) {
1862 for (LaTeXFeatures::LanguageList::const_iterator cit =
1863 features.UsedLanguages.begin();
1864 cit != features.UsedLanguages.end(); ++cit)
1865 language_options << (*cit)->babel() << ',';
1866 language_options << params.language->babel();
1867 if (lyxrc.language_global_options)
1868 options << language_options.str() << ',';
1871 // the user-defined options
1872 if (!params.options.empty()) {
1873 options << params.options << ',';
1876 string strOptions(options.str().c_str());
1877 if (!strOptions.empty()){
1878 strOptions = strip(strOptions, ',');
1879 ofs << '[' << strOptions << ']';
1883 << textclasslist.LatexnameOfClass(params.textclass)
1886 // end of \documentclass defs
1888 // font selection must be done before loading fontenc.sty
1889 // The ae package is not needed when using OT1 font encoding.
1890 if (params.fonts != "default" &&
1891 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1892 ofs << "\\usepackage{" << params.fonts << "}\n";
1894 if (params.fonts == "ae") {
1895 ofs << "\\usepackage{aecompl}\n";
1899 // this one is not per buffer
1900 if (lyxrc.fontenc != "default") {
1901 ofs << "\\usepackage[" << lyxrc.fontenc
1906 if (params.inputenc == "auto") {
1907 string const doc_encoding =
1908 params.language->encoding()->LatexName();
1910 // Create a list with all the input encodings used
1912 set<string> encodings;
1913 for (LaTeXFeatures::LanguageList::const_iterator it =
1914 features.UsedLanguages.begin();
1915 it != features.UsedLanguages.end(); ++it)
1916 if ((*it)->encoding()->LatexName() != doc_encoding)
1917 encodings.insert((*it)->encoding()->LatexName());
1919 ofs << "\\usepackage[";
1920 std::copy(encodings.begin(), encodings.end(),
1921 std::ostream_iterator<string>(ofs, ","));
1922 ofs << doc_encoding << "]{inputenc}\n";
1924 } else if (params.inputenc != "default") {
1925 ofs << "\\usepackage[" << params.inputenc
1930 // At the very beginning the text parameters.
1931 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1932 switch (params.paperpackage) {
1933 case BufferParams::PACKAGE_A4:
1934 ofs << "\\usepackage{a4}\n";
1937 case BufferParams::PACKAGE_A4WIDE:
1938 ofs << "\\usepackage{a4wide}\n";
1941 case BufferParams::PACKAGE_WIDEMARGINSA4:
1942 ofs << "\\usepackage[widemargins]{a4}\n";
1947 if (params.use_geometry) {
1948 ofs << "\\usepackage{geometry}\n";
1950 ofs << "\\geometry{verbose";
1951 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1952 ofs << ",landscape";
1953 switch (params.papersize2) {
1954 case BufferParams::VM_PAPER_CUSTOM:
1955 if (!params.paperwidth.empty())
1956 ofs << ",paperwidth="
1957 << params.paperwidth;
1958 if (!params.paperheight.empty())
1959 ofs << ",paperheight="
1960 << params.paperheight;
1962 case BufferParams::VM_PAPER_USLETTER:
1963 ofs << ",letterpaper";
1965 case BufferParams::VM_PAPER_USLEGAL:
1966 ofs << ",legalpaper";
1968 case BufferParams::VM_PAPER_USEXECUTIVE:
1969 ofs << ",executivepaper";
1971 case BufferParams::VM_PAPER_A3:
1974 case BufferParams::VM_PAPER_A4:
1977 case BufferParams::VM_PAPER_A5:
1980 case BufferParams::VM_PAPER_B3:
1983 case BufferParams::VM_PAPER_B4:
1986 case BufferParams::VM_PAPER_B5:
1990 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1991 switch (lyxrc.default_papersize) {
1992 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1993 case BufferParams::PAPER_USLETTER:
1994 ofs << ",letterpaper";
1996 case BufferParams::PAPER_LEGALPAPER:
1997 ofs << ",legalpaper";
1999 case BufferParams::PAPER_EXECUTIVEPAPER:
2000 ofs << ",executivepaper";
2002 case BufferParams::PAPER_A3PAPER:
2005 case BufferParams::PAPER_A4PAPER:
2008 case BufferParams::PAPER_A5PAPER:
2011 case BufferParams::PAPER_B5PAPER:
2016 if (!params.topmargin.empty())
2017 ofs << ",tmargin=" << params.topmargin;
2018 if (!params.bottommargin.empty())
2019 ofs << ",bmargin=" << params.bottommargin;
2020 if (!params.leftmargin.empty())
2021 ofs << ",lmargin=" << params.leftmargin;
2022 if (!params.rightmargin.empty())
2023 ofs << ",rmargin=" << params.rightmargin;
2024 if (!params.headheight.empty())
2025 ofs << ",headheight=" << params.headheight;
2026 if (!params.headsep.empty())
2027 ofs << ",headsep=" << params.headsep;
2028 if (!params.footskip.empty())
2029 ofs << ",footskip=" << params.footskip;
2033 if (features.amsstyle
2034 && !tclass.provides(LyXTextClass::amsmath)) {
2035 ofs << "\\usepackage{amsmath}\n";
2039 if (tokenPos(tclass.opt_pagestyle(),
2040 '|', params.pagestyle) >= 0) {
2041 if (params.pagestyle == "fancy") {
2042 ofs << "\\usepackage{fancyhdr}\n";
2045 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2049 // We try to load babel late, in case it interferes
2050 // with other packages.
2052 string tmp = lyxrc.language_package;
2053 if (!lyxrc.language_global_options
2054 && tmp == "\\usepackage{babel}")
2055 tmp = string("\\usepackage[") +
2056 language_options.str().c_str() +
2062 if (params.secnumdepth != tclass.secnumdepth()) {
2063 ofs << "\\setcounter{secnumdepth}{"
2064 << params.secnumdepth
2068 if (params.tocdepth != tclass.tocdepth()) {
2069 ofs << "\\setcounter{tocdepth}{"
2075 if (params.paragraph_separation) {
2076 switch (params.defskip.kind()) {
2077 case VSpace::SMALLSKIP:
2078 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2080 case VSpace::MEDSKIP:
2081 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2083 case VSpace::BIGSKIP:
2084 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2086 case VSpace::LENGTH:
2087 ofs << "\\setlength\\parskip{"
2088 << params.defskip.length().asLatexString()
2091 default: // should never happen // Then delete it.
2092 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2097 ofs << "\\setlength\\parindent{0pt}\n";
2101 // Now insert the LyX specific LaTeX commands...
2103 // The optional packages;
2104 string preamble(features.getPackages());
2106 // this might be useful...
2107 preamble += "\n\\makeatletter\n";
2109 // Some macros LyX will need
2110 string tmppreamble(features.getMacros());
2112 if (!tmppreamble.empty()) {
2113 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2114 "LyX specific LaTeX commands.\n"
2115 + tmppreamble + '\n';
2118 // the text class specific preamble
2119 tmppreamble = features.getTClassPreamble();
2120 if (!tmppreamble.empty()) {
2121 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2122 "Textclass specific LaTeX commands.\n"
2123 + tmppreamble + '\n';
2126 /* the user-defined preamble */
2127 if (!params.preamble.empty()) {
2128 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2129 "User specified LaTeX commands.\n"
2130 + params.preamble + '\n';
2133 preamble += "\\makeatother\n";
2135 // Itemize bullet settings need to be last in case the user
2136 // defines their own bullets that use a package included
2137 // in the user-defined preamble -- ARRae
2138 // Actually it has to be done much later than that
2139 // since some packages like frenchb make modifications
2140 // at \begin{document} time -- JMarc
2142 for (int i = 0; i < 4; ++i) {
2143 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2144 if (bullets_def.empty())
2145 bullets_def="\\AtBeginDocument{\n";
2146 bullets_def += " \\renewcommand{\\labelitemi";
2148 // `i' is one less than the item to modify
2155 bullets_def += "ii";
2161 bullets_def += "}{" +
2162 params.user_defined_bullets[i].getText()
2167 if (!bullets_def.empty())
2168 preamble += bullets_def + "}\n\n";
2170 for (int j = countChar(preamble, '\n'); j-- ;) {
2177 ofs << "\\begin{document}\n";
2180 lyxerr.debug() << "preamble finished, now the body." << endl;
2182 if (!lyxrc.language_auto_begin) {
2183 ofs << subst(lyxrc.language_command_begin, "$$lang",
2184 params.language->babel())
2189 latexParagraphs(ofs, paragraph, 0, texrow);
2191 // add this just in case after all the paragraphs
2195 if (!lyxrc.language_auto_end) {
2196 ofs << subst(lyxrc.language_command_end, "$$lang",
2197 params.language->babel())
2203 ofs << "\\end{document}\n";
2206 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2208 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2212 // Just to be sure. (Asger)
2215 // tex_code_break_column's value is used to decide
2216 // if we are in batchmode or not (within mathed_write()
2217 // in math_write.C) so we must set it to a non-zero
2218 // value when we leave otherwise we save incorrect .lyx files.
2219 tex_code_break_column = lyxrc.ascii_linelen;
2223 lyxerr << "File was not closed properly." << endl;
2226 lyxerr.debug() << "Finished making latex file." << endl;
2231 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2233 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2234 Paragraph * endpar, TexRow & texrow) const
2236 bool was_title = false;
2237 bool already_title = false;
2240 while (par != endpar) {
2241 LyXLayout const & layout =
2242 textclasslist.Style(params.textclass,
2245 if (layout.intitle) {
2246 if (already_title) {
2247 lyxerr <<"Error in latexParagraphs: You"
2248 " should not mix title layouts"
2249 " with normal ones." << endl;
2252 } else if (was_title && !already_title) {
2253 ofs << "\\maketitle\n";
2255 already_title = true;
2259 if (layout.isEnvironment()) {
2260 par = par->TeXEnvironment(this, params, ofs, texrow);
2262 par = par->TeXOnePar(this, params, ofs, texrow, false);
2265 // It might be that we only have a title in this document
2266 if (was_title && !already_title) {
2267 ofs << "\\maketitle\n";
2273 bool Buffer::isLatex() const
2275 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2279 bool Buffer::isLinuxDoc() const
2281 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2285 bool Buffer::isLiterate() const
2287 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2291 bool Buffer::isDocBook() const
2293 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2297 bool Buffer::isSGML() const
2299 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2300 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2304 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2305 string const & latexname) const
2307 if (!latexname.empty() && latexname != "!-- --")
2308 os << string(depth, ' ') << "<" << latexname << ">\n";
2312 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2313 string const & latexname) const
2315 if (!latexname.empty() && latexname != "!-- --")
2316 os << string(depth, ' ') << "</" << latexname << ">\n";
2320 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2322 ofstream ofs(fname.c_str());
2325 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2329 niceFile = nice; // this will be used by included files.
2331 LyXTextClass const & tclass =
2332 textclasslist.TextClass(params.textclass);
2334 LaTeXFeatures features(params, tclass.numLayouts());
2339 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2342 string sgml_includedfiles=features.getIncludedFiles(fname);
2344 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2345 ofs << "<!doctype linuxdoc system>\n\n";
2347 ofs << "<!doctype linuxdoc system [ "
2348 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2351 if (params.options.empty())
2352 sgmlOpenTag(ofs, 0, top_element);
2354 string top = top_element;
2356 top += params.options;
2357 sgmlOpenTag(ofs, 0, top);
2361 ofs << "<!-- " << LYX_DOCVERSION
2362 << " created this file. For more info see http://www.lyx.org/"
2365 Paragraph::depth_type depth = 0; // paragraph depth
2366 Paragraph * par = paragraph;
2368 vector<string> environment_stack(5);
2371 LyXLayout const & style =
2372 textclasslist.Style(params.textclass,
2375 // treat <toc> as a special case for compatibility with old code
2376 if (par->getChar(0) == Paragraph::META_INSET) {
2377 Inset * inset = par->getInset(0);
2378 Inset::Code lyx_code = inset->LyxCode();
2379 if (lyx_code == Inset::TOC_CODE){
2380 string const temp = "toc";
2381 sgmlOpenTag(ofs, depth, temp);
2388 // environment tag closing
2389 for (; depth > par->params().depth(); --depth) {
2390 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2391 environment_stack[depth].erase();
2394 // write opening SGML tags
2395 switch (style.latextype) {
2396 case LATEX_PARAGRAPH:
2397 if (depth == par->params().depth()
2398 && !environment_stack[depth].empty()) {
2399 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2400 environment_stack[depth].erase();
2406 sgmlOpenTag(ofs, depth, style.latexname());
2411 LinuxDocError(par, 0,
2412 _("Error : Wrong depth for"
2413 " LatexType Command.\n"));
2415 if (!environment_stack[depth].empty()){
2416 sgmlCloseTag(ofs, depth,
2417 environment_stack[depth]);
2421 environment_stack[depth].erase();
2422 sgmlOpenTag(ofs, depth, style.latexname());
2425 case LATEX_ENVIRONMENT:
2426 case LATEX_ITEM_ENVIRONMENT:
2427 if (depth == par->params().depth()
2428 && environment_stack[depth] != style.latexname()) {
2429 sgmlCloseTag(ofs, depth,
2430 environment_stack[depth]);
2431 environment_stack[depth].erase();
2433 if (depth < par->params().depth()) {
2434 depth = par->params().depth();
2435 environment_stack[depth].erase();
2437 if (environment_stack[depth] != style.latexname()) {
2439 sgmlOpenTag(ofs, depth, "p");
2441 sgmlOpenTag(ofs, depth, style.latexname());
2443 if (environment_stack.size() == depth + 1)
2444 environment_stack.push_back("!-- --");
2445 environment_stack[depth] = style.latexname();
2448 if (style.latexparam() == "CDATA")
2451 if (style.latextype == LATEX_ENVIRONMENT) break;
2453 if (style.labeltype == LABEL_MANUAL)
2458 sgmlOpenTag(ofs, depth + 1, item_name);
2461 sgmlOpenTag(ofs, depth, style.latexname());
2465 SimpleLinuxDocOnePar(ofs, par, depth);
2470 // write closing SGML tags
2471 switch (style.latextype) {
2474 case LATEX_ENVIRONMENT:
2475 case LATEX_ITEM_ENVIRONMENT:
2476 if (style.latexparam() == "CDATA")
2480 sgmlCloseTag(ofs, depth, style.latexname());
2486 for (int i=depth; i >= 0; --i)
2487 sgmlCloseTag(ofs, depth, environment_stack[i]);
2491 sgmlCloseTag(ofs, 0, top_element);
2495 // How to check for successful close
2499 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2500 Paragraph::depth_type depth, int desc_on,
2503 Paragraph * tpar = par;
2505 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2507 tpar = tpar->next();
2510 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2511 "Caption").second) {
2512 sgmlOpenTag(os, depth + 1, inner_tag);
2514 SimpleDocBookOnePar(os, extra_par, tpar,
2515 desc_on, depth + 2);
2516 sgmlCloseTag(os, depth+1, inner_tag);
2517 if (!extra_par.empty())
2523 // checks, if newcol chars should be put into this line
2524 // writes newline, if necessary.
2527 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2528 string::size_type newcol)
2531 if (colcount > lyxrc.ascii_linelen) {
2533 colcount = newcol; // assume write after this call
2548 string tag_name(PAR_TAG const & pt) {
2550 case NONE: return "!-- --";
2551 case TT: return "tt";
2552 case SF: return "sf";
2553 case BF: return "bf";
2554 case IT: return "it";
2555 case SL: return "sl";
2556 case EM: return "em";
2563 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2565 p1 = static_cast<PAR_TAG>(p1 | p2);
2570 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2572 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2580 // Handle internal paragraph parsing -- layout already processed.
2581 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2583 Paragraph::depth_type /*depth*/)
2585 LyXLayout const & style = textclasslist.Style(params.textclass,
2587 string::size_type char_line_count = 5; // Heuristic choice ;-)
2589 // gets paragraph main font
2592 if (style.labeltype == LABEL_MANUAL) {
2593 font_old = style.labelfont;
2596 font_old = style.font;
2600 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2601 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2602 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2605 stack < PAR_TAG > tag_state;
2606 // parsing main loop
2607 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2609 PAR_TAG tag_close = NONE;
2610 list < PAR_TAG > tag_open;
2612 LyXFont const font = par->getFont(params, i);
2614 if (font_old.family() != font.family()) {
2615 switch (family_type) {
2616 case LyXFont::SANS_FAMILY:
2619 case LyXFont::TYPEWRITER_FAMILY:
2626 family_type = font.family();
2628 switch (family_type) {
2629 case LyXFont::SANS_FAMILY:
2630 tag_open.push_back(SF);
2632 case LyXFont::TYPEWRITER_FAMILY:
2633 tag_open.push_back(TT);
2640 if (font_old.series() != font.series()) {
2641 switch (series_type) {
2642 case LyXFont::BOLD_SERIES:
2649 series_type = font.series();
2651 switch (series_type) {
2652 case LyXFont::BOLD_SERIES:
2653 tag_open.push_back(BF);
2661 if (font_old.shape() != font.shape()) {
2662 switch (shape_type) {
2663 case LyXFont::ITALIC_SHAPE:
2666 case LyXFont::SLANTED_SHAPE:
2673 shape_type = font.shape();
2675 switch (shape_type) {
2676 case LyXFont::ITALIC_SHAPE:
2677 tag_open.push_back(IT);
2679 case LyXFont::SLANTED_SHAPE:
2680 tag_open.push_back(SL);
2687 if (font_old.emph() != font.emph()) {
2688 if (font.emph() == LyXFont::ON) {
2689 tag_open.push_back(EM);
2698 list < PAR_TAG > temp;
2699 while(!tag_state.empty() && tag_close ) {
2700 PAR_TAG k = tag_state.top();
2702 os << "</" << tag_name(k) << ">";
2709 for(list< PAR_TAG >::const_iterator j = temp.begin();
2710 j != temp.end(); ++j) {
2712 os << "<" << tag_name(*j) << ">";
2715 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2716 j != tag_open.end(); ++j) {
2718 os << "<" << tag_name(*j) << ">";
2721 char c = par->getChar(i);
2723 if (c == Paragraph::META_INSET) {
2724 Inset * inset = par->getInset(i);
2725 inset->Linuxdoc(this, os);
2730 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
2731 // "TeX"-Mode on == > SGML-Mode on.
2737 if (par->linuxDocConvertChar(c, sgml_string)
2738 && !style.free_spacing) {
2739 // in freespacing mode, spaces are
2740 // non-breaking characters
2741 if (desc_on) {// if char is ' ' then...
2744 linux_doc_line_break(os, char_line_count, 6);
2748 linux_doc_line_break(os, char_line_count, 1);
2753 char_line_count += sgml_string.length();
2759 while (!tag_state.empty()) {
2760 os << "</" << tag_name(tag_state.top()) << ">";
2764 // resets description flag correctly
2766 // <tag> not closed...
2767 linux_doc_line_break(os, char_line_count, 6);
2773 // Print an error message.
2774 void Buffer::LinuxDocError(Paragraph * par, int pos,
2775 string const & message)
2777 // insert an error marker in text
2778 InsetError * new_inset = new InsetError(message);
2779 par->insertInset(pos, new_inset);
2783 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2785 ofstream ofs(fname.c_str());
2787 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2791 Paragraph * par = paragraph;
2793 niceFile = nice; // this will be used by Insetincludes.
2795 LyXTextClass const & tclass =
2796 textclasslist.TextClass(params.textclass);
2798 LaTeXFeatures features(params, tclass.numLayouts());
2803 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2806 string sgml_includedfiles = features.getIncludedFiles(fname);
2808 ofs << "<!doctype " << top_element
2809 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2811 if (params.preamble.empty() && sgml_includedfiles.empty())
2814 ofs << "\n [ " << params.preamble
2815 << sgml_includedfiles << " \n]>\n\n";
2818 string top = top_element;
2820 top += params.language->code();
2823 if (!params.options.empty()) {
2825 top += params.options;
2827 sgmlOpenTag(ofs, 0, top);
2829 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2830 << "\n See http://www.lyx.org/ for more information -->\n";
2832 vector<string> environment_stack(10);
2833 vector<string> environment_inner(10);
2834 vector<string> command_stack(10);
2836 bool command_flag = false;
2837 Paragraph::depth_type command_depth = 0;
2838 Paragraph::depth_type command_base = 0;
2839 Paragraph::depth_type cmd_depth = 0;
2840 Paragraph::depth_type depth = 0; // paragraph depth
2843 string command_name;
2849 int desc_on = 0; // description mode
2851 LyXLayout const & style =
2852 textclasslist.Style(params.textclass,
2855 // environment tag closing
2856 for (; depth > par->params().depth(); --depth) {
2857 if (environment_inner[depth] != "!-- --") {
2858 item_name = "listitem";
2859 sgmlCloseTag(ofs, command_depth + depth,
2861 if (environment_inner[depth] == "varlistentry")
2862 sgmlCloseTag(ofs, depth+command_depth,
2863 environment_inner[depth]);
2865 sgmlCloseTag(ofs, depth + command_depth,
2866 environment_stack[depth]);
2867 environment_stack[depth].erase();
2868 environment_inner[depth].erase();
2871 if (depth == par->params().depth()
2872 && environment_stack[depth] != style.latexname()
2873 && !environment_stack[depth].empty()) {
2874 if (environment_inner[depth] != "!-- --") {
2875 item_name= "listitem";
2876 sgmlCloseTag(ofs, command_depth+depth,
2878 if (environment_inner[depth] == "varlistentry")
2880 depth + command_depth,
2881 environment_inner[depth]);
2884 sgmlCloseTag(ofs, depth + command_depth,
2885 environment_stack[depth]);
2887 environment_stack[depth].erase();
2888 environment_inner[depth].erase();
2891 // Write opening SGML tags.
2892 switch (style.latextype) {
2893 case LATEX_PARAGRAPH:
2894 sgmlOpenTag(ofs, depth + command_depth,
2900 LinuxDocError(par, 0,
2901 _("Error : Wrong depth for "
2902 "LatexType Command.\n"));
2904 command_name = style.latexname();
2906 sgmlparam = style.latexparam();
2907 c_params = split(sgmlparam, c_depth,'|');
2909 cmd_depth = lyx::atoi(c_depth);
2912 if (cmd_depth < command_base) {
2913 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
2914 sgmlCloseTag(ofs, j, command_stack[j]);
2915 command_depth = command_base = cmd_depth;
2916 } else if (cmd_depth <= command_depth) {
2917 for (int j = command_depth; j >= int(cmd_depth); --j)
2918 sgmlCloseTag(ofs, j, command_stack[j]);
2919 command_depth = cmd_depth;
2921 command_depth = cmd_depth;
2923 command_depth = command_base = cmd_depth;
2924 command_flag = true;
2926 if (command_stack.size() == command_depth + 1)
2927 command_stack.push_back(string());
2928 command_stack[command_depth] = command_name;
2930 // treat label as a special case for
2931 // more WYSIWYM handling.
2932 if (par->getChar(0) == Paragraph::META_INSET) {
2933 Inset * inset = par->getInset(0);
2934 Inset::Code lyx_code = inset->LyxCode();
2935 if (lyx_code == Inset::LABEL_CODE){
2936 command_name += " id=\"";
2937 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2938 command_name += "\"";
2943 sgmlOpenTag(ofs, depth + command_depth, command_name);
2944 if (c_params.empty())
2945 item_name = "title";
2947 item_name = c_params;
2948 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2951 case LATEX_ENVIRONMENT:
2952 case LATEX_ITEM_ENVIRONMENT:
2953 if (depth < par->params().depth()) {
2954 depth = par->params().depth();
2955 environment_stack[depth].erase();
2958 if (environment_stack[depth] != style.latexname()) {
2959 if(environment_stack.size() == depth + 1) {
2960 environment_stack.push_back("!-- --");
2961 environment_inner.push_back("!-- --");
2963 environment_stack[depth] = style.latexname();
2964 environment_inner[depth] = "!-- --";
2965 sgmlOpenTag(ofs, depth + command_depth,
2966 environment_stack[depth]);
2968 if (environment_inner[depth] != "!-- --") {
2969 item_name= "listitem";
2971 command_depth + depth,
2973 if (environment_inner[depth] == "varlistentry")
2975 depth + command_depth,
2976 environment_inner[depth]);
2980 if (style.latextype == LATEX_ENVIRONMENT) {
2981 if (!style.latexparam().empty()) {
2982 if(style.latexparam() == "CDATA")
2985 sgmlOpenTag(ofs, depth + command_depth,
2986 style.latexparam());
2991 desc_on = (style.labeltype == LABEL_MANUAL);
2994 environment_inner[depth]= "varlistentry";
2996 environment_inner[depth]= "listitem";
2998 sgmlOpenTag(ofs, depth + 1 + command_depth,
2999 environment_inner[depth]);
3003 sgmlOpenTag(ofs, depth + 1 + command_depth,
3007 sgmlOpenTag(ofs, depth + 1 + command_depth,
3012 sgmlOpenTag(ofs, depth + command_depth,
3018 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3019 depth + 1 + command_depth);
3023 // write closing SGML tags
3024 switch (style.latextype) {
3026 if (c_params.empty())
3030 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3032 case LATEX_ENVIRONMENT:
3033 if (!style.latexparam().empty()) {
3034 if(style.latexparam() == "CDATA")
3037 sgmlCloseTag(ofs, depth + command_depth,
3038 style.latexparam());
3041 case LATEX_ITEM_ENVIRONMENT:
3042 if (desc_on == 1) break;
3044 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3046 case LATEX_PARAGRAPH:
3047 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3050 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3056 for (int d = depth; d >= 0; --d) {
3057 if (!environment_stack[depth].empty()) {
3058 if (environment_inner[depth] != "!-- --") {
3059 item_name = "listitem";
3060 sgmlCloseTag(ofs, command_depth + depth,
3062 if (environment_inner[depth] == "varlistentry")
3063 sgmlCloseTag(ofs, depth + command_depth,
3064 environment_inner[depth]);
3067 sgmlCloseTag(ofs, depth + command_depth,
3068 environment_stack[depth]);
3072 for (int j = command_depth; j >= 0 ; --j)
3073 if (!command_stack[j].empty())
3074 sgmlCloseTag(ofs, j, command_stack[j]);
3077 sgmlCloseTag(ofs, 0, top_element);
3080 // How to check for successful close
3084 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3085 Paragraph * par, int & desc_on,
3086 Paragraph::depth_type depth) const
3088 bool emph_flag = false;
3090 LyXLayout const & style = textclasslist.Style(params.textclass,
3093 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3095 int char_line_count = depth;
3096 if (!style.free_spacing)
3097 os << string(depth,' ');
3099 // parsing main loop
3100 for (Paragraph::size_type i = 0;
3101 i < par->size(); ++i) {
3102 LyXFont font = par->getFont(params, i);
3104 // handle <emphasis> tag
3105 if (font_old.emph() != font.emph()) {
3106 if (font.emph() == LyXFont::ON) {
3110 os << "</emphasis>";
3115 char c = par->getChar(i);
3117 if (c == Paragraph::META_INSET) {
3118 Inset * inset = par->getInset(i);
3119 std::ostringstream ost;
3120 inset->DocBook(this, ost);
3121 string tmp_out = ost.str().c_str();
3124 // This code needs some explanation:
3125 // Two insets are treated specially
3126 // label if it is the first element in a command paragraph
3128 // graphics inside tables or figure floats can't go on
3129 // title (the equivalente in latex for this case is caption
3130 // and title should come first
3133 if (desc_on!= 3 || i!= 0) {
3134 if (!tmp_out.empty() && tmp_out[0] == '@') {
3136 extra += frontStrip(tmp_out, '@');
3138 os << frontStrip(tmp_out, '@');
3143 } else if (font.latex() == LyXFont::ON) {
3144 // "TeX"-Mode on ==> SGML-Mode on.
3150 if (par->linuxDocConvertChar(c, sgml_string)
3151 && !style.free_spacing) { // in freespacing
3153 // non-breaking characters
3157 os << "\n</term><listitem><para>";
3170 os << "</emphasis>";
3173 // resets description flag correctly
3175 // <term> not closed...
3182 // This should be enabled when the Chktex class is implemented. (Asger)
3183 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3184 // Other flags: -wall -v0 -x
3185 int Buffer::runChktex()
3187 if (!users->text) return 0;
3189 ProhibitInput(users);
3191 // get LaTeX-Filename
3192 string const name = getLatexName();
3193 string path = OnlyPath(filename);
3195 string const org_path = path;
3196 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3200 Path p(path); // path to LaTeX file
3201 users->owner()->message(_("Running chktex..."));
3203 // Remove all error insets
3204 bool const removedErrorInsets = users->removeAutoInsets();
3206 // Generate the LaTeX file if neccessary
3207 makeLaTeXFile(name, org_path, false);
3210 Chktex chktex(lyxrc.chktex_command, name, filepath);
3211 int res = chktex.run(terr); // run chktex
3214 WriteAlert(_("chktex did not work!"),
3215 _("Could not run with file:"), name);
3216 } else if (res > 0) {
3217 // Insert all errors as errors boxes
3218 users->insertErrors(terr);
3221 // if we removed error insets before we ran chktex or if we inserted
3222 // error insets after we ran chktex, this must be run:
3223 if (removedErrorInsets || res){
3225 users->fitCursor(users->text);
3233 void Buffer::validate(LaTeXFeatures & features) const
3235 Paragraph * par = paragraph;
3236 LyXTextClass const & tclass =
3237 textclasslist.TextClass(params.textclass);
3239 // AMS Style is at document level
3241 features.amsstyle = (params.use_amsmath ||
3242 tclass.provides(LyXTextClass::amsmath));
3245 // We don't use "lyxerr.debug" because of speed. (Asger)
3246 if (lyxerr.debugging(Debug::LATEX))
3247 lyxerr << "Paragraph: " << par << endl;
3249 // Now just follow the list of paragraphs and run
3250 // validate on each of them.
3251 par->validate(features);
3253 // and then the next paragraph
3257 // the bullet shapes are buffer level not paragraph level
3258 // so they are tested here
3259 for (int i = 0; i < 4; ++i) {
3260 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3261 int const font = params.user_defined_bullets[i].getFont();
3263 int const c = params
3264 .user_defined_bullets[i]
3271 features.latexsym = true;
3273 } else if (font == 1) {
3274 features.amssymb = true;
3275 } else if ((font >= 2 && font <= 5)) {
3276 features.pifont = true;
3281 if (lyxerr.debugging(Debug::LATEX)) {
3282 features.showStruct();
3287 void Buffer::setPaperStuff()
3289 params.papersize = BufferParams::PAPER_DEFAULT;
3290 char const c1 = params.paperpackage;
3291 if (c1 == BufferParams::PACKAGE_NONE) {
3292 char const c2 = params.papersize2;
3293 if (c2 == BufferParams::VM_PAPER_USLETTER)
3294 params.papersize = BufferParams::PAPER_USLETTER;
3295 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3296 params.papersize = BufferParams::PAPER_LEGALPAPER;
3297 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3298 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3299 else if (c2 == BufferParams::VM_PAPER_A3)
3300 params.papersize = BufferParams::PAPER_A3PAPER;
3301 else if (c2 == BufferParams::VM_PAPER_A4)
3302 params.papersize = BufferParams::PAPER_A4PAPER;
3303 else if (c2 == BufferParams::VM_PAPER_A5)
3304 params.papersize = BufferParams::PAPER_A5PAPER;
3305 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3306 (c2 == BufferParams::VM_PAPER_B5))
3307 params.papersize = BufferParams::PAPER_B5PAPER;
3308 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3309 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3310 params.papersize = BufferParams::PAPER_A4PAPER;
3314 // This function should be in Buffer because it's a buffer's property (ale)
3315 string const Buffer::getIncludeonlyList(char delim)
3318 for (inset_iterator it = inset_iterator_begin();
3319 it != inset_iterator_end(); ++it) {
3320 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3321 InsetInclude * insetinc =
3322 static_cast<InsetInclude *>(*it);
3323 if (insetinc->isIncludeOnly()) {
3326 lst += insetinc->getRelFileBaseName();
3330 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3335 vector<string> const Buffer::getLabelList()
3337 /// if this is a child document and the parent is already loaded
3338 /// Use the parent's list instead [ale990407]
3339 if (!params.parentname.empty()
3340 && bufferlist.exists(params.parentname)) {
3341 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3343 return tmp->getLabelList();
3346 vector<string> label_list;
3347 for (inset_iterator it = inset_iterator_begin();
3348 it != inset_iterator_end(); ++it) {
3349 vector<string> const l = (*it)->getLabelList();
3350 label_list.insert(label_list.end(), l.begin(), l.end());
3356 Buffer::Lists const Buffer::getLists() const
3359 Paragraph * par = paragraph;
3361 LyXTextClassList::size_type cap;
3362 boost::tie(found, cap) = textclasslist
3363 .NumberOfLayout(params.textclass, "Caption");
3366 char const labeltype =
3367 textclasslist.Style(params.textclass,
3368 par->getLayout()).labeltype;
3370 if (labeltype >= LABEL_COUNTER_CHAPTER
3371 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3372 // insert this into the table of contents
3373 SingleList & item = l["TOC"];
3376 textclasslist.TextClass(params.textclass).maxcounter());
3377 item.push_back(TocItem(par, depth, par->asString(this, true)));
3379 // For each paragrph, traverse its insets and look for
3383 Paragraph::inset_iterator it =
3384 par->inset_iterator_begin();
3385 Paragraph::inset_iterator end =
3386 par->inset_iterator_end();
3388 for (; it != end; ++it) {
3389 if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3391 static_cast<InsetFloat*>(*it);
3393 string const type = il->type();
3395 // Now find the caption in the float...
3396 // We now tranverse the paragraphs of
3398 Paragraph * tmp = il->inset.par;
3400 if (tmp->layout == cap) {
3401 SingleList & item = l[type];
3403 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3404 item.push_back(TocItem(tmp, 0 , str));
3411 lyxerr << "caption not found" << endl;
3420 // This is also a buffer property (ale)
3421 vector<pair<string, string> > const Buffer::getBibkeyList()
3423 /// if this is a child document and the parent is already loaded
3424 /// Use the parent's list instead [ale990412]
3425 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3426 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3428 return tmp->getBibkeyList();
3431 vector<pair<string, string> > keys;
3432 Paragraph * par = paragraph;
3435 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3436 par->asString(this, false)));
3440 // Might be either using bibtex or a child has bibliography
3442 for (inset_iterator it = inset_iterator_begin();
3443 it != inset_iterator_end(); ++it) {
3444 // Search for Bibtex or Include inset
3445 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3446 vector<pair<string,string> > tmp =
3447 static_cast<InsetBibtex*>(*it)->getKeys(this);
3448 keys.insert(keys.end(), tmp.begin(), tmp.end());
3449 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3450 vector<pair<string,string> > const tmp =
3451 static_cast<InsetInclude*>(*it)->getKeys();
3452 keys.insert(keys.end(), tmp.begin(), tmp.end());
3461 bool Buffer::isDepClean(string const & name) const
3463 DEPCLEAN * item = dep_clean;
3464 while (item && item->master != name)
3466 if (!item) return true;
3471 void Buffer::markDepClean(string const & name)
3474 dep_clean = new DEPCLEAN;
3475 dep_clean->clean = true;
3476 dep_clean->master = name;
3477 dep_clean->next = 0;
3479 DEPCLEAN * item = dep_clean;
3480 while (item && item->master != name)
3485 item = new DEPCLEAN;
3487 item->master = name;
3494 bool Buffer::Dispatch(string const & command)
3496 // Split command string into command and argument
3498 string line = frontStrip(command);
3499 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3501 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3505 bool Buffer::Dispatch(int action, string const & argument)
3507 bool dispatched = true;
3510 Exporter::Export(this, argument, false);
3520 void Buffer::resizeInsets(BufferView * bv)
3522 /// then remove all LyXText in text-insets
3523 Paragraph * par = paragraph;
3524 for (; par; par = par->next()) {
3525 par->resizeInsetsLyXText(bv);
3530 void Buffer::redraw()
3533 users->fitCursor(users->text);
3537 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3540 Paragraph * par = paragraph;
3542 par->changeLanguage(params, from, to);
3548 bool Buffer::isMultiLingual()
3550 Paragraph * par = paragraph;
3552 if (par->isMultiLingual(params))
3560 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3561 Paragraph::size_type pos)
3564 it = par->InsetIterator(pos);
3565 if (it == par->inset_iterator_end()) {
3572 void Buffer::inset_iterator::SetParagraph()
3575 it = par->inset_iterator_begin();
3576 if (it != par->inset_iterator_end())
3581 // We maintain an invariant that whenever par = 0 then it = 0