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 "insets/lyxinset.h"
53 #include "insets/inseterror.h"
54 #include "insets/insetlabel.h"
55 #include "insets/insetref.h"
56 #include "insets/inseturl.h"
57 #include "insets/insetinfo.h"
58 #include "insets/insetquotes.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetbib.h"
61 #include "insets/insetcite.h"
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h"
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/figinset.h"
69 #include "insets/insettext.h"
70 #include "insets/insetert.h"
71 #include "insets/insetgraphics.h"
72 #include "insets/insetfoot.h"
73 #include "insets/insetmarginal.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insetlist.h"
77 #include "insets/insettabular.h"
78 #include "insets/insettheorem.h"
79 #include "insets/insetcaption.h"
80 #include "insets/insetfloatlist.h"
81 #include "support/filetools.h"
82 #include "support/path.h"
83 #include "support/os.h"
88 #include "LaTeXFeatures.h"
89 #include "support/syscall.h"
90 #include "support/lyxlib.h"
91 #include "support/FileInfo.h"
92 #include "support/lyxmanip.h"
96 #include "lyx_gui_misc.h" // WarnReadonly()
97 #include "frontends/Dialogs.h"
100 #include "Lsstream.h"
101 #include "converter.h"
103 using std::stringstream;
112 using std::make_pair;
120 // all these externs should eventually be removed.
121 extern BufferList bufferlist;
123 extern LyXAction lyxaction;
127 const int LYX_FORMAT = 218;
131 extern int tex_code_break_column;
134 Buffer::Buffer(string const & file, bool ronly)
136 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
138 filepath = OnlyPath(file);
147 if (read_only || (lyxrc.use_tempdir)) {
148 tmppath = CreateBufferTmpDir();
149 } else tmppath.erase();
155 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
156 // here the buffer should take care that it is
157 // saved properly, before it goes into the void.
159 // make sure that views using this buffer
164 if (!tmppath.empty()) {
165 DestroyBufferTmpDir(tmppath);
168 LyXParagraph * par = paragraph;
169 LyXParagraph * tmppar;
171 tmppar = par->next();
179 string const Buffer::getLatexName(bool no_path) const
182 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
185 return ChangeExtension(MakeLatexName(filename),
190 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
192 string const filename = getLatexName(false);
194 if (filename.empty())
195 return make_pair(Buffer::latexlog, string());
197 string path = OnlyPath(filename);
199 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
202 string const fname = AddName(path,
203 OnlyFilename(ChangeExtension(filename,
206 AddName(path, OnlyFilename(
207 ChangeExtension(filename,
208 formats.Extension("literate") + ".out")));
210 // If no Latex log or Build log is newer, show Build log
212 FileInfo const f_fi(fname);
213 FileInfo const b_fi(bname);
216 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
217 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
218 return make_pair(Buffer::buildlog, bname);
220 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
221 return make_pair(Buffer::latexlog, fname);
225 void Buffer::setReadonly(bool flag)
227 if (read_only != flag) {
230 users->owner()->getDialogs()->updateBufferDependent(false);
233 WarnReadonly(filename);
238 bool Buffer::saveParamsAsDefaults() // const
240 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
242 Buffer defaults = Buffer(fname);
244 // Use the current buffer's parameters as default
245 defaults.params = params;
247 // add an empty paragraph. Is this enough?
248 defaults.paragraph = new LyXParagraph;
250 return defaults.writeFile(defaults.filename, false);
254 /// Update window titles of all users
255 // Should work on a list
256 void Buffer::updateTitles() const
258 if (users) users->owner()->updateWindowTitle();
262 /// Reset autosave timer of all users
263 // Should work on a list
264 void Buffer::resetAutosaveTimers() const
266 if (users) users->owner()->resetAutosaveTimer();
270 void Buffer::setFileName(string const & newfile)
272 filename = MakeAbsPath(newfile);
273 filepath = OnlyPath(filename);
274 setReadonly(IsFileWriteable(filename) == 0);
279 // candidate for move to BufferView
280 // (at least some parts in the beginning of the func)
283 // changed to be public and have one parameter
284 // if par = 0 normal behavior
285 // else insert behavior
286 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
287 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
290 char depth = 0; // signed or unsigned?
291 bool the_end_read = false;
293 LyXParagraph * return_par = 0;
294 LyXFont font(LyXFont::ALL_INHERIT, params.language);
295 if (file_format < 216 && params.language->lang() == "hebrew")
296 font.setLanguage(default_language);
297 // If we are inserting, we cheat and get a token in advance
298 bool has_token = false;
302 par = new LyXParagraph;
304 users->text->BreakParagraph(users);
305 return_par = users->text->FirstParagraph();
308 // We don't want to adopt the parameters from the
309 // document we insert, so we skip until the text begins:
312 pretoken = lex.GetString();
313 if (pretoken == "\\layout") {
325 pretoken = lex.GetString();
328 if (pretoken.empty()) continue;
331 parseSingleLyXformat2Token(lex, par, return_par,
332 pretoken, pos, depth,
340 paragraph = return_par;
346 // We'll remove this later. (Lgb)
349 string last_inset_read;
355 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
356 LyXParagraph *& return_par,
357 string const & token, int & pos,
358 char & depth, LyXFont & font
361 bool the_end_read = false;
362 #ifndef NO_PEXTRA_REALLY
363 // This is super temporary but is needed to get the compability
364 // mode for minipages work correctly together with new tabulars.
365 static int call_depth = 0;
367 bool checkminipage = false;
368 static LyXParagraph * minipar = 0;
369 static LyXParagraph * parBeforeMinipage = 0;
372 if (token[0] != '\\') {
373 for (string::const_iterator cit = token.begin();
374 cit != token.end(); ++cit)
376 par->InsertChar(pos, (*cit), font);
379 checkminipage = true;
380 } else if (token == "\\i") {
381 Inset * inset = new InsetLatexAccent;
382 inset->Read(this, lex);
383 par->InsertInset(pos, inset, font);
385 } else if (token == "\\layout") {
387 string const layoutname = lex.GetString();
388 pair<bool, LyXTextClass::LayoutList::size_type> pp
389 = textclasslist.NumberOfLayout(params.textclass,
393 // The is the compability reading of layout caption.
394 // It can be removed in LyX version 1.3.0. (Lgb)
395 if (compare_no_case(layoutname, "caption") == 0) {
396 // We expect that the par we are now working on is
397 // really inside a InsetText inside a InsetFloat.
398 // We also know that captions can only be
399 // one paragraph. (Lgb)
401 // We should now read until the next "\layout"
403 // This is probably not good enough, what if the
404 // caption is the last par in the document (Lgb)
405 istream & ist = lex.getStream();
411 if (prefixIs(line, "\\layout")) {
415 if (prefixIs(line, "\\begin_inset"))
417 if (prefixIs(line, "\\end_inset")) {
428 // Now we should have the whole layout in ss
429 // we should now be able to give this to the
431 ss << "\\end_inset\n";
433 // This seems like a bug in stringstream.
434 // We really should be able to use ss
436 istringstream is(ss.str());
438 tmplex.setStream(is);
439 Inset * inset = new InsetCaption;
440 inset->Read(this, tmplex);
441 par->InsertInset(pos, inset, font);
449 par = new LyXParagraph(par);
453 par->layout = pp.second;
456 // use default layout "Standard" (0)
459 // Test whether the layout is obsolete.
460 LyXLayout const & layout =
461 textclasslist.Style(params.textclass,
463 if (!layout.obsoleted_by().empty())
464 par->layout = textclasslist
465 .NumberOfLayout(params.textclass,
466 layout.obsoleted_by())
468 par->params.depth(depth);
469 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
470 if (file_format < 216
471 && params.language->lang() == "hebrew")
472 font.setLanguage(default_language);
477 } else if (token == "\\begin_float") {
478 // This is the compability reader. It can be removed in
479 // LyX version 1.3.0. (Lgb)
481 string const tmptok = lex.GetString();
482 //lyxerr << "old float: " << tmptok << endl;
485 stringstream old_float;
487 if (tmptok == "footnote") {
488 inset = new InsetFoot;
489 } else if (tmptok == "margin") {
490 inset = new InsetMarginal;
491 } else if (tmptok == "fig") {
492 inset = new InsetFloat("figure");
493 old_float << "placement htbp\n";
494 } else if (tmptok == "tab") {
495 inset = new InsetFloat("table");
496 old_float << "placement htbp\n";
497 } else if (tmptok == "alg") {
498 inset = new InsetFloat("algorithm");
499 old_float << "placement htbp\n";
500 } else if (tmptok == "wide-fig") {
501 InsetFloat * tmp = new InsetFloat("figure");
504 old_float << "placement htbp\n";
505 } else if (tmptok == "wide-tab") {
506 InsetFloat * tmp = new InsetFloat("table");
509 old_float << "placement htbp\n";
514 return false; // no end read yet
517 old_float << "collapsed true\n";
519 // Here we need to check for \end_deeper and handle that
520 // before we do the footnote parsing.
521 // This _is_ a hack! (Lgb)
524 string const tmp = lex.GetString();
525 if (tmp == "\\end_deeper") {
526 //lyxerr << "\\end_deeper caught!" << endl;
528 lex.printError("\\end_deeper: "
529 "depth is already null");
534 old_float << tmp << ' ';
539 old_float << lex.getLongString("\\end_float")
540 << "\n\\end_inset\n";
541 //lyxerr << "Float Body:\n" << old_float.str() << endl;
542 // That this does not work seems like a bug
543 // in stringstream. (Lgb)
544 istringstream istr(old_float.str());
546 nylex.setStream(istr);
547 inset->Read(this, nylex);
548 par->InsertInset(pos, inset, font);
550 } else if (token == "\\begin_deeper") {
552 } else if (token == "\\end_deeper") {
554 lex.printError("\\end_deeper: "
555 "depth is already null");
559 } else if (token == "\\begin_preamble") {
560 params.readPreamble(lex);
561 } else if (token == "\\textclass") {
563 pair<bool, LyXTextClassList::size_type> pp =
564 textclasslist.NumberOfClass(lex.GetString());
566 params.textclass = pp.second;
568 WriteAlert(string(_("Textclass error")),
569 string(_("The document uses an unknown textclass \"")) +
570 lex.GetString() + string("\"."),
571 string(_("LyX will not be able to produce output correctly.")));
572 params.textclass = 0;
574 if (!textclasslist.Load(params.textclass)) {
575 // if the textclass wasn't loaded properly
576 // we need to either substitute another
577 // or stop loading the file.
578 // I can substitute but I don't see how I can
579 // stop loading... ideas?? ARRae980418
580 WriteAlert(_("Textclass Loading Error!"),
581 string(_("Can't load textclass ")) +
582 textclasslist.NameOfClass(params.textclass),
583 _("-- substituting default"));
584 params.textclass = 0;
586 } else if (token == "\\options") {
588 params.options = lex.GetString();
589 } else if (token == "\\language") {
590 params.readLanguage(lex);
591 } else if (token == "\\fontencoding") {
593 } else if (token == "\\inputencoding") {
595 params.inputenc = lex.GetString();
596 } else if (token == "\\graphics") {
597 params.readGraphicsDriver(lex);
598 } else if (token == "\\fontscheme") {
600 params.fonts = lex.GetString();
601 } else if (token == "\\noindent") {
602 par->params.noindent(true);
603 } else if (token == "\\fill_top") {
604 par->params.spaceTop(VSpace(VSpace::VFILL));
605 } else if (token == "\\fill_bottom") {
606 par->params.spaceBottom(VSpace(VSpace::VFILL));
607 } else if (token == "\\line_top") {
608 par->params.lineTop(true);
609 } else if (token == "\\line_bottom") {
610 par->params.lineBottom(true);
611 } else if (token == "\\pagebreak_top") {
612 par->params.pagebreakTop(true);
613 } else if (token == "\\pagebreak_bottom") {
614 par->params.pagebreakBottom(true);
615 } else if (token == "\\start_of_appendix") {
616 par->params.startOfAppendix(true);
617 } else if (token == "\\paragraph_separation") {
618 int tmpret = lex.FindToken(string_paragraph_separation);
619 if (tmpret == -1) ++tmpret;
620 if (tmpret != LYX_LAYOUT_DEFAULT)
621 params.paragraph_separation =
622 static_cast<BufferParams::PARSEP>(tmpret);
623 } else if (token == "\\defskip") {
625 params.defskip = VSpace(lex.GetString());
626 } else if (token == "\\epsfig") { // obsolete
627 // Indeed it is obsolete, but we HAVE to be backwards
628 // compatible until 0.14, because otherwise all figures
629 // in existing documents are irretrivably lost. (Asger)
630 params.readGraphicsDriver(lex);
631 } else if (token == "\\quotes_language") {
632 int tmpret = lex.FindToken(string_quotes_language);
633 if (tmpret == -1) ++tmpret;
634 if (tmpret != LYX_LAYOUT_DEFAULT) {
635 InsetQuotes::quote_language tmpl =
636 InsetQuotes::EnglishQ;
639 tmpl = InsetQuotes::EnglishQ;
642 tmpl = InsetQuotes::SwedishQ;
645 tmpl = InsetQuotes::GermanQ;
648 tmpl = InsetQuotes::PolishQ;
651 tmpl = InsetQuotes::FrenchQ;
654 tmpl = InsetQuotes::DanishQ;
657 params.quotes_language = tmpl;
659 } else if (token == "\\quotes_times") {
661 switch (lex.GetInteger()) {
663 params.quotes_times = InsetQuotes::SingleQ;
666 params.quotes_times = InsetQuotes::DoubleQ;
669 } else if (token == "\\papersize") {
670 int tmpret = lex.FindToken(string_papersize);
674 params.papersize2 = tmpret;
675 } else if (token == "\\paperpackage") {
676 int tmpret = lex.FindToken(string_paperpackages);
679 params.paperpackage = BufferParams::PACKAGE_NONE;
681 params.paperpackage = tmpret;
682 } else if (token == "\\use_geometry") {
684 params.use_geometry = lex.GetInteger();
685 } else if (token == "\\use_amsmath") {
687 params.use_amsmath = lex.GetInteger();
688 } else if (token == "\\paperorientation") {
689 int tmpret = lex.FindToken(string_orientation);
690 if (tmpret == -1) ++tmpret;
691 if (tmpret != LYX_LAYOUT_DEFAULT)
692 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
693 } else if (token == "\\paperwidth") {
695 params.paperwidth = lex.GetString();
696 } else if (token == "\\paperheight") {
698 params.paperheight = lex.GetString();
699 } else if (token == "\\leftmargin") {
701 params.leftmargin = lex.GetString();
702 } else if (token == "\\topmargin") {
704 params.topmargin = lex.GetString();
705 } else if (token == "\\rightmargin") {
707 params.rightmargin = lex.GetString();
708 } else if (token == "\\bottommargin") {
710 params.bottommargin = lex.GetString();
711 } else if (token == "\\headheight") {
713 params.headheight = lex.GetString();
714 } else if (token == "\\headsep") {
716 params.headsep = lex.GetString();
717 } else if (token == "\\footskip") {
719 params.footskip = lex.GetString();
720 } else if (token == "\\paperfontsize") {
722 params.fontsize = strip(lex.GetString());
723 } else if (token == "\\papercolumns") {
725 params.columns = lex.GetInteger();
726 } else if (token == "\\papersides") {
728 switch (lex.GetInteger()) {
730 case 1: params.sides = LyXTextClass::OneSide; break;
731 case 2: params.sides = LyXTextClass::TwoSides; break;
733 } else if (token == "\\paperpagestyle") {
735 params.pagestyle = strip(lex.GetString());
736 } else if (token == "\\bullet") {
738 int const index = lex.GetInteger();
740 int temp_int = lex.GetInteger();
741 params.user_defined_bullets[index].setFont(temp_int);
742 params.temp_bullets[index].setFont(temp_int);
744 temp_int = lex.GetInteger();
745 params.user_defined_bullets[index].setCharacter(temp_int);
746 params.temp_bullets[index].setCharacter(temp_int);
748 temp_int = lex.GetInteger();
749 params.user_defined_bullets[index].setSize(temp_int);
750 params.temp_bullets[index].setSize(temp_int);
752 string const temp_str = lex.GetString();
753 if (temp_str != "\\end_bullet") {
754 // this element isn't really necessary for
755 // parsing but is easier for humans
756 // to understand bullets. Put it back and
757 // set a debug message?
758 lex.printError("\\end_bullet expected, got" + temp_str);
759 //how can I put it back?
761 } else if (token == "\\bulletLaTeX") {
763 int const index = lex.GetInteger();
765 string temp_str = lex.GetString();
767 while (temp_str != "\\end_bullet") {
768 // this loop structure is needed when user
769 // enters an empty string since the first
770 // thing returned will be the \\end_bullet
772 // if the LaTeX entry has spaces. Each element
773 // therefore needs to be read in turn
776 temp_str = lex.GetString();
778 params.user_defined_bullets[index].setText(sum_str);
779 params.temp_bullets[index].setText(sum_str);
780 } else if (token == "\\secnumdepth") {
782 params.secnumdepth = lex.GetInteger();
783 } else if (token == "\\tocdepth") {
785 params.tocdepth = lex.GetInteger();
786 } else if (token == "\\spacing") {
788 string const tmp = strip(lex.GetString());
789 Spacing::Space tmp_space = Spacing::Default;
791 if (tmp == "single") {
792 tmp_space = Spacing::Single;
793 } else if (tmp == "onehalf") {
794 tmp_space = Spacing::Onehalf;
795 } else if (tmp == "double") {
796 tmp_space = Spacing::Double;
797 } else if (tmp == "other") {
799 tmp_space = Spacing::Other;
800 tmp_val = lex.GetFloat();
802 lex.printError("Unknown spacing token: '$$Token'");
804 // Small hack so that files written with klyx will be
807 par->params.spacing(Spacing(tmp_space, tmp_val));
809 params.spacing.set(tmp_space, tmp_val);
811 } else if (token == "\\paragraph_spacing") {
813 string const tmp = strip(lex.GetString());
814 if (tmp == "single") {
815 par->params.spacing(Spacing(Spacing::Single));
816 } else if (tmp == "onehalf") {
817 par->params.spacing(Spacing(Spacing::Onehalf));
818 } else if (tmp == "double") {
819 par->params.spacing(Spacing(Spacing::Double));
820 } else if (tmp == "other") {
822 par->params.spacing(Spacing(Spacing::Other,
825 lex.printError("Unknown spacing token: '$$Token'");
827 } else if (token == "\\float_placement") {
829 params.float_placement = lex.GetString();
830 } else if (token == "\\family") {
832 font.setLyXFamily(lex.GetString());
833 } else if (token == "\\series") {
835 font.setLyXSeries(lex.GetString());
836 } else if (token == "\\shape") {
838 font.setLyXShape(lex.GetString());
839 } else if (token == "\\size") {
841 font.setLyXSize(lex.GetString());
842 } else if (token == "\\latex") {
844 string const tok = lex.GetString();
845 // This is dirty, but gone with LyX3. (Asger)
846 if (tok == "no_latex")
847 font.setLatex(LyXFont::OFF);
848 else if (tok == "latex")
849 font.setLatex(LyXFont::ON);
850 else if (tok == "default")
851 font.setLatex(LyXFont::INHERIT);
853 lex.printError("Unknown LaTeX font flag "
855 } else if (token == "\\lang") {
857 string const tok = lex.GetString();
858 Language const * lang = languages.getLanguage(tok);
860 font.setLanguage(lang);
862 font.setLanguage(params.language);
863 lex.printError("Unknown language `$$Token'");
865 } else if (token == "\\numeric") {
867 font.setNumber(font.setLyXMisc(lex.GetString()));
868 } else if (token == "\\emph") {
870 font.setEmph(font.setLyXMisc(lex.GetString()));
871 } else if (token == "\\bar") {
873 string const tok = lex.GetString();
874 // This is dirty, but gone with LyX3. (Asger)
876 font.setUnderbar(LyXFont::ON);
877 else if (tok == "no")
878 font.setUnderbar(LyXFont::OFF);
879 else if (tok == "default")
880 font.setUnderbar(LyXFont::INHERIT);
882 lex.printError("Unknown bar font flag "
884 } else if (token == "\\noun") {
886 font.setNoun(font.setLyXMisc(lex.GetString()));
887 } else if (token == "\\color") {
889 font.setLyXColor(lex.GetString());
890 } else if (token == "\\align") {
891 int tmpret = lex.FindToken(string_align);
892 if (tmpret == -1) ++tmpret;
893 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
894 int const tmpret2 = int(pow(2.0, tmpret));
895 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
896 par->params.align(LyXAlignment(tmpret2));
898 } else if (token == "\\added_space_top") {
900 par->params.spaceTop(VSpace(lex.GetString()));
901 } else if (token == "\\added_space_bottom") {
903 par->params.spaceBottom(VSpace(lex.GetString()));
904 #ifndef NO_PEXTRA_REALLY
905 } else if (token == "\\pextra_type") {
907 par->params.pextraType(lex.GetInteger());
908 } else if (token == "\\pextra_width") {
910 par->params.pextraWidth(lex.GetString());
911 } else if (token == "\\pextra_widthp") {
913 par->params.pextraWidthp(lex.GetString());
914 } else if (token == "\\pextra_alignment") {
916 par->params.pextraAlignment(lex.GetInteger());
917 } else if (token == "\\pextra_hfill") {
919 par->params.pextraHfill(lex.GetInteger());
920 } else if (token == "\\pextra_start_minipage") {
922 par->params.pextraStartMinipage(lex.GetInteger());
924 } else if (token == "\\labelwidthstring") {
926 par->params.labelWidthString(lex.GetString());
927 // do not delete this token, it is still needed!
928 } else if (token == "\\end_inset") {
929 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
930 << "Last inset read was: " << last_inset_read
932 // Simply ignore this. The insets do not have
934 // But insets should read it, it is a part of
935 // the inset isn't it? Lgb.
936 } else if (token == "\\begin_inset") {
937 readInset(lex, par, pos, font);
938 } else if (token == "\\SpecialChar") {
939 LyXLayout const & layout =
940 textclasslist.Style(params.textclass,
943 // Insets don't make sense in a free-spacing context! ---Kayvan
944 if (layout.free_spacing) {
947 string next_token = lex.GetString();
948 if (next_token == "\\-") {
949 par->InsertChar(pos, '-', font);
950 } else if (next_token == "\\protected_separator"
951 || next_token == "~") {
952 par->InsertChar(pos, ' ', font);
954 lex.printError("Token `$$Token' "
956 "paragraph layout!");
961 Inset * inset = new InsetSpecialChar;
962 inset->Read(this, lex);
963 par->InsertInset(pos, inset, font);
966 } else if (token == "\\newline") {
967 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
969 } else if (token == "\\LyXTable") {
970 Inset * inset = new InsetTabular(*this);
971 inset->Read(this, lex);
972 par->InsertInset(pos, inset, font);
974 // because of OLD_TABULAR_READ where tabulars have been
976 checkminipage = true;
977 } else if (token == "\\hfill") {
978 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
980 } else if (token == "\\protected_separator") { // obsolete
981 // This is a backward compability thingie. (Lgb)
982 // Remove it later some time...introduced with fileformat
984 LyXLayout const & layout =
985 textclasslist.Style(params.textclass,
988 if (layout.free_spacing) {
989 par->InsertChar(pos, ' ', font);
991 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
992 par->InsertInset(pos, inset, font);
995 } else if (token == "\\bibitem") { // ale970302
997 InsetCommandParams p("bibitem", "dummy");
998 par->bibkey = new InsetBibKey(p);
1000 par->bibkey->Read(this, lex);
1001 } else if (token == "\\backslash") {
1002 par->InsertChar(pos, '\\', font);
1004 } else if (token == "\\the_end") {
1005 the_end_read = true;
1006 minipar = parBeforeMinipage = 0;
1008 // This should be insurance for the future: (Asger)
1009 lex.printError("Unknown token `$$Token'. "
1010 "Inserting as text.");
1011 string::const_iterator cit = token.begin();
1012 string::const_iterator end = token.end();
1013 for (; cit != end; ++cit) {
1014 par->InsertChar(pos, (*cit), font);
1018 #ifndef NO_PEXTRA_REALLY
1019 // now check if we have a minipage paragraph as at this
1020 // point we already read all the necessary data!
1021 // this cannot be done in layout because there we did
1022 // not read yet the paragraph PEXTRA-params (Jug)
1024 // BEGIN pextra_minipage compability
1025 // This should be removed in 1.3.x (Lgb)
1027 // This compability code is not perfect. In a couple
1028 // of rand cases it fails. When the minipage par is
1029 // the first par in the document, and when there are
1030 // none or only one regular paragraphs after the
1031 // minipage. Currently I am not investing any effort
1032 // in fixing those cases.
1034 //lyxerr << "Call depth: " << call_depth << endl;
1035 if (checkminipage && (call_depth == 1)) {
1036 checkminipage = false;
1037 if (minipar && (minipar != par) &&
1038 (par->params.pextraType()==LyXParagraph::PEXTRA_MINIPAGE))
1040 lyxerr << "minipages in a row" << endl;
1041 if (par->params.pextraStartMinipage()) {
1042 lyxerr << "start new minipage" << endl;
1043 // minipages in a row
1044 par->previous()->next(0);
1047 LyXParagraph * tmp = minipar;
1049 tmp->params.pextraType(0);
1050 tmp->params.pextraWidth(string());
1051 tmp->params.pextraWidthp(string());
1052 tmp->params.pextraAlignment(0);
1053 tmp->params.pextraHfill(false);
1054 tmp->params.pextraStartMinipage(false);
1057 // create a new paragraph to insert the
1058 // minipages in the following case
1059 if (par->params.pextraStartMinipage() &&
1060 !par->params.pextraHfill())
1062 LyXParagraph * p = new LyXParagraph;
1064 p->previous(parBeforeMinipage);
1065 parBeforeMinipage->next(p);
1067 p->params.depth(parBeforeMinipage->params.depth());
1068 parBeforeMinipage = p;
1070 InsetMinipage * mini = new InsetMinipage;
1071 mini->pos(static_cast<InsetMinipage::Position>(par->params.pextraAlignment()));
1072 mini->width(par->params.pextraWidth());
1073 if (!par->params.pextraWidthp().empty()) {
1074 lyxerr << "WP:" << mini->width() << endl;
1075 mini->width(tostr(par->params.pextraWidthp())+"%");
1077 mini->inset.par = par;
1078 // Insert the minipage last in the
1079 // previous paragraph.
1080 if (par->params.pextraHfill()) {
1081 parBeforeMinipage->InsertChar
1082 (parBeforeMinipage->size(), LyXParagraph::META_HFILL);
1084 parBeforeMinipage->InsertInset
1085 (parBeforeMinipage->size(), mini);
1089 lyxerr << "new minipage par" << endl;
1090 //nothing to do just continue reading
1093 } else if (minipar && (minipar != par)) {
1094 lyxerr << "last minipage par read" << endl;
1095 // The last paragraph read was not part of a
1096 // minipage but the par linked list is...
1097 // So we need to remove the last par from the
1099 if (par->previous())
1100 par->previous()->next(0);
1101 par->previous(parBeforeMinipage);
1102 parBeforeMinipage->next(par);
1103 LyXParagraph * tmp = minipar;
1105 tmp->params.pextraType(0);
1106 tmp->params.pextraWidth(string());
1107 tmp->params.pextraWidthp(string());
1108 tmp->params.pextraAlignment(0);
1109 tmp->params.pextraHfill(false);
1110 tmp->params.pextraStartMinipage(false);
1113 depth = parBeforeMinipage->params.depth();
1114 minipar = parBeforeMinipage = 0;
1115 } else if (!minipar &&
1116 (par->params.pextraType() == LyXParagraph::PEXTRA_MINIPAGE))
1118 // par is the first paragraph in a minipage
1119 lyxerr << "begin minipage" << endl;
1120 // To minimize problems for
1121 // the users we will insert
1122 // the first minipage in
1123 // a sequence of minipages
1124 // in its own paragraph.
1125 LyXParagraph * p = new LyXParagraph;
1127 p->previous(par->previous());
1129 p->params.depth(depth);
1130 par->params.depth(0);
1132 if (par->previous())
1133 par->previous()->next(p);
1135 parBeforeMinipage = p;
1137 if (!return_par || (return_par == par))
1140 InsetMinipage * mini = new InsetMinipage;
1141 mini->pos(static_cast<InsetMinipage::Position>(minipar->params.pextraAlignment()));
1142 mini->width(minipar->params.pextraWidth());
1143 if (!par->params.pextraWidthp().empty()) {
1144 lyxerr << "WP:" << mini->width() << endl;
1145 mini->width(tostr(par->params.pextraWidthp())+"%");
1147 mini->inset.par = minipar;
1149 // Insert the minipage last in the
1150 // previous paragraph.
1151 if (minipar->params.pextraHfill()) {
1152 parBeforeMinipage->InsertChar
1153 (parBeforeMinipage->size(),LyXParagraph::META_HFILL);
1155 parBeforeMinipage->InsertInset
1156 (parBeforeMinipage->size(), mini);
1159 // End of pextra_minipage compability
1162 return the_end_read;
1166 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1167 int & pos, LyXFont & font)
1169 // consistency check
1170 if (lex.GetString() != "\\begin_inset") {
1171 lyxerr << "Buffer::readInset: Consistency check failed."
1178 string const tmptok = lex.GetString();
1179 last_inset_read = tmptok;
1181 // test the different insets
1182 if (tmptok == "LatexCommand") {
1183 InsetCommandParams inscmd;
1186 string const cmdName = inscmd.getCmdName();
1188 if (cmdName == "cite") {
1189 inset = new InsetCitation(inscmd);
1190 } else if (cmdName == "bibitem") {
1191 lex.printError("Wrong place for bibitem");
1192 inset = new InsetBibKey(inscmd);
1193 } else if (cmdName == "BibTeX") {
1194 inset = new InsetBibtex(inscmd);
1195 } else if (cmdName == "index") {
1196 inset = new InsetIndex(inscmd);
1197 } else if (cmdName == "include") {
1198 inset = new InsetInclude(inscmd, *this);
1199 } else if (cmdName == "label") {
1200 inset = new InsetLabel(inscmd);
1201 } else if (cmdName == "url"
1202 || cmdName == "htmlurl") {
1203 inset = new InsetUrl(inscmd);
1204 } else if (cmdName == "ref"
1205 || cmdName == "pageref"
1206 || cmdName == "vref"
1207 || cmdName == "vpageref"
1208 || cmdName == "prettyref") {
1209 if (!inscmd.getOptions().empty()
1210 || !inscmd.getContents().empty()) {
1211 inset = new InsetRef(inscmd, *this);
1213 } else if (cmdName == "tableofcontents") {
1214 inset = new InsetTOC(inscmd);
1215 } else if (cmdName == "listofalgorithms") {
1216 inset = new InsetFloatList("algorithm");
1217 } else if (cmdName == "listoffigures") {
1218 inset = new InsetFloatList("figure");
1219 } else if (cmdName == "listoftables") {
1220 inset = new InsetFloatList("table");
1221 } else if (cmdName == "printindex") {
1222 inset = new InsetPrintIndex(inscmd);
1223 } else if (cmdName == "lyxparent") {
1224 inset = new InsetParent(inscmd, *this);
1227 if (tmptok == "Quotes") {
1228 inset = new InsetQuotes;
1229 } else if (tmptok == "External") {
1230 inset = new InsetExternal;
1231 } else if (tmptok == "FormulaMacro") {
1232 inset = new InsetFormulaMacro;
1233 } else if (tmptok == "Formula") {
1234 inset = new InsetFormula;
1235 } else if (tmptok == "Figure") {
1236 inset = new InsetFig(100, 100, *this);
1237 } else if (tmptok == "Info") {
1238 inset = new InsetInfo;
1239 } else if (tmptok == "Include") {
1240 InsetCommandParams p( "Include" );
1241 inset = new InsetInclude(p, *this);
1242 } else if (tmptok == "ERT") {
1243 inset = new InsetERT;
1244 } else if (tmptok == "Tabular") {
1245 inset = new InsetTabular(*this);
1246 } else if (tmptok == "Text") {
1247 inset = new InsetText;
1248 } else if (tmptok == "Foot") {
1249 inset = new InsetFoot;
1250 } else if (tmptok == "Marginal") {
1251 inset = new InsetMarginal;
1252 } else if (tmptok == "Minipage") {
1253 inset = new InsetMinipage;
1254 } else if (tmptok == "Float") {
1256 string tmptok = lex.GetString();
1257 inset = new InsetFloat(tmptok);
1258 } else if (tmptok == "List") {
1259 inset = new InsetList;
1260 } else if (tmptok == "Theorem") {
1261 inset = new InsetList;
1262 } else if (tmptok == "Caption") {
1263 inset = new InsetCaption;
1264 } else if (tmptok == "GRAPHICS") {
1265 inset = new InsetGraphics;
1266 } else if (tmptok == "FloatList") {
1267 inset = new InsetFloatList;
1270 if (inset) inset->Read(this, lex);
1274 par->InsertInset(pos, inset, font);
1280 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1284 string const token(lex.GetString());
1285 if (token == "\\lyxformat") { // the first token _must_ be...
1287 string tmp_format = lex.GetString();
1288 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1289 // if present remove ".," from string.
1290 string::size_type dot = tmp_format.find_first_of(".,");
1291 //lyxerr << " dot found at " << dot << endl;
1292 if (dot != string::npos)
1293 tmp_format.erase(dot, 1);
1294 file_format = strToInt(tmp_format);
1295 if (file_format == LYX_FORMAT) {
1297 } else if (file_format > LYX_FORMAT) {
1299 WriteAlert(_("Warning!"),
1300 _("LyX file format is newer that what"),
1301 _("is supported in this LyX version. Expect some problems."));
1303 } else if (file_format < LYX_FORMAT) {
1305 if (file_format < 200) {
1306 WriteAlert(_("ERROR!"),
1307 _("Old LyX file format found. "
1308 "Use LyX 0.10.x to read this!"));
1312 bool the_end = readLyXformat2(lex, par);
1314 // the_end was added in 213
1315 if (file_format < 213)
1319 WriteAlert(_("Warning!"),
1320 _("Reading of document is not complete"),
1321 _("Maybe the document is truncated"));
1323 } else { // "\\lyxformat" not found
1324 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1327 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1333 // Should probably be moved to somewhere else: BufferView? LyXView?
1334 bool Buffer::save() const
1336 // We don't need autosaves in the immediate future. (Asger)
1337 resetAutosaveTimers();
1341 if (lyxrc.make_backup) {
1342 s = fileName() + '~';
1343 if (!lyxrc.backupdir_path.empty())
1344 s = AddName(lyxrc.backupdir_path,
1345 subst(os::slashify_path(s),'/','!'));
1347 // Rename is the wrong way of making a backup,
1348 // this is the correct way.
1349 /* truss cp fil fil2:
1350 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1351 stat("LyXVC.lyx", 0xEFFFF688) = 0
1352 open("LyXVC.lyx", O_RDONLY) = 3
1353 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1354 fstat(4, 0xEFFFF508) = 0
1355 fstat(3, 0xEFFFF508) = 0
1356 read(3, " # T h i s f i l e w".., 8192) = 5579
1357 write(4, " # T h i s f i l e w".., 5579) = 5579
1358 read(3, 0xEFFFD4A0, 8192) = 0
1361 chmod("LyXVC3.lyx", 0100644) = 0
1362 lseek(0, 0, SEEK_CUR) = 46440
1366 // Should proabaly have some more error checking here.
1367 // Should be cleaned up in 0.13, at least a bit.
1368 // Doing it this way, also makes the inodes stay the same.
1369 // This is still not a very good solution, in particular we
1370 // might loose the owner of the backup.
1371 FileInfo finfo(fileName());
1372 if (finfo.exist()) {
1373 mode_t fmode = finfo.getMode();
1374 struct utimbuf times = {
1375 finfo.getAccessTime(),
1376 finfo.getModificationTime() };
1378 ifstream ifs(fileName().c_str());
1379 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1384 ::chmod(s.c_str(), fmode);
1386 if (::utime(s.c_str(), ×)) {
1387 lyxerr << "utime error." << endl;
1390 lyxerr << "LyX was not able to make "
1391 "backupcopy. Beware." << endl;
1396 if (writeFile(fileName(), false)) {
1398 removeAutosaveFile(fileName());
1400 // Saving failed, so backup is not backup
1401 if (lyxrc.make_backup) {
1402 lyx::rename(s, fileName());
1410 // Returns false if unsuccesful
1411 bool Buffer::writeFile(string const & fname, bool flag) const
1413 // if flag is false writeFile will not create any GUI
1414 // warnings, only cerr.
1415 // Needed for autosave in background or panic save (Matthias 120496)
1417 if (read_only && (fname == filename)) {
1418 // Here we should come with a question if we should
1419 // perform the write anyway.
1421 lyxerr << _("Error! Document is read-only: ")
1424 WriteAlert(_("Error! Document is read-only: "),
1429 FileInfo finfo(fname);
1430 if (finfo.exist() && !finfo.writable()) {
1431 // Here we should come with a question if we should
1432 // try to do the save anyway. (i.e. do a chmod first)
1434 lyxerr << _("Error! Cannot write file: ")
1437 WriteFSAlert(_("Error! Cannot write file: "),
1442 ofstream ofs(fname.c_str());
1445 lyxerr << _("Error! Cannot open file: ")
1448 WriteFSAlert(_("Error! Cannot open file: "),
1454 // Use the standard "C" locale for file output.
1455 ofs.imbue(std::locale::classic());
1458 // The top of the file should not be written by params.
1460 // write out a comment in the top of the file
1461 ofs << '#' << LYX_DOCVERSION
1462 << " created this file. For more info see http://www.lyx.org/\n"
1463 << "\\lyxformat " << LYX_FORMAT << "\n";
1465 // now write out the buffer paramters.
1466 params.writeFile(ofs);
1470 // this will write out all the paragraphs
1471 // using recursive descent.
1472 paragraph->writeFile(this, ofs, params, depth);
1474 // Write marker that shows file is complete
1475 ofs << "\n\\the_end" << endl;
1479 // how to check if close went ok?
1480 // Following is an attempt... (BE 20001011)
1482 // good() returns false if any error occured, including some
1483 // formatting error.
1484 // bad() returns true if something bad happened in the buffer,
1485 // which should include file system full errors.
1492 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1494 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1504 string const Buffer::asciiParagraph(LyXParagraph const * par,
1505 unsigned int linelen) const
1507 ostringstream buffer;
1510 int ltype_depth = 0;
1511 unsigned int currlinelen = 0;
1512 bool ref_printed = false;
1516 if (!par->previous()) {
1517 // begins or ends a deeper area ?
1518 if (depth != par->params.depth()) {
1519 if (par->params.depth() > depth) {
1520 while (par->params.depth() > depth) {
1524 while (par->params.depth() < depth) {
1530 // First write the layout
1531 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1532 if (tmp == "Itemize") {
1534 ltype_depth = depth + 1;
1535 } else if (tmp == "Enumerate") {
1537 ltype_depth = depth + 1;
1538 } else if (contains(tmp, "ection")) {
1540 ltype_depth = depth + 1;
1541 } else if (contains(tmp, "aragraph")) {
1543 ltype_depth = depth + 1;
1544 } else if (tmp == "Description") {
1546 ltype_depth = depth + 1;
1547 } else if (tmp == "Abstract") {
1550 } else if (tmp == "Bibliography") {
1558 /* maybe some vertical spaces */
1560 /* the labelwidthstring used in lists */
1564 /* some pagebreaks? */
1568 /* what about the alignment */
1570 lyxerr << "Should this ever happen?" << endl;
1573 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1574 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1575 if (!i && !noparbreak) {
1578 for (char j = 0; j < depth; ++j)
1580 currlinelen = depth * 2;
1583 case 4: // (Sub)Paragraph
1584 case 5: // Description
1588 buffer << "Abstract\n\n";
1590 buffer << "Abstract: ";
1592 case 7: // Bibliography
1595 buffer << "References\n\n";
1597 buffer << "References: ";
1602 buffer << par->params.labelString() << " ";
1605 if (ltype_depth > depth) {
1606 for (char j = ltype_depth - 1; j > depth; --j)
1608 currlinelen += (ltype_depth-depth)*2;
1611 LyXFont const font2 = par->GetFontSettings(params, i);
1612 if (font1.latex() != font2.latex()) {
1613 if (font2.latex() == LyXFont::OFF)
1621 char c = par->GetUChar(params, i);
1625 case LyXParagraph::META_INSET:
1627 Inset const * inset = par->GetInset(i);
1629 if (!inset->Ascii(this, buffer)) {
1632 rsplit(buffer.str().c_str(),
1634 currlinelen += s.length();
1636 // to be sure it breaks paragraph
1637 currlinelen += linelen;
1643 case LyXParagraph::META_NEWLINE:
1646 for (char j = 0; j < depth; ++j)
1649 currlinelen = depth * 2;
1650 if (ltype_depth > depth) {
1651 for (char j = ltype_depth;
1654 currlinelen += (ltype_depth - depth) * 2;
1658 case LyXParagraph::META_HFILL:
1667 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1668 (c == ' ') && ((i + 2) < par->size()))
1671 for (char j = 0; j < depth; ++j)
1673 currlinelen = depth * 2;
1674 if (ltype_depth > depth) {
1675 for (char j = ltype_depth;
1678 currlinelen += (ltype_depth-depth)*2;
1680 } else if (c != '\0')
1683 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1688 return buffer.str().c_str();
1692 void Buffer::writeFileAscii(string const & fname, int linelen)
1694 ofstream ofs(fname.c_str());
1696 WriteFSAlert(_("Error: Cannot write file:"), fname);
1699 writeFileAscii(ofs, linelen);
1703 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1705 LyXParagraph * par = paragraph;
1707 ofs << asciiParagraph(par, linelen);
1715 void Buffer::makeLaTeXFile(string const & fname,
1716 string const & original_path,
1717 bool nice, bool only_body)
1719 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1721 niceFile = nice; // this will be used by Insetincludes.
1723 tex_code_break_column = lyxrc.ascii_linelen;
1725 LyXTextClass const & tclass =
1726 textclasslist.TextClass(params.textclass);
1728 ofstream ofs(fname.c_str());
1730 WriteFSAlert(_("Error: Cannot open file: "), fname);
1734 // validate the buffer.
1735 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1736 LaTeXFeatures features(params, tclass.numLayouts());
1738 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1741 // The starting paragraph of the coming rows is the
1742 // first paragraph of the document. (Asger)
1743 texrow.start(paragraph, 0);
1745 if (!only_body && nice) {
1746 ofs << "%% " LYX_DOCVERSION " created this file. "
1747 "For more info, see http://www.lyx.org/.\n"
1748 "%% Do not edit unless you really know what "
1753 lyxerr.debug() << "lyx header finished" << endl;
1754 // There are a few differences between nice LaTeX and usual files:
1755 // usual is \batchmode and has a
1756 // special input@path to allow the including of figures
1757 // with either \input or \includegraphics (what figinsets do).
1758 // batchmode is not set if there is a tex_code_break_column.
1759 // In this case somebody is interested in the generated LaTeX,
1760 // so this is OK. input@path is set when the actual parameter
1761 // original_path is set. This is done for usual tex-file, but not
1762 // for nice-latex-file. (Matthias 250696)
1765 // code for usual, NOT nice-latex-file
1766 ofs << "\\batchmode\n"; // changed
1767 // from \nonstopmode
1770 if (!original_path.empty()) {
1771 ofs << "\\makeatletter\n"
1772 << "\\def\\input@path{{"
1773 << os::external_path(original_path) << "/}}\n"
1774 << "\\makeatother\n";
1780 ofs << "\\documentclass";
1782 ostringstream options; // the document class options.
1784 if (tokenPos(tclass.opt_fontsize(),
1785 '|', params.fontsize) >= 0) {
1786 // only write if existing in list (and not default)
1787 options << params.fontsize << "pt,";
1791 if (!params.use_geometry &&
1792 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1793 switch (params.papersize) {
1794 case BufferParams::PAPER_A4PAPER:
1795 options << "a4paper,";
1797 case BufferParams::PAPER_USLETTER:
1798 options << "letterpaper,";
1800 case BufferParams::PAPER_A5PAPER:
1801 options << "a5paper,";
1803 case BufferParams::PAPER_B5PAPER:
1804 options << "b5paper,";
1806 case BufferParams::PAPER_EXECUTIVEPAPER:
1807 options << "executivepaper,";
1809 case BufferParams::PAPER_LEGALPAPER:
1810 options << "legalpaper,";
1816 if (params.sides != tclass.sides()) {
1817 switch (params.sides) {
1818 case LyXTextClass::OneSide:
1819 options << "oneside,";
1821 case LyXTextClass::TwoSides:
1822 options << "twoside,";
1828 if (params.columns != tclass.columns()) {
1829 if (params.columns == 2)
1830 options << "twocolumn,";
1832 options << "onecolumn,";
1835 if (!params.use_geometry
1836 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1837 options << "landscape,";
1839 // language should be a parameter to \documentclass
1841 ostringstream language_options;
1842 if (params.language->babel() == "hebrew"
1843 && default_language->babel() != "hebrew")
1844 // This seems necessary
1845 features.UsedLanguages.insert(default_language);
1847 if (lyxrc.language_use_babel ||
1848 params.language->lang() != lyxrc.default_language ||
1849 !features.UsedLanguages.empty()) {
1851 for (LaTeXFeatures::LanguageList::const_iterator cit =
1852 features.UsedLanguages.begin();
1853 cit != features.UsedLanguages.end(); ++cit)
1854 language_options << (*cit)->babel() << ',';
1855 language_options << params.language->babel();
1856 if (lyxrc.language_global_options)
1857 options << language_options.str() << ',';
1860 // the user-defined options
1861 if (!params.options.empty()) {
1862 options << params.options << ',';
1865 string strOptions(options.str().c_str());
1866 if (!strOptions.empty()){
1867 strOptions = strip(strOptions, ',');
1868 ofs << '[' << strOptions << ']';
1872 << textclasslist.LatexnameOfClass(params.textclass)
1875 // end of \documentclass defs
1877 // font selection must be done before loading fontenc.sty
1878 // The ae package is not needed when using OT1 font encoding.
1879 if (params.fonts != "default" &&
1880 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1881 ofs << "\\usepackage{" << params.fonts << "}\n";
1883 if (params.fonts == "ae") {
1884 ofs << "\\usepackage{aecompl}\n";
1888 // this one is not per buffer
1889 if (lyxrc.fontenc != "default") {
1890 ofs << "\\usepackage[" << lyxrc.fontenc
1895 if (params.inputenc == "auto") {
1896 string const doc_encoding =
1897 params.language->encoding()->LatexName();
1899 // Create a list with all the input encodings used
1901 set<string> encodings;
1902 for (LaTeXFeatures::LanguageList::const_iterator it =
1903 features.UsedLanguages.begin();
1904 it != features.UsedLanguages.end(); ++it)
1905 if ((*it)->encoding()->LatexName() != doc_encoding)
1906 encodings.insert((*it)->encoding()->LatexName());
1908 ofs << "\\usepackage[";
1909 std::copy(encodings.begin(), encodings.end(),
1910 std::ostream_iterator<string>(ofs, ","));
1911 ofs << doc_encoding << "]{inputenc}\n";
1913 } else if (params.inputenc != "default") {
1914 ofs << "\\usepackage[" << params.inputenc
1919 // At the very beginning the text parameters.
1920 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1921 switch (params.paperpackage) {
1922 case BufferParams::PACKAGE_A4:
1923 ofs << "\\usepackage{a4}\n";
1926 case BufferParams::PACKAGE_A4WIDE:
1927 ofs << "\\usepackage{a4wide}\n";
1930 case BufferParams::PACKAGE_WIDEMARGINSA4:
1931 ofs << "\\usepackage[widemargins]{a4}\n";
1936 if (params.use_geometry) {
1937 ofs << "\\usepackage{geometry}\n";
1939 ofs << "\\geometry{verbose";
1940 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1941 ofs << ",landscape";
1942 switch (params.papersize2) {
1943 case BufferParams::VM_PAPER_CUSTOM:
1944 if (!params.paperwidth.empty())
1945 ofs << ",paperwidth="
1946 << params.paperwidth;
1947 if (!params.paperheight.empty())
1948 ofs << ",paperheight="
1949 << params.paperheight;
1951 case BufferParams::VM_PAPER_USLETTER:
1952 ofs << ",letterpaper";
1954 case BufferParams::VM_PAPER_USLEGAL:
1955 ofs << ",legalpaper";
1957 case BufferParams::VM_PAPER_USEXECUTIVE:
1958 ofs << ",executivepaper";
1960 case BufferParams::VM_PAPER_A3:
1963 case BufferParams::VM_PAPER_A4:
1966 case BufferParams::VM_PAPER_A5:
1969 case BufferParams::VM_PAPER_B3:
1972 case BufferParams::VM_PAPER_B4:
1975 case BufferParams::VM_PAPER_B5:
1979 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1980 switch (lyxrc.default_papersize) {
1981 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1982 case BufferParams::PAPER_USLETTER:
1983 ofs << ",letterpaper";
1985 case BufferParams::PAPER_LEGALPAPER:
1986 ofs << ",legalpaper";
1988 case BufferParams::PAPER_EXECUTIVEPAPER:
1989 ofs << ",executivepaper";
1991 case BufferParams::PAPER_A3PAPER:
1994 case BufferParams::PAPER_A4PAPER:
1997 case BufferParams::PAPER_A5PAPER:
2000 case BufferParams::PAPER_B5PAPER:
2005 if (!params.topmargin.empty())
2006 ofs << ",tmargin=" << params.topmargin;
2007 if (!params.bottommargin.empty())
2008 ofs << ",bmargin=" << params.bottommargin;
2009 if (!params.leftmargin.empty())
2010 ofs << ",lmargin=" << params.leftmargin;
2011 if (!params.rightmargin.empty())
2012 ofs << ",rmargin=" << params.rightmargin;
2013 if (!params.headheight.empty())
2014 ofs << ",headheight=" << params.headheight;
2015 if (!params.headsep.empty())
2016 ofs << ",headsep=" << params.headsep;
2017 if (!params.footskip.empty())
2018 ofs << ",footskip=" << params.footskip;
2022 if (features.amsstyle
2023 && !tclass.provides(LyXTextClass::amsmath)) {
2024 ofs << "\\usepackage{amsmath}\n";
2028 if (tokenPos(tclass.opt_pagestyle(),
2029 '|', params.pagestyle) >= 0) {
2030 if (params.pagestyle == "fancy") {
2031 ofs << "\\usepackage{fancyhdr}\n";
2034 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2038 // We try to load babel late, in case it interferes
2039 // with other packages.
2041 string tmp = lyxrc.language_package;
2042 if (!lyxrc.language_global_options
2043 && tmp == "\\usepackage{babel}")
2044 tmp = string("\\usepackage[") +
2045 language_options.str().c_str() +
2051 if (params.secnumdepth != tclass.secnumdepth()) {
2052 ofs << "\\setcounter{secnumdepth}{"
2053 << params.secnumdepth
2057 if (params.tocdepth != tclass.tocdepth()) {
2058 ofs << "\\setcounter{tocdepth}{"
2064 if (params.paragraph_separation) {
2065 switch (params.defskip.kind()) {
2066 case VSpace::SMALLSKIP:
2067 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2069 case VSpace::MEDSKIP:
2070 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2072 case VSpace::BIGSKIP:
2073 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2075 case VSpace::LENGTH:
2076 ofs << "\\setlength\\parskip{"
2077 << params.defskip.length().asLatexString()
2080 default: // should never happen // Then delete it.
2081 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2086 ofs << "\\setlength\\parindent{0pt}\n";
2090 // Now insert the LyX specific LaTeX commands...
2092 // The optional packages;
2093 string preamble(features.getPackages());
2095 // this might be useful...
2096 preamble += "\n\\makeatletter\n";
2098 // Some macros LyX will need
2099 string tmppreamble(features.getMacros());
2101 if (!tmppreamble.empty()) {
2102 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2103 "LyX specific LaTeX commands.\n"
2104 + tmppreamble + '\n';
2107 // the text class specific preamble
2108 tmppreamble = features.getTClassPreamble();
2109 if (!tmppreamble.empty()) {
2110 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2111 "Textclass specific LaTeX commands.\n"
2112 + tmppreamble + '\n';
2115 /* the user-defined preamble */
2116 if (!params.preamble.empty()) {
2117 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2118 "User specified LaTeX commands.\n"
2119 + params.preamble + '\n';
2122 preamble += "\\makeatother\n";
2124 // Itemize bullet settings need to be last in case the user
2125 // defines their own bullets that use a package included
2126 // in the user-defined preamble -- ARRae
2127 // Actually it has to be done much later than that
2128 // since some packages like frenchb make modifications
2129 // at \begin{document} time -- JMarc
2131 for (int i = 0; i < 4; ++i) {
2132 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2133 if (bullets_def.empty())
2134 bullets_def="\\AtBeginDocument{\n";
2135 bullets_def += " \\renewcommand{\\labelitemi";
2137 // `i' is one less than the item to modify
2144 bullets_def += "ii";
2150 bullets_def += "}{" +
2151 params.user_defined_bullets[i].getText()
2156 if (!bullets_def.empty())
2157 preamble += bullets_def + "}\n\n";
2159 for (int j = countChar(preamble, '\n'); j-- ;) {
2166 ofs << "\\begin{document}\n";
2169 lyxerr.debug() << "preamble finished, now the body." << endl;
2171 if (!lyxrc.language_auto_begin) {
2172 ofs << subst(lyxrc.language_command_begin, "$$lang",
2173 params.language->babel())
2178 latexParagraphs(ofs, paragraph, 0, texrow);
2180 // add this just in case after all the paragraphs
2184 if (!lyxrc.language_auto_end) {
2185 ofs << subst(lyxrc.language_command_end, "$$lang",
2186 params.language->babel())
2192 ofs << "\\end{document}\n";
2195 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2197 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2201 // Just to be sure. (Asger)
2204 // tex_code_break_column's value is used to decide
2205 // if we are in batchmode or not (within mathed_write()
2206 // in math_write.C) so we must set it to a non-zero
2207 // value when we leave otherwise we save incorrect .lyx files.
2208 tex_code_break_column = lyxrc.ascii_linelen;
2212 lyxerr << "File was not closed properly." << endl;
2215 lyxerr.debug() << "Finished making latex file." << endl;
2220 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2222 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2223 LyXParagraph * endpar, TexRow & texrow) const
2225 bool was_title = false;
2226 bool already_title = false;
2229 while (par != endpar) {
2230 LyXLayout const & layout =
2231 textclasslist.Style(params.textclass,
2234 if (layout.intitle) {
2235 if (already_title) {
2236 lyxerr <<"Error in latexParagraphs: You"
2237 " should not mix title layouts"
2238 " with normal ones." << endl;
2241 } else if (was_title && !already_title) {
2242 ofs << "\\maketitle\n";
2244 already_title = true;
2248 if (layout.isEnvironment()) {
2249 par = par->TeXEnvironment(this, params, ofs, texrow);
2251 par = par->TeXOnePar(this, params, ofs, texrow, false);
2254 // It might be that we only have a title in this document
2255 if (was_title && !already_title) {
2256 ofs << "\\maketitle\n";
2262 bool Buffer::isLatex() const
2264 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2268 bool Buffer::isLinuxDoc() const
2270 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2274 bool Buffer::isLiterate() const
2276 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2280 bool Buffer::isDocBook() const
2282 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2286 bool Buffer::isSGML() const
2288 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2289 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2293 void Buffer::sgmlOpenTag(ostream & os, int depth,
2294 string const & latexname) const
2296 if (!latexname.empty() && latexname != "!-- --")
2297 os << string(depth, ' ') << "<" << latexname << ">\n";
2301 void Buffer::sgmlCloseTag(ostream & os, int depth,
2302 string const & latexname) const
2304 if (!latexname.empty() && latexname != "!-- --")
2305 os << string(depth, ' ') << "</" << latexname << ">\n";
2309 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2311 ofstream ofs(fname.c_str());
2314 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2318 niceFile = nice; // this will be used by included files.
2320 LyXTextClass const & tclass =
2321 textclasslist.TextClass(params.textclass);
2323 LaTeXFeatures features(params, tclass.numLayouts());
2328 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2331 string sgml_includedfiles=features.getIncludedFiles(fname);
2333 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2334 ofs << "<!doctype linuxdoc system>\n\n";
2336 ofs << "<!doctype linuxdoc system [ "
2337 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2340 if (params.options.empty())
2341 sgmlOpenTag(ofs, 0, top_element);
2343 string top = top_element;
2345 top += params.options;
2346 sgmlOpenTag(ofs, 0, top);
2350 ofs << "<!-- " << LYX_DOCVERSION
2351 << " created this file. For more info see http://www.lyx.org/"
2354 int depth = 0; // paragraph depth
2355 LyXParagraph * par = paragraph;
2357 vector<string> environment_stack(5);
2360 LyXLayout const & style =
2361 textclasslist.Style(params.textclass,
2364 // treat <toc> as a special case for compatibility with old code
2365 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2366 Inset * inset = par->GetInset(0);
2367 Inset::Code lyx_code = inset->LyxCode();
2368 if (lyx_code == Inset::TOC_CODE){
2369 string const temp = "toc";
2370 sgmlOpenTag(ofs, depth, temp);
2377 // environment tag closing
2378 for (; depth > par->params.depth(); --depth) {
2379 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2380 environment_stack[depth].erase();
2383 // write opening SGML tags
2384 switch (style.latextype) {
2385 case LATEX_PARAGRAPH:
2386 if (depth == par->params.depth()
2387 && !environment_stack[depth].empty()) {
2388 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2389 environment_stack[depth].erase();
2395 sgmlOpenTag(ofs, depth, style.latexname());
2400 LinuxDocError(par, 0,
2401 _("Error : Wrong depth for"
2402 " LatexType Command.\n"));
2404 if (!environment_stack[depth].empty()){
2405 sgmlCloseTag(ofs, depth,
2406 environment_stack[depth]);
2410 environment_stack[depth].erase();
2411 sgmlOpenTag(ofs, depth, style.latexname());
2414 case LATEX_ENVIRONMENT:
2415 case LATEX_ITEM_ENVIRONMENT:
2416 if (depth == par->params.depth()
2417 && environment_stack[depth] != style.latexname()) {
2418 sgmlCloseTag(ofs, depth,
2419 environment_stack[depth]);
2420 environment_stack[depth].erase();
2422 if (depth < par->params.depth()) {
2423 depth = par->params.depth();
2424 environment_stack[depth].erase();
2426 if (environment_stack[depth] != style.latexname()) {
2428 sgmlOpenTag(ofs, depth, "p");
2430 sgmlOpenTag(ofs, depth, style.latexname());
2432 if (environment_stack.size() == depth + 1)
2433 environment_stack.push_back("!-- --");
2434 environment_stack[depth] = style.latexname();
2437 if (style.latexparam() == "CDATA")
2440 if (style.latextype == LATEX_ENVIRONMENT) break;
2442 if (style.labeltype == LABEL_MANUAL)
2447 sgmlOpenTag(ofs, depth + 1, item_name);
2450 sgmlOpenTag(ofs, depth, style.latexname());
2454 SimpleLinuxDocOnePar(ofs, par, depth);
2459 // write closing SGML tags
2460 switch (style.latextype) {
2463 case LATEX_ENVIRONMENT:
2464 case LATEX_ITEM_ENVIRONMENT:
2465 if (style.latexparam() == "CDATA")
2469 sgmlCloseTag(ofs, depth, style.latexname());
2475 for (int i=depth; i >= 0; --i)
2476 sgmlCloseTag(ofs, depth, environment_stack[i]);
2480 sgmlCloseTag(ofs, 0, top_element);
2484 // How to check for successful close
2488 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2489 int depth, int desc_on,
2490 LyXParagraph * & par)
2492 LyXParagraph * tpar = par;
2494 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2496 tpar = tpar->next();
2499 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2500 "Caption").second) {
2501 sgmlOpenTag(os, depth + 1, inner_tag);
2503 SimpleDocBookOnePar(os, extra_par, tpar,
2504 desc_on, depth + 2);
2505 sgmlCloseTag(os, depth+1, inner_tag);
2506 if (!extra_par.empty())
2512 // checks, if newcol chars should be put into this line
2513 // writes newline, if necessary.
2516 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2517 string::size_type newcol)
2520 if (colcount > lyxrc.ascii_linelen) {
2522 colcount = newcol; // assume write after this call
2537 string tag_name(PAR_TAG const & pt) {
2539 case NONE: return "!-- --";
2540 case TT: return "tt";
2541 case SF: return "sf";
2542 case BF: return "bf";
2543 case IT: return "it";
2544 case SL: return "sl";
2545 case EM: return "em";
2552 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2554 p1 = static_cast<PAR_TAG>(p1 | p2);
2559 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2561 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2569 // Handle internal paragraph parsing -- layout already processed.
2570 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2571 LyXParagraph * par, int /*depth*/)
2573 LyXLayout const & style = textclasslist.Style(params.textclass,
2575 string::size_type char_line_count = 5; // Heuristic choice ;-)
2577 // gets paragraph main font
2580 if (style.labeltype == LABEL_MANUAL) {
2581 font_old = style.labelfont;
2584 font_old = style.font;
2588 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2589 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2590 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2593 stack < PAR_TAG > tag_state;
2594 // parsing main loop
2595 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
2597 PAR_TAG tag_close = NONE;
2598 list < PAR_TAG > tag_open;
2600 LyXFont const font = par->getFont(params, i);
2602 if (font_old.family() != font.family()) {
2603 switch (family_type) {
2604 case LyXFont::SANS_FAMILY:
2607 case LyXFont::TYPEWRITER_FAMILY:
2614 family_type = font.family();
2616 switch (family_type) {
2617 case LyXFont::SANS_FAMILY:
2618 tag_open.push_back(SF);
2620 case LyXFont::TYPEWRITER_FAMILY:
2621 tag_open.push_back(TT);
2628 if (font_old.series() != font.series()) {
2629 switch (series_type) {
2630 case LyXFont::BOLD_SERIES:
2637 series_type = font.series();
2639 switch (series_type) {
2640 case LyXFont::BOLD_SERIES:
2641 tag_open.push_back(BF);
2649 if (font_old.shape() != font.shape()) {
2650 switch (shape_type) {
2651 case LyXFont::ITALIC_SHAPE:
2654 case LyXFont::SLANTED_SHAPE:
2661 shape_type = font.shape();
2663 switch (shape_type) {
2664 case LyXFont::ITALIC_SHAPE:
2665 tag_open.push_back(IT);
2667 case LyXFont::SLANTED_SHAPE:
2668 tag_open.push_back(SL);
2675 if (font_old.emph() != font.emph()) {
2676 if (font.emph() == LyXFont::ON) {
2677 tag_open.push_back(EM);
2686 list < PAR_TAG > temp;
2687 while(!tag_state.empty() && tag_close ) {
2688 PAR_TAG k = tag_state.top();
2690 os << "</" << tag_name(k) << ">";
2697 for(list< PAR_TAG >::const_iterator j = temp.begin();
2698 j != temp.end(); ++j) {
2700 os << "<" << tag_name(*j) << ">";
2703 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2704 j != tag_open.end(); ++j) {
2706 os << "<" << tag_name(*j) << ">";
2709 char c = par->GetChar(i);
2711 if (c == LyXParagraph::META_INSET) {
2712 Inset * inset = par->GetInset(i);
2713 inset->Linuxdoc(this, os);
2718 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
2719 // "TeX"-Mode on == > SGML-Mode on.
2725 if (par->linuxDocConvertChar(c, sgml_string)
2726 && !style.free_spacing) {
2727 // in freespacing mode, spaces are
2728 // non-breaking characters
2729 if (desc_on) {// if char is ' ' then...
2732 linux_doc_line_break(os, char_line_count, 6);
2736 linux_doc_line_break(os, char_line_count, 1);
2741 char_line_count += sgml_string.length();
2747 while (!tag_state.empty()) {
2748 os << "</" << tag_name(tag_state.top()) << ">";
2752 // resets description flag correctly
2754 // <tag> not closed...
2755 linux_doc_line_break(os, char_line_count, 6);
2761 // Print an error message.
2762 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2763 string const & message)
2765 // insert an error marker in text
2766 InsetError * new_inset = new InsetError(message);
2767 par->InsertInset(pos, new_inset);
2771 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2773 ofstream ofs(fname.c_str());
2775 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2779 LyXParagraph * par = paragraph;
2781 niceFile = nice; // this will be used by Insetincludes.
2783 LyXTextClass const & tclass =
2784 textclasslist.TextClass(params.textclass);
2786 LaTeXFeatures features(params, tclass.numLayouts());
2791 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2794 string sgml_includedfiles = features.getIncludedFiles(fname);
2796 ofs << "<!doctype " << top_element
2797 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2799 if (params.preamble.empty() && sgml_includedfiles.empty())
2802 ofs << "\n [ " << params.preamble
2803 << sgml_includedfiles << " \n]>\n\n";
2806 string top = top_element;
2808 top += params.language->code();
2811 if (!params.options.empty()) {
2813 top += params.options;
2815 sgmlOpenTag(ofs, 0, top);
2817 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2818 << "\n See http://www.lyx.org/ for more information -->\n";
2820 vector<string> environment_stack(10);
2821 vector<string> environment_inner(10);
2822 vector<string> command_stack(10);
2824 bool command_flag = false;
2825 int command_depth = 0;
2826 int command_base = 0;
2828 int depth = 0; // paragraph depth
2831 string command_name;
2837 int desc_on = 0; // description mode
2839 LyXLayout const & style =
2840 textclasslist.Style(params.textclass,
2843 // environment tag closing
2844 for (; depth > par->params.depth(); --depth) {
2845 if (environment_inner[depth] != "!-- --") {
2846 item_name = "listitem";
2847 sgmlCloseTag(ofs, command_depth + depth,
2849 if (environment_inner[depth] == "varlistentry")
2850 sgmlCloseTag(ofs, depth+command_depth,
2851 environment_inner[depth]);
2853 sgmlCloseTag(ofs, depth + command_depth,
2854 environment_stack[depth]);
2855 environment_stack[depth].erase();
2856 environment_inner[depth].erase();
2859 if (depth == par->params.depth()
2860 && environment_stack[depth] != style.latexname()
2861 && !environment_stack[depth].empty()) {
2862 if (environment_inner[depth] != "!-- --") {
2863 item_name= "listitem";
2864 sgmlCloseTag(ofs, command_depth+depth,
2866 if (environment_inner[depth] == "varlistentry")
2868 depth + command_depth,
2869 environment_inner[depth]);
2872 sgmlCloseTag(ofs, depth + command_depth,
2873 environment_stack[depth]);
2875 environment_stack[depth].erase();
2876 environment_inner[depth].erase();
2879 // Write opening SGML tags.
2880 switch (style.latextype) {
2881 case LATEX_PARAGRAPH:
2882 sgmlOpenTag(ofs, depth + command_depth,
2888 LinuxDocError(par, 0,
2889 _("Error : Wrong depth for "
2890 "LatexType Command.\n"));
2892 command_name = style.latexname();
2894 sgmlparam = style.latexparam();
2895 c_params = split(sgmlparam, c_depth,'|');
2897 cmd_depth = lyx::atoi(c_depth);
2900 if (cmd_depth < command_base) {
2901 for (int j = command_depth; j >= command_base; --j)
2902 sgmlCloseTag(ofs, j, command_stack[j]);
2903 command_depth = command_base = cmd_depth;
2904 } else if (cmd_depth <= command_depth) {
2905 for (int j = command_depth; j >= cmd_depth; --j)
2906 sgmlCloseTag(ofs, j, command_stack[j]);
2907 command_depth = cmd_depth;
2909 command_depth = cmd_depth;
2911 command_depth = command_base = cmd_depth;
2912 command_flag = true;
2914 if (command_stack.size() == command_depth + 1)
2915 command_stack.push_back("");
2916 command_stack[command_depth] = command_name;
2918 // treat label as a special case for
2919 // more WYSIWYM handling.
2920 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2921 Inset * inset = par->GetInset(0);
2922 Inset::Code lyx_code = inset->LyxCode();
2923 if (lyx_code == Inset::LABEL_CODE){
2924 command_name += " id=\"";
2925 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2926 command_name += "\"";
2931 sgmlOpenTag(ofs, depth + command_depth, command_name);
2932 if (c_params.empty())
2933 item_name = "title";
2935 item_name = c_params;
2936 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2939 case LATEX_ENVIRONMENT:
2940 case LATEX_ITEM_ENVIRONMENT:
2941 if (depth < par->params.depth()) {
2942 depth = par->params.depth();
2943 environment_stack[depth].erase();
2946 if (environment_stack[depth] != style.latexname()) {
2947 if(environment_stack.size() == depth + 1) {
2948 environment_stack.push_back("!-- --");
2949 environment_inner.push_back("!-- --");
2951 environment_stack[depth] = style.latexname();
2952 environment_inner[depth] = "!-- --";
2953 sgmlOpenTag(ofs, depth + command_depth,
2954 environment_stack[depth]);
2956 if (environment_inner[depth] != "!-- --") {
2957 item_name= "listitem";
2959 command_depth + depth,
2961 if (environment_inner[depth] == "varlistentry")
2963 depth + command_depth,
2964 environment_inner[depth]);
2968 if (style.latextype == LATEX_ENVIRONMENT) {
2969 if (!style.latexparam().empty()) {
2970 if(style.latexparam() == "CDATA")
2973 sgmlOpenTag(ofs, depth + command_depth,
2974 style.latexparam());
2979 desc_on = (style.labeltype == LABEL_MANUAL);
2982 environment_inner[depth]= "varlistentry";
2984 environment_inner[depth]= "listitem";
2986 sgmlOpenTag(ofs, depth + 1 + command_depth,
2987 environment_inner[depth]);
2991 sgmlOpenTag(ofs, depth + 1 + command_depth,
2995 sgmlOpenTag(ofs, depth + 1 + command_depth,
3000 sgmlOpenTag(ofs, depth + command_depth,
3006 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3007 depth + 1 + command_depth);
3011 // write closing SGML tags
3012 switch (style.latextype) {
3014 if (c_params.empty())
3018 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3020 case LATEX_ENVIRONMENT:
3021 if (!style.latexparam().empty()) {
3022 if(style.latexparam() == "CDATA")
3025 sgmlCloseTag(ofs, depth + command_depth,
3026 style.latexparam());
3029 case LATEX_ITEM_ENVIRONMENT:
3030 if (desc_on == 1) break;
3032 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3034 case LATEX_PARAGRAPH:
3035 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3038 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3044 for (; depth >= 0; --depth) {
3045 if (!environment_stack[depth].empty()) {
3046 if (environment_inner[depth] != "!-- --") {
3047 item_name = "listitem";
3048 sgmlCloseTag(ofs, command_depth + depth,
3050 if (environment_inner[depth] == "varlistentry")
3051 sgmlCloseTag(ofs, depth + command_depth,
3052 environment_inner[depth]);
3055 sgmlCloseTag(ofs, depth + command_depth,
3056 environment_stack[depth]);
3060 for (int j = command_depth; j >= command_base; --j)
3061 if (!command_stack[j].empty())
3062 sgmlCloseTag(ofs, j, command_stack[j]);
3065 sgmlCloseTag(ofs, 0, top_element);
3068 // How to check for successful close
3072 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3073 LyXParagraph * par, int & desc_on,
3076 bool emph_flag = false;
3078 LyXLayout const & style = textclasslist.Style(params.textclass,
3081 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3083 int char_line_count = depth;
3084 if (!style.free_spacing)
3085 os << string(depth,' ');
3087 // parsing main loop
3088 for (LyXParagraph::size_type i = 0;
3089 i < par->size(); ++i) {
3090 LyXFont font = par->getFont(params, i);
3092 // handle <emphasis> tag
3093 if (font_old.emph() != font.emph()) {
3094 if (font.emph() == LyXFont::ON) {
3098 os << "</emphasis>";
3103 char c = par->GetChar(i);
3105 if (c == LyXParagraph::META_INSET) {
3106 Inset * inset = par->GetInset(i);
3107 std::ostringstream ost;
3108 inset->DocBook(this, ost);
3109 string tmp_out = ost.str().c_str();
3112 // This code needs some explanation:
3113 // Two insets are treated specially
3114 // label if it is the first element in a command paragraph
3116 // graphics inside tables or figure floats can't go on
3117 // title (the equivalente in latex for this case is caption
3118 // and title should come first
3121 if (desc_on!= 3 || i!= 0) {
3122 if (!tmp_out.empty() && tmp_out[0] == '@') {
3124 extra += frontStrip(tmp_out, '@');
3126 os << frontStrip(tmp_out, '@');
3131 } else if (font.latex() == LyXFont::ON) {
3132 // "TeX"-Mode on ==> SGML-Mode on.
3138 if (par->linuxDocConvertChar(c, sgml_string)
3139 && !style.free_spacing) { // in freespacing
3141 // non-breaking characters
3145 os << "\n</term><listitem><para>";
3158 os << "</emphasis>";
3161 // resets description flag correctly
3163 // <term> not closed...
3170 // This should be enabled when the Chktex class is implemented. (Asger)
3171 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3172 // Other flags: -wall -v0 -x
3173 int Buffer::runChktex()
3175 if (!users->text) return 0;
3177 ProhibitInput(users);
3179 // get LaTeX-Filename
3180 string const name = getLatexName();
3181 string path = OnlyPath(filename);
3183 string const org_path = path;
3184 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3188 Path p(path); // path to LaTeX file
3189 users->owner()->message(_("Running chktex..."));
3191 // Remove all error insets
3192 bool const removedErrorInsets = users->removeAutoInsets();
3194 // Generate the LaTeX file if neccessary
3195 makeLaTeXFile(name, org_path, false);
3198 Chktex chktex(lyxrc.chktex_command, name, filepath);
3199 int res = chktex.run(terr); // run chktex
3202 WriteAlert(_("chktex did not work!"),
3203 _("Could not run with file:"), name);
3204 } else if (res > 0) {
3205 // Insert all errors as errors boxes
3206 users->insertErrors(terr);
3209 // if we removed error insets before we ran chktex or if we inserted
3210 // error insets after we ran chktex, this must be run:
3211 if (removedErrorInsets || res){
3213 users->fitCursor(users->text);
3221 void Buffer::validate(LaTeXFeatures & features) const
3223 LyXParagraph * par = paragraph;
3224 LyXTextClass const & tclass =
3225 textclasslist.TextClass(params.textclass);
3227 // AMS Style is at document level
3229 features.amsstyle = (params.use_amsmath ||
3230 tclass.provides(LyXTextClass::amsmath));
3233 // We don't use "lyxerr.debug" because of speed. (Asger)
3234 if (lyxerr.debugging(Debug::LATEX))
3235 lyxerr << "Paragraph: " << par << endl;
3237 // Now just follow the list of paragraphs and run
3238 // validate on each of them.
3239 par->validate(features);
3241 // and then the next paragraph
3245 // the bullet shapes are buffer level not paragraph level
3246 // so they are tested here
3247 for (int i = 0; i < 4; ++i) {
3248 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3249 int const font = params.user_defined_bullets[i].getFont();
3251 int const c = params
3252 .user_defined_bullets[i]
3259 features.latexsym = true;
3261 } else if (font == 1) {
3262 features.amssymb = true;
3263 } else if ((font >= 2 && font <= 5)) {
3264 features.pifont = true;
3269 if (lyxerr.debugging(Debug::LATEX)) {
3270 features.showStruct();
3275 void Buffer::setPaperStuff()
3277 params.papersize = BufferParams::PAPER_DEFAULT;
3278 char const c1 = params.paperpackage;
3279 if (c1 == BufferParams::PACKAGE_NONE) {
3280 char const c2 = params.papersize2;
3281 if (c2 == BufferParams::VM_PAPER_USLETTER)
3282 params.papersize = BufferParams::PAPER_USLETTER;
3283 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3284 params.papersize = BufferParams::PAPER_LEGALPAPER;
3285 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3286 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3287 else if (c2 == BufferParams::VM_PAPER_A3)
3288 params.papersize = BufferParams::PAPER_A3PAPER;
3289 else if (c2 == BufferParams::VM_PAPER_A4)
3290 params.papersize = BufferParams::PAPER_A4PAPER;
3291 else if (c2 == BufferParams::VM_PAPER_A5)
3292 params.papersize = BufferParams::PAPER_A5PAPER;
3293 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3294 (c2 == BufferParams::VM_PAPER_B5))
3295 params.papersize = BufferParams::PAPER_B5PAPER;
3296 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3297 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3298 params.papersize = BufferParams::PAPER_A4PAPER;
3302 // This function should be in Buffer because it's a buffer's property (ale)
3303 string const Buffer::getIncludeonlyList(char delim)
3306 for (inset_iterator it = inset_iterator_begin();
3307 it != inset_iterator_end(); ++it) {
3308 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3309 InsetInclude * insetinc =
3310 static_cast<InsetInclude *>(*it);
3311 if (insetinc->isIncludeOnly()) {
3314 lst += insetinc->getRelFileBaseName();
3318 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3323 vector<string> const Buffer::getLabelList()
3325 /// if this is a child document and the parent is already loaded
3326 /// Use the parent's list instead [ale990407]
3327 if (!params.parentname.empty()
3328 && bufferlist.exists(params.parentname)) {
3329 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3331 return tmp->getLabelList();
3334 vector<string> label_list;
3335 for (inset_iterator it = inset_iterator_begin();
3336 it != inset_iterator_end(); ++it) {
3337 vector<string> const l = (*it)->getLabelList();
3338 label_list.insert(label_list.end(), l.begin(), l.end());
3344 Buffer::Lists const Buffer::getLists() const
3347 LyXParagraph * par = paragraph;
3349 LyXTextClassList::size_type cap;
3350 boost::tie(found, cap) = textclasslist
3351 .NumberOfLayout(params.textclass, "Caption");
3354 char const labeltype =
3355 textclasslist.Style(params.textclass,
3356 par->GetLayout()).labeltype;
3358 if (labeltype >= LABEL_COUNTER_CHAPTER
3359 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3360 // insert this into the table of contents
3361 SingleList & item = l["TOC"];
3364 textclasslist.TextClass(params.textclass).maxcounter());
3365 item.push_back(TocItem(par, depth, par->String(this, true)));
3367 // For each paragrph, traverse its insets and look for
3371 LyXParagraph::inset_iterator it =
3372 par->inset_iterator_begin();
3373 LyXParagraph::inset_iterator end =
3374 par->inset_iterator_end();
3376 for (; it != end; ++it) {
3377 if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3379 static_cast<InsetFloat*>(*it);
3381 string const type = il->type();
3383 // Now find the caption in the float...
3384 // We now tranverse the paragraphs of
3386 LyXParagraph * tmp = il->inset.par;
3388 if (tmp->layout == cap) {
3389 SingleList & item = l[type];
3391 tostr(item.size()+1) + ". " + tmp->String(this, false);
3392 item.push_back(TocItem(tmp, 0 , str));
3399 lyxerr << "caption not found" << endl;
3408 // This is also a buffer property (ale)
3409 vector<pair<string, string> > const Buffer::getBibkeyList()
3411 /// if this is a child document and the parent is already loaded
3412 /// Use the parent's list instead [ale990412]
3413 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3414 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3416 return tmp->getBibkeyList();
3419 vector<pair<string, string> > keys;
3420 LyXParagraph * par = paragraph;
3423 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3424 par->String(this, false)));
3428 // Might be either using bibtex or a child has bibliography
3430 for (inset_iterator it = inset_iterator_begin();
3431 it != inset_iterator_end(); ++it) {
3432 // Search for Bibtex or Include inset
3433 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3434 vector<pair<string,string> > tmp =
3435 static_cast<InsetBibtex*>(*it)->getKeys(this);
3436 keys.insert(keys.end(), tmp.begin(), tmp.end());
3437 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3438 vector<pair<string,string> > const tmp =
3439 static_cast<InsetInclude*>(*it)->getKeys();
3440 keys.insert(keys.end(), tmp.begin(), tmp.end());
3449 bool Buffer::isDepClean(string const & name) const
3451 DEPCLEAN * item = dep_clean;
3452 while (item && item->master != name)
3454 if (!item) return true;
3459 void Buffer::markDepClean(string const & name)
3462 dep_clean = new DEPCLEAN;
3463 dep_clean->clean = true;
3464 dep_clean->master = name;
3465 dep_clean->next = 0;
3467 DEPCLEAN * item = dep_clean;
3468 while (item && item->master != name)
3473 item = new DEPCLEAN;
3475 item->master = name;
3482 bool Buffer::Dispatch(string const & command)
3484 // Split command string into command and argument
3486 string line = frontStrip(command);
3487 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3489 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3493 bool Buffer::Dispatch(int action, string const & argument)
3495 bool dispatched = true;
3498 Exporter::Export(this, argument, false);
3508 void Buffer::resize()
3510 /// resize the BufferViews!
3516 void Buffer::resizeInsets(BufferView * bv)
3518 /// then remove all LyXText in text-insets
3519 LyXParagraph * par = paragraph;
3520 for (; par; par = par->next()) {
3521 par->resizeInsetsLyXText(bv);
3526 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3529 LyXParagraph * par = paragraph;
3531 par->ChangeLanguage(params, from, to);
3537 bool Buffer::isMultiLingual()
3539 LyXParagraph * par = paragraph;
3541 if (par->isMultiLingual(params))
3549 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3550 LyXParagraph::size_type pos)
3553 it = par->InsetIterator(pos);
3554 if (it == par->inset_iterator_end()) {
3561 void Buffer::inset_iterator::SetParagraph()
3564 it = par->inset_iterator_begin();
3565 if (it != par->inset_iterator_end())
3570 // We maintain an invariant that whenever par = 0 then it = 0