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;
367 bool checkminipage = false;
368 static LyXParagraph * minipar;
369 static LyXParagraph * parBeforeMinipage;
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"
495 } else if (tmptok == "tab") {
496 inset = new InsetFloat("table");
497 old_float << "placement htbp\n"
499 } else if (tmptok == "alg") {
500 inset = new InsetFloat("algorithm");
501 old_float << "placement htbp\n"
503 } else if (tmptok == "wide-fig") {
504 inset = new InsetFloat("figure");
505 //InsetFloat * tmp = new InsetFloat("figure");
508 old_float << "placement htbp\n"
510 } else if (tmptok == "wide-tab") {
511 inset = new InsetFloat("table");
512 //InsetFloat * tmp = new InsetFloat("table");
515 old_float << "placement htbp\n"
521 return false; // no end read yet
524 old_float << "collapsed true\n";
526 // Here we need to check for \end_deeper and handle that
527 // before we do the footnote parsing.
528 // This _is_ a hack! (Lgb)
531 string const tmp = lex.GetString();
532 if (tmp == "\\end_deeper") {
533 //lyxerr << "\\end_deeper caught!" << endl;
535 lex.printError("\\end_deeper: "
536 "depth is already null");
541 old_float << tmp << ' ';
546 old_float << lex.getLongString("\\end_float")
547 << "\n\\end_inset\n";
548 //lyxerr << "Float Body:\n" << old_float.str() << endl;
549 // That this does not work seems like a bug
550 // in stringstream. (Lgb)
551 istringstream istr(old_float.str());
553 nylex.setStream(istr);
554 inset->Read(this, nylex);
555 par->InsertInset(pos, inset, font);
557 } else if (token == "\\begin_deeper") {
559 } else if (token == "\\end_deeper") {
561 lex.printError("\\end_deeper: "
562 "depth is already null");
566 } else if (token == "\\begin_preamble") {
567 params.readPreamble(lex);
568 } else if (token == "\\textclass") {
570 pair<bool, LyXTextClassList::size_type> pp =
571 textclasslist.NumberOfClass(lex.GetString());
573 params.textclass = pp.second;
575 WriteAlert(string(_("Textclass error")),
576 string(_("The document uses an unknown textclass \"")) +
577 lex.GetString() + string("\"."),
578 string(_("LyX will not be able to produce output correctly.")));
579 params.textclass = 0;
581 if (!textclasslist.Load(params.textclass)) {
582 // if the textclass wasn't loaded properly
583 // we need to either substitute another
584 // or stop loading the file.
585 // I can substitute but I don't see how I can
586 // stop loading... ideas?? ARRae980418
587 WriteAlert(_("Textclass Loading Error!"),
588 string(_("Can't load textclass ")) +
589 textclasslist.NameOfClass(params.textclass),
590 _("-- substituting default"));
591 params.textclass = 0;
593 } else if (token == "\\options") {
595 params.options = lex.GetString();
596 } else if (token == "\\language") {
597 params.readLanguage(lex);
598 } else if (token == "\\fontencoding") {
600 } else if (token == "\\inputencoding") {
602 params.inputenc = lex.GetString();
603 } else if (token == "\\graphics") {
604 params.readGraphicsDriver(lex);
605 } else if (token == "\\fontscheme") {
607 params.fonts = lex.GetString();
608 } else if (token == "\\noindent") {
609 par->params.noindent(true);
610 } else if (token == "\\fill_top") {
611 par->params.spaceTop(VSpace(VSpace::VFILL));
612 } else if (token == "\\fill_bottom") {
613 par->params.spaceBottom(VSpace(VSpace::VFILL));
614 } else if (token == "\\line_top") {
615 par->params.lineTop(true);
616 } else if (token == "\\line_bottom") {
617 par->params.lineBottom(true);
618 } else if (token == "\\pagebreak_top") {
619 par->params.pagebreakTop(true);
620 } else if (token == "\\pagebreak_bottom") {
621 par->params.pagebreakBottom(true);
622 } else if (token == "\\start_of_appendix") {
623 par->params.startOfAppendix(true);
624 } else if (token == "\\paragraph_separation") {
625 int tmpret = lex.FindToken(string_paragraph_separation);
626 if (tmpret == -1) ++tmpret;
627 if (tmpret != LYX_LAYOUT_DEFAULT)
628 params.paragraph_separation =
629 static_cast<BufferParams::PARSEP>(tmpret);
630 } else if (token == "\\defskip") {
632 params.defskip = VSpace(lex.GetString());
633 } else if (token == "\\epsfig") { // obsolete
634 // Indeed it is obsolete, but we HAVE to be backwards
635 // compatible until 0.14, because otherwise all figures
636 // in existing documents are irretrivably lost. (Asger)
637 params.readGraphicsDriver(lex);
638 } else if (token == "\\quotes_language") {
639 int tmpret = lex.FindToken(string_quotes_language);
640 if (tmpret == -1) ++tmpret;
641 if (tmpret != LYX_LAYOUT_DEFAULT) {
642 InsetQuotes::quote_language tmpl =
643 InsetQuotes::EnglishQ;
646 tmpl = InsetQuotes::EnglishQ;
649 tmpl = InsetQuotes::SwedishQ;
652 tmpl = InsetQuotes::GermanQ;
655 tmpl = InsetQuotes::PolishQ;
658 tmpl = InsetQuotes::FrenchQ;
661 tmpl = InsetQuotes::DanishQ;
664 params.quotes_language = tmpl;
666 } else if (token == "\\quotes_times") {
668 switch (lex.GetInteger()) {
670 params.quotes_times = InsetQuotes::SingleQ;
673 params.quotes_times = InsetQuotes::DoubleQ;
676 } else if (token == "\\papersize") {
677 int tmpret = lex.FindToken(string_papersize);
681 params.papersize2 = tmpret;
682 } else if (token == "\\paperpackage") {
683 int tmpret = lex.FindToken(string_paperpackages);
686 params.paperpackage = BufferParams::PACKAGE_NONE;
688 params.paperpackage = tmpret;
689 } else if (token == "\\use_geometry") {
691 params.use_geometry = lex.GetInteger();
692 } else if (token == "\\use_amsmath") {
694 params.use_amsmath = lex.GetInteger();
695 } else if (token == "\\paperorientation") {
696 int tmpret = lex.FindToken(string_orientation);
697 if (tmpret == -1) ++tmpret;
698 if (tmpret != LYX_LAYOUT_DEFAULT)
699 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
700 } else if (token == "\\paperwidth") {
702 params.paperwidth = lex.GetString();
703 } else if (token == "\\paperheight") {
705 params.paperheight = lex.GetString();
706 } else if (token == "\\leftmargin") {
708 params.leftmargin = lex.GetString();
709 } else if (token == "\\topmargin") {
711 params.topmargin = lex.GetString();
712 } else if (token == "\\rightmargin") {
714 params.rightmargin = lex.GetString();
715 } else if (token == "\\bottommargin") {
717 params.bottommargin = lex.GetString();
718 } else if (token == "\\headheight") {
720 params.headheight = lex.GetString();
721 } else if (token == "\\headsep") {
723 params.headsep = lex.GetString();
724 } else if (token == "\\footskip") {
726 params.footskip = lex.GetString();
727 } else if (token == "\\paperfontsize") {
729 params.fontsize = strip(lex.GetString());
730 } else if (token == "\\papercolumns") {
732 params.columns = lex.GetInteger();
733 } else if (token == "\\papersides") {
735 switch (lex.GetInteger()) {
737 case 1: params.sides = LyXTextClass::OneSide; break;
738 case 2: params.sides = LyXTextClass::TwoSides; break;
740 } else if (token == "\\paperpagestyle") {
742 params.pagestyle = strip(lex.GetString());
743 } else if (token == "\\bullet") {
745 int const index = lex.GetInteger();
747 int temp_int = lex.GetInteger();
748 params.user_defined_bullets[index].setFont(temp_int);
749 params.temp_bullets[index].setFont(temp_int);
751 temp_int = lex.GetInteger();
752 params.user_defined_bullets[index].setCharacter(temp_int);
753 params.temp_bullets[index].setCharacter(temp_int);
755 temp_int = lex.GetInteger();
756 params.user_defined_bullets[index].setSize(temp_int);
757 params.temp_bullets[index].setSize(temp_int);
759 string const temp_str = lex.GetString();
760 if (temp_str != "\\end_bullet") {
761 // this element isn't really necessary for
762 // parsing but is easier for humans
763 // to understand bullets. Put it back and
764 // set a debug message?
765 lex.printError("\\end_bullet expected, got" + temp_str);
766 //how can I put it back?
768 } else if (token == "\\bulletLaTeX") {
770 int const index = lex.GetInteger();
772 string temp_str = lex.GetString();
774 while (temp_str != "\\end_bullet") {
775 // this loop structure is needed when user
776 // enters an empty string since the first
777 // thing returned will be the \\end_bullet
779 // if the LaTeX entry has spaces. Each element
780 // therefore needs to be read in turn
783 temp_str = lex.GetString();
785 params.user_defined_bullets[index].setText(sum_str);
786 params.temp_bullets[index].setText(sum_str);
787 } else if (token == "\\secnumdepth") {
789 params.secnumdepth = lex.GetInteger();
790 } else if (token == "\\tocdepth") {
792 params.tocdepth = lex.GetInteger();
793 } else if (token == "\\spacing") {
795 string const tmp = strip(lex.GetString());
796 Spacing::Space tmp_space = Spacing::Default;
798 if (tmp == "single") {
799 tmp_space = Spacing::Single;
800 } else if (tmp == "onehalf") {
801 tmp_space = Spacing::Onehalf;
802 } else if (tmp == "double") {
803 tmp_space = Spacing::Double;
804 } else if (tmp == "other") {
806 tmp_space = Spacing::Other;
807 tmp_val = lex.GetFloat();
809 lex.printError("Unknown spacing token: '$$Token'");
811 // Small hack so that files written with klyx will be
814 par->params.spacing(Spacing(tmp_space, tmp_val));
816 params.spacing.set(tmp_space, tmp_val);
818 } else if (token == "\\paragraph_spacing") {
820 string const tmp = strip(lex.GetString());
821 if (tmp == "single") {
822 par->params.spacing(Spacing(Spacing::Single));
823 } else if (tmp == "onehalf") {
824 par->params.spacing(Spacing(Spacing::Onehalf));
825 } else if (tmp == "double") {
826 par->params.spacing(Spacing(Spacing::Double));
827 } else if (tmp == "other") {
829 par->params.spacing(Spacing(Spacing::Other,
832 lex.printError("Unknown spacing token: '$$Token'");
834 } else if (token == "\\float_placement") {
836 params.float_placement = lex.GetString();
837 } else if (token == "\\family") {
839 font.setLyXFamily(lex.GetString());
840 } else if (token == "\\series") {
842 font.setLyXSeries(lex.GetString());
843 } else if (token == "\\shape") {
845 font.setLyXShape(lex.GetString());
846 } else if (token == "\\size") {
848 font.setLyXSize(lex.GetString());
849 } else if (token == "\\latex") {
851 string const tok = lex.GetString();
852 // This is dirty, but gone with LyX3. (Asger)
853 if (tok == "no_latex")
854 font.setLatex(LyXFont::OFF);
855 else if (tok == "latex")
856 font.setLatex(LyXFont::ON);
857 else if (tok == "default")
858 font.setLatex(LyXFont::INHERIT);
860 lex.printError("Unknown LaTeX font flag "
862 } else if (token == "\\lang") {
864 string const tok = lex.GetString();
865 Language const * lang = languages.getLanguage(tok);
867 font.setLanguage(lang);
869 font.setLanguage(params.language);
870 lex.printError("Unknown language `$$Token'");
872 } else if (token == "\\numeric") {
874 font.setNumber(font.setLyXMisc(lex.GetString()));
875 } else if (token == "\\emph") {
877 font.setEmph(font.setLyXMisc(lex.GetString()));
878 } else if (token == "\\bar") {
880 string const tok = lex.GetString();
881 // This is dirty, but gone with LyX3. (Asger)
883 font.setUnderbar(LyXFont::ON);
884 else if (tok == "no")
885 font.setUnderbar(LyXFont::OFF);
886 else if (tok == "default")
887 font.setUnderbar(LyXFont::INHERIT);
889 lex.printError("Unknown bar font flag "
891 } else if (token == "\\noun") {
893 font.setNoun(font.setLyXMisc(lex.GetString()));
894 } else if (token == "\\color") {
896 font.setLyXColor(lex.GetString());
897 } else if (token == "\\align") {
898 int tmpret = lex.FindToken(string_align);
899 if (tmpret == -1) ++tmpret;
900 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
901 int const tmpret2 = int(pow(2.0, tmpret));
902 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
903 par->params.align(LyXAlignment(tmpret2));
905 } else if (token == "\\added_space_top") {
907 par->params.spaceTop(VSpace(lex.GetString()));
908 } else if (token == "\\added_space_bottom") {
910 par->params.spaceBottom(VSpace(lex.GetString()));
911 #ifndef NO_PEXTRA_REALLY
912 } else if (token == "\\pextra_type") {
914 par->params.pextraType(lex.GetInteger());
915 } else if (token == "\\pextra_width") {
917 par->params.pextraWidth(lex.GetString());
918 } else if (token == "\\pextra_widthp") {
920 par->params.pextraWidthp(lex.GetString());
921 } else if (token == "\\pextra_alignment") {
923 par->params.pextraAlignment(lex.GetInteger());
924 } else if (token == "\\pextra_hfill") {
926 par->params.pextraHfill(lex.GetInteger());
927 } else if (token == "\\pextra_start_minipage") {
929 par->params.pextraStartMinipage(lex.GetInteger());
931 } else if (token == "\\labelwidthstring") {
933 par->params.labelWidthString(lex.GetString());
934 // do not delete this token, it is still needed!
935 } else if (token == "\\end_inset") {
936 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
937 << "Last inset read was: " << last_inset_read
939 // Simply ignore this. The insets do not have
941 // But insets should read it, it is a part of
942 // the inset isn't it? Lgb.
943 } else if (token == "\\begin_inset") {
944 readInset(lex, par, pos, font);
945 } else if (token == "\\SpecialChar") {
946 LyXLayout const & layout =
947 textclasslist.Style(params.textclass,
950 // Insets don't make sense in a free-spacing context! ---Kayvan
951 if (layout.free_spacing) {
954 string next_token = lex.GetString();
955 if (next_token == "\\-") {
956 par->InsertChar(pos, '-', font);
957 } else if (next_token == "\\protected_separator"
958 || next_token == "~") {
959 par->InsertChar(pos, ' ', font);
961 lex.printError("Token `$$Token' "
963 "paragraph layout!");
968 Inset * inset = new InsetSpecialChar;
969 inset->Read(this, lex);
970 par->InsertInset(pos, inset, font);
973 } else if (token == "\\newline") {
974 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
976 } else if (token == "\\LyXTable") {
977 Inset * inset = new InsetTabular(*this);
978 inset->Read(this, lex);
979 par->InsertInset(pos, inset, font);
981 // because of OLD_TABULAR_READ where tabulars have been
983 checkminipage = true;
984 } else if (token == "\\hfill") {
985 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
987 } else if (token == "\\protected_separator") { // obsolete
988 // This is a backward compability thingie. (Lgb)
989 // Remove it later some time...introduced with fileformat
991 LyXLayout const & layout =
992 textclasslist.Style(params.textclass,
995 if (layout.free_spacing) {
996 par->InsertChar(pos, ' ', font);
998 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
999 par->InsertInset(pos, inset, font);
1002 } else if (token == "\\bibitem") { // ale970302
1004 InsetCommandParams p("bibitem", "dummy");
1005 par->bibkey = new InsetBibKey(p);
1007 par->bibkey->Read(this, lex);
1008 } else if (token == "\\backslash") {
1009 par->InsertChar(pos, '\\', font);
1011 } else if (token == "\\the_end") {
1012 the_end_read = true;
1013 minipar = parBeforeMinipage = 0;
1015 // This should be insurance for the future: (Asger)
1016 lex.printError("Unknown token `$$Token'. "
1017 "Inserting as text.");
1018 string::const_iterator cit = token.begin();
1019 string::const_iterator end = token.end();
1020 for (; cit != end; ++cit) {
1021 par->InsertChar(pos, (*cit), font);
1025 #ifndef NO_PEXTRA_REALLY
1026 // now check if we have a minipage paragraph as at this
1027 // point we already read all the necessary data!
1028 // this cannot be done in layout because there we did
1029 // not read yet the paragraph PEXTRA-params (Jug)
1031 // BEGIN pextra_minipage compability
1032 // This should be removed in 1.3.x (Lgb)
1034 // This compability code is not perfect. In a couple
1035 // of rand cases it fails. When the minipage par is
1036 // the first par in the document, and when there are
1037 // none or only one regular paragraphs after the
1038 // minipage. Currently I am not investing any effort
1039 // in fixing those cases.
1041 //lyxerr << "Call depth: " << call_depth << endl;
1042 if (checkminipage && (call_depth == 1)) {
1043 checkminipage = false;
1044 if (minipar && (minipar != par) &&
1045 (par->params.pextraType()==LyXParagraph::PEXTRA_MINIPAGE))
1047 lyxerr << "minipages in a row" << endl;
1048 if (par->params.pextraStartMinipage()) {
1049 lyxerr << "start new minipage" << endl;
1050 // minipages in a row
1051 par->previous()->next(0);
1054 LyXParagraph * tmp = minipar;
1056 tmp->params.pextraType(0);
1057 tmp->params.pextraWidth(string());
1058 tmp->params.pextraWidthp(string());
1059 tmp->params.pextraAlignment(0);
1060 tmp->params.pextraHfill(false);
1061 tmp->params.pextraStartMinipage(false);
1064 // create a new paragraph to insert the
1065 // minipages in the following case
1066 if (par->params.pextraStartMinipage() &&
1067 !par->params.pextraHfill())
1069 LyXParagraph * p = new LyXParagraph;
1071 p->previous(parBeforeMinipage);
1072 parBeforeMinipage->next(p);
1074 p->params.depth(parBeforeMinipage->params.depth());
1075 parBeforeMinipage = p;
1077 InsetMinipage * mini = new InsetMinipage;
1078 mini->pos(static_cast<InsetMinipage::Position>(par->params.pextraAlignment()));
1079 mini->width(par->params.pextraWidth());
1080 if (!par->params.pextraWidthp().empty()) {
1081 lyxerr << "WP:" << mini->width() << endl;
1082 mini->width(tostr(par->params.pextraWidthp())+"%");
1084 mini->inset.par = par;
1085 // Insert the minipage last in the
1086 // previous paragraph.
1087 if (par->params.pextraHfill()) {
1088 parBeforeMinipage->InsertChar
1089 (parBeforeMinipage->size(), LyXParagraph::META_HFILL);
1091 parBeforeMinipage->InsertInset
1092 (parBeforeMinipage->size(), mini);
1096 lyxerr << "new minipage par" << endl;
1097 //nothing to do just continue reading
1100 } else if (minipar && (minipar != par)) {
1101 lyxerr << "last minipage par read" << endl;
1102 // The last paragraph read was not part of a
1103 // minipage but the par linked list is...
1104 // So we need to remove the last par from the
1106 if (par->previous())
1107 par->previous()->next(0);
1108 par->previous(parBeforeMinipage);
1109 parBeforeMinipage->next(par);
1110 LyXParagraph * tmp = minipar;
1112 tmp->params.pextraType(0);
1113 tmp->params.pextraWidth(string());
1114 tmp->params.pextraWidthp(string());
1115 tmp->params.pextraAlignment(0);
1116 tmp->params.pextraHfill(false);
1117 tmp->params.pextraStartMinipage(false);
1120 depth = parBeforeMinipage->params.depth();
1121 minipar = parBeforeMinipage = 0;
1122 } else if (!minipar &&
1123 (par->params.pextraType() == LyXParagraph::PEXTRA_MINIPAGE))
1125 // par is the first paragraph in a minipage
1126 lyxerr << "begin minipage" << endl;
1127 // To minimize problems for
1128 // the users we will insert
1129 // the first minipage in
1130 // a sequence of minipages
1131 // in its own paragraph.
1132 LyXParagraph * p = new LyXParagraph;
1134 p->previous(par->previous());
1136 p->params.depth(depth);
1137 par->params.depth(0);
1139 if (par->previous())
1140 par->previous()->next(p);
1142 parBeforeMinipage = p;
1144 if (!return_par || (return_par == par))
1147 InsetMinipage * mini = new InsetMinipage;
1148 mini->pos(static_cast<InsetMinipage::Position>(minipar->params.pextraAlignment()));
1149 mini->width(minipar->params.pextraWidth());
1150 if (!par->params.pextraWidthp().empty()) {
1151 lyxerr << "WP:" << mini->width() << endl;
1152 mini->width(tostr(par->params.pextraWidthp())+"%");
1154 mini->inset.par = minipar;
1156 // Insert the minipage last in the
1157 // previous paragraph.
1158 if (minipar->params.pextraHfill()) {
1159 parBeforeMinipage->InsertChar
1160 (parBeforeMinipage->size(),LyXParagraph::META_HFILL);
1162 parBeforeMinipage->InsertInset
1163 (parBeforeMinipage->size(), mini);
1166 // End of pextra_minipage compability
1169 return the_end_read;
1173 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1174 int & pos, LyXFont & font)
1176 // consistency check
1177 if (lex.GetString() != "\\begin_inset") {
1178 lyxerr << "Buffer::readInset: Consistency check failed."
1185 string const tmptok = lex.GetString();
1186 last_inset_read = tmptok;
1188 // test the different insets
1189 if (tmptok == "LatexCommand") {
1190 InsetCommandParams inscmd;
1193 string const cmdName = inscmd.getCmdName();
1195 if (cmdName == "cite") {
1196 inset = new InsetCitation(inscmd);
1197 } else if (cmdName == "bibitem") {
1198 lex.printError("Wrong place for bibitem");
1199 inset = new InsetBibKey(inscmd);
1200 } else if (cmdName == "BibTeX") {
1201 inset = new InsetBibtex(inscmd);
1202 } else if (cmdName == "index") {
1203 inset = new InsetIndex(inscmd);
1204 } else if (cmdName == "include") {
1205 inset = new InsetInclude(inscmd, *this);
1206 } else if (cmdName == "label") {
1207 inset = new InsetLabel(inscmd);
1208 } else if (cmdName == "url"
1209 || cmdName == "htmlurl") {
1210 inset = new InsetUrl(inscmd);
1211 } else if (cmdName == "ref"
1212 || cmdName == "pageref"
1213 || cmdName == "vref"
1214 || cmdName == "vpageref"
1215 || cmdName == "prettyref") {
1216 if (!inscmd.getOptions().empty()
1217 || !inscmd.getContents().empty()) {
1218 inset = new InsetRef(inscmd, *this);
1220 } else if (cmdName == "tableofcontents") {
1221 inset = new InsetTOC(inscmd);
1222 } else if (cmdName == "listofalgorithms") {
1223 inset = new InsetFloatList("algorithm");
1224 } else if (cmdName == "listoffigures") {
1225 inset = new InsetFloatList("figure");
1226 } else if (cmdName == "listoftables") {
1227 inset = new InsetFloatList("table");
1228 } else if (cmdName == "printindex") {
1229 inset = new InsetPrintIndex(inscmd);
1230 } else if (cmdName == "lyxparent") {
1231 inset = new InsetParent(inscmd, *this);
1234 if (tmptok == "Quotes") {
1235 inset = new InsetQuotes;
1236 } else if (tmptok == "External") {
1237 inset = new InsetExternal;
1238 } else if (tmptok == "FormulaMacro") {
1239 inset = new InsetFormulaMacro;
1240 } else if (tmptok == "Formula") {
1241 inset = new InsetFormula;
1242 } else if (tmptok == "Figure") {
1243 inset = new InsetFig(100, 100, *this);
1244 } else if (tmptok == "Info") {
1245 inset = new InsetInfo;
1246 } else if (tmptok == "Include") {
1247 InsetCommandParams p( "Include" );
1248 inset = new InsetInclude(p, *this);
1249 } else if (tmptok == "ERT") {
1250 inset = new InsetERT;
1251 } else if (tmptok == "Tabular") {
1252 inset = new InsetTabular(*this);
1253 } else if (tmptok == "Text") {
1254 inset = new InsetText;
1255 } else if (tmptok == "Foot") {
1256 inset = new InsetFoot;
1257 } else if (tmptok == "Marginal") {
1258 inset = new InsetMarginal;
1259 } else if (tmptok == "Minipage") {
1260 inset = new InsetMinipage;
1261 } else if (tmptok == "Float") {
1263 string tmptok = lex.GetString();
1264 inset = new InsetFloat(tmptok);
1265 } else if (tmptok == "List") {
1266 inset = new InsetList;
1267 } else if (tmptok == "Theorem") {
1268 inset = new InsetList;
1269 } else if (tmptok == "Caption") {
1270 inset = new InsetCaption;
1271 } else if (tmptok == "GRAPHICS") {
1272 inset = new InsetGraphics;
1273 } else if (tmptok == "FloatList") {
1274 inset = new InsetFloatList;
1277 if (inset) inset->Read(this, lex);
1281 par->InsertInset(pos, inset, font);
1287 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1291 string const token(lex.GetString());
1292 if (token == "\\lyxformat") { // the first token _must_ be...
1294 string tmp_format = lex.GetString();
1295 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1296 // if present remove ".," from string.
1297 string::size_type dot = tmp_format.find_first_of(".,");
1298 //lyxerr << " dot found at " << dot << endl;
1299 if (dot != string::npos)
1300 tmp_format.erase(dot, 1);
1301 file_format = strToInt(tmp_format);
1302 if (file_format == LYX_FORMAT) {
1304 } else if (file_format > LYX_FORMAT) {
1306 WriteAlert(_("Warning!"),
1307 _("LyX file format is newer that what"),
1308 _("is supported in this LyX version. Expect some problems."));
1310 } else if (file_format < LYX_FORMAT) {
1312 if (file_format < 200) {
1313 WriteAlert(_("ERROR!"),
1314 _("Old LyX file format found. "
1315 "Use LyX 0.10.x to read this!"));
1319 bool the_end = readLyXformat2(lex, par);
1321 // the_end was added in 213
1322 if (file_format < 213)
1326 WriteAlert(_("Warning!"),
1327 _("Reading of document is not complete"),
1328 _("Maybe the document is truncated"));
1330 } else { // "\\lyxformat" not found
1331 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1334 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1340 // Should probably be moved to somewhere else: BufferView? LyXView?
1341 bool Buffer::save() const
1343 // We don't need autosaves in the immediate future. (Asger)
1344 resetAutosaveTimers();
1348 if (lyxrc.make_backup) {
1349 s = fileName() + '~';
1350 if (!lyxrc.backupdir_path.empty())
1351 s = AddName(lyxrc.backupdir_path,
1352 subst(os::slashify_path(s),'/','!'));
1354 // Rename is the wrong way of making a backup,
1355 // this is the correct way.
1356 /* truss cp fil fil2:
1357 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1358 stat("LyXVC.lyx", 0xEFFFF688) = 0
1359 open("LyXVC.lyx", O_RDONLY) = 3
1360 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1361 fstat(4, 0xEFFFF508) = 0
1362 fstat(3, 0xEFFFF508) = 0
1363 read(3, " # T h i s f i l e w".., 8192) = 5579
1364 write(4, " # T h i s f i l e w".., 5579) = 5579
1365 read(3, 0xEFFFD4A0, 8192) = 0
1368 chmod("LyXVC3.lyx", 0100644) = 0
1369 lseek(0, 0, SEEK_CUR) = 46440
1373 // Should proabaly have some more error checking here.
1374 // Should be cleaned up in 0.13, at least a bit.
1375 // Doing it this way, also makes the inodes stay the same.
1376 // This is still not a very good solution, in particular we
1377 // might loose the owner of the backup.
1378 FileInfo finfo(fileName());
1379 if (finfo.exist()) {
1380 mode_t fmode = finfo.getMode();
1381 struct utimbuf times = {
1382 finfo.getAccessTime(),
1383 finfo.getModificationTime() };
1385 ifstream ifs(fileName().c_str());
1386 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1391 ::chmod(s.c_str(), fmode);
1393 if (::utime(s.c_str(), ×)) {
1394 lyxerr << "utime error." << endl;
1397 lyxerr << "LyX was not able to make "
1398 "backupcopy. Beware." << endl;
1403 if (writeFile(fileName(), false)) {
1405 removeAutosaveFile(fileName());
1407 // Saving failed, so backup is not backup
1408 if (lyxrc.make_backup) {
1409 lyx::rename(s, fileName());
1417 // Returns false if unsuccesful
1418 bool Buffer::writeFile(string const & fname, bool flag) const
1420 // if flag is false writeFile will not create any GUI
1421 // warnings, only cerr.
1422 // Needed for autosave in background or panic save (Matthias 120496)
1424 if (read_only && (fname == filename)) {
1425 // Here we should come with a question if we should
1426 // perform the write anyway.
1428 lyxerr << _("Error! Document is read-only: ")
1431 WriteAlert(_("Error! Document is read-only: "),
1436 FileInfo finfo(fname);
1437 if (finfo.exist() && !finfo.writable()) {
1438 // Here we should come with a question if we should
1439 // try to do the save anyway. (i.e. do a chmod first)
1441 lyxerr << _("Error! Cannot write file: ")
1444 WriteFSAlert(_("Error! Cannot write file: "),
1449 ofstream ofs(fname.c_str());
1452 lyxerr << _("Error! Cannot open file: ")
1455 WriteFSAlert(_("Error! Cannot open file: "),
1461 // Use the standard "C" locale for file output.
1462 ofs.imbue(std::locale::classic());
1465 // The top of the file should not be written by params.
1467 // write out a comment in the top of the file
1468 ofs << '#' << LYX_DOCVERSION
1469 << " created this file. For more info see http://www.lyx.org/\n"
1470 << "\\lyxformat " << LYX_FORMAT << "\n";
1472 // now write out the buffer paramters.
1473 params.writeFile(ofs);
1477 // this will write out all the paragraphs
1478 // using recursive descent.
1479 paragraph->writeFile(this, ofs, params, depth);
1481 // Write marker that shows file is complete
1482 ofs << "\n\\the_end" << endl;
1486 // how to check if close went ok?
1487 // Following is an attempt... (BE 20001011)
1489 // good() returns false if any error occured, including some
1490 // formatting error.
1491 // bad() returns true if something bad happened in the buffer,
1492 // which should include file system full errors.
1499 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1501 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1511 string const Buffer::asciiParagraph(LyXParagraph const * par,
1512 unsigned int linelen) const
1514 ostringstream buffer;
1517 int ltype_depth = 0;
1518 unsigned int currlinelen = 0;
1519 bool ref_printed = false;
1523 if (!par->previous()) {
1524 // begins or ends a deeper area ?
1525 if (depth != par->params.depth()) {
1526 if (par->params.depth() > depth) {
1527 while (par->params.depth() > depth) {
1531 while (par->params.depth() < depth) {
1537 // First write the layout
1538 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1539 if (tmp == "Itemize") {
1541 ltype_depth = depth + 1;
1542 } else if (tmp == "Enumerate") {
1544 ltype_depth = depth + 1;
1545 } else if (contains(tmp, "ection")) {
1547 ltype_depth = depth + 1;
1548 } else if (contains(tmp, "aragraph")) {
1550 ltype_depth = depth + 1;
1551 } else if (tmp == "Description") {
1553 ltype_depth = depth + 1;
1554 } else if (tmp == "Abstract") {
1557 } else if (tmp == "Bibliography") {
1565 /* maybe some vertical spaces */
1567 /* the labelwidthstring used in lists */
1571 /* some pagebreaks? */
1575 /* what about the alignment */
1577 lyxerr << "Should this ever happen?" << endl;
1580 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1581 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1582 if (!i && !noparbreak) {
1585 for (char j = 0; j < depth; ++j)
1587 currlinelen = depth * 2;
1590 case 4: // (Sub)Paragraph
1591 case 5: // Description
1595 buffer << "Abstract\n\n";
1597 buffer << "Abstract: ";
1599 case 7: // Bibliography
1602 buffer << "References\n\n";
1604 buffer << "References: ";
1609 buffer << par->params.labelString() << " ";
1612 if (ltype_depth > depth) {
1613 for (char j = ltype_depth - 1; j > depth; --j)
1615 currlinelen += (ltype_depth-depth)*2;
1618 LyXFont const font2 = par->GetFontSettings(params, i);
1619 if (font1.latex() != font2.latex()) {
1620 if (font2.latex() == LyXFont::OFF)
1628 char c = par->GetUChar(params, i);
1632 case LyXParagraph::META_INSET:
1634 Inset const * inset = par->GetInset(i);
1636 if (!inset->Ascii(this, buffer)) {
1639 rsplit(buffer.str().c_str(),
1641 currlinelen += s.length();
1643 // to be sure it breaks paragraph
1644 currlinelen += linelen;
1650 case LyXParagraph::META_NEWLINE:
1653 for (char j = 0; j < depth; ++j)
1656 currlinelen = depth * 2;
1657 if (ltype_depth > depth) {
1658 for (char j = ltype_depth;
1661 currlinelen += (ltype_depth - depth) * 2;
1665 case LyXParagraph::META_HFILL:
1674 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1675 (c == ' ') && ((i + 2) < par->size()))
1678 for (char j = 0; j < depth; ++j)
1680 currlinelen = depth * 2;
1681 if (ltype_depth > depth) {
1682 for (char j = ltype_depth;
1685 currlinelen += (ltype_depth-depth)*2;
1687 } else if (c != '\0')
1690 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1695 return buffer.str().c_str();
1699 void Buffer::writeFileAscii(string const & fname, int linelen)
1701 ofstream ofs(fname.c_str());
1703 WriteFSAlert(_("Error: Cannot write file:"), fname);
1706 writeFileAscii(ofs, linelen);
1710 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1712 LyXParagraph * par = paragraph;
1714 ofs << asciiParagraph(par, linelen);
1722 void Buffer::makeLaTeXFile(string const & fname,
1723 string const & original_path,
1724 bool nice, bool only_body)
1726 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1728 niceFile = nice; // this will be used by Insetincludes.
1730 tex_code_break_column = lyxrc.ascii_linelen;
1732 LyXTextClass const & tclass =
1733 textclasslist.TextClass(params.textclass);
1735 ofstream ofs(fname.c_str());
1737 WriteFSAlert(_("Error: Cannot open file: "), fname);
1741 // validate the buffer.
1742 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1743 LaTeXFeatures features(params, tclass.numLayouts());
1745 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1748 // The starting paragraph of the coming rows is the
1749 // first paragraph of the document. (Asger)
1750 texrow.start(paragraph, 0);
1752 if (!only_body && nice) {
1753 ofs << "%% " LYX_DOCVERSION " created this file. "
1754 "For more info, see http://www.lyx.org/.\n"
1755 "%% Do not edit unless you really know what "
1760 lyxerr.debug() << "lyx header finished" << endl;
1761 // There are a few differences between nice LaTeX and usual files:
1762 // usual is \batchmode and has a
1763 // special input@path to allow the including of figures
1764 // with either \input or \includegraphics (what figinsets do).
1765 // batchmode is not set if there is a tex_code_break_column.
1766 // In this case somebody is interested in the generated LaTeX,
1767 // so this is OK. input@path is set when the actual parameter
1768 // original_path is set. This is done for usual tex-file, but not
1769 // for nice-latex-file. (Matthias 250696)
1772 // code for usual, NOT nice-latex-file
1773 ofs << "\\batchmode\n"; // changed
1774 // from \nonstopmode
1777 if (!original_path.empty()) {
1778 ofs << "\\makeatletter\n"
1779 << "\\def\\input@path{{"
1780 << os::external_path(original_path) << "/}}\n"
1781 << "\\makeatother\n";
1787 ofs << "\\documentclass";
1789 ostringstream options; // the document class options.
1791 if (tokenPos(tclass.opt_fontsize(),
1792 '|', params.fontsize) >= 0) {
1793 // only write if existing in list (and not default)
1794 options << params.fontsize << "pt,";
1798 if (!params.use_geometry &&
1799 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1800 switch (params.papersize) {
1801 case BufferParams::PAPER_A4PAPER:
1802 options << "a4paper,";
1804 case BufferParams::PAPER_USLETTER:
1805 options << "letterpaper,";
1807 case BufferParams::PAPER_A5PAPER:
1808 options << "a5paper,";
1810 case BufferParams::PAPER_B5PAPER:
1811 options << "b5paper,";
1813 case BufferParams::PAPER_EXECUTIVEPAPER:
1814 options << "executivepaper,";
1816 case BufferParams::PAPER_LEGALPAPER:
1817 options << "legalpaper,";
1823 if (params.sides != tclass.sides()) {
1824 switch (params.sides) {
1825 case LyXTextClass::OneSide:
1826 options << "oneside,";
1828 case LyXTextClass::TwoSides:
1829 options << "twoside,";
1835 if (params.columns != tclass.columns()) {
1836 if (params.columns == 2)
1837 options << "twocolumn,";
1839 options << "onecolumn,";
1842 if (!params.use_geometry
1843 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1844 options << "landscape,";
1846 // language should be a parameter to \documentclass
1848 ostringstream language_options;
1849 if (params.language->babel() == "hebrew"
1850 && default_language->babel() != "hebrew")
1851 // This seems necessary
1852 features.UsedLanguages.insert(default_language);
1854 if (lyxrc.language_use_babel ||
1855 params.language->lang() != lyxrc.default_language ||
1856 !features.UsedLanguages.empty()) {
1858 for (LaTeXFeatures::LanguageList::const_iterator cit =
1859 features.UsedLanguages.begin();
1860 cit != features.UsedLanguages.end(); ++cit)
1861 language_options << (*cit)->babel() << ',';
1862 language_options << params.language->babel();
1863 if (lyxrc.language_global_options)
1864 options << language_options.str() << ',';
1867 // the user-defined options
1868 if (!params.options.empty()) {
1869 options << params.options << ',';
1872 string strOptions(options.str().c_str());
1873 if (!strOptions.empty()){
1874 strOptions = strip(strOptions, ',');
1875 ofs << '[' << strOptions << ']';
1879 << textclasslist.LatexnameOfClass(params.textclass)
1882 // end of \documentclass defs
1884 // font selection must be done before loading fontenc.sty
1885 // The ae package is not needed when using OT1 font encoding.
1886 if (params.fonts != "default" &&
1887 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1888 ofs << "\\usepackage{" << params.fonts << "}\n";
1890 if (params.fonts == "ae") {
1891 ofs << "\\usepackage{aecompl}\n";
1895 // this one is not per buffer
1896 if (lyxrc.fontenc != "default") {
1897 ofs << "\\usepackage[" << lyxrc.fontenc
1902 if (params.inputenc == "auto") {
1903 string const doc_encoding =
1904 params.language->encoding()->LatexName();
1906 // Create a list with all the input encodings used
1908 set<string> encodings;
1909 for (LaTeXFeatures::LanguageList::const_iterator it =
1910 features.UsedLanguages.begin();
1911 it != features.UsedLanguages.end(); ++it)
1912 if ((*it)->encoding()->LatexName() != doc_encoding)
1913 encodings.insert((*it)->encoding()->LatexName());
1915 ofs << "\\usepackage[";
1916 std::copy(encodings.begin(), encodings.end(),
1917 std::ostream_iterator<string>(ofs, ","));
1918 ofs << doc_encoding << "]{inputenc}\n";
1920 } else if (params.inputenc != "default") {
1921 ofs << "\\usepackage[" << params.inputenc
1926 // At the very beginning the text parameters.
1927 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1928 switch (params.paperpackage) {
1929 case BufferParams::PACKAGE_A4:
1930 ofs << "\\usepackage{a4}\n";
1933 case BufferParams::PACKAGE_A4WIDE:
1934 ofs << "\\usepackage{a4wide}\n";
1937 case BufferParams::PACKAGE_WIDEMARGINSA4:
1938 ofs << "\\usepackage[widemargins]{a4}\n";
1943 if (params.use_geometry) {
1944 ofs << "\\usepackage{geometry}\n";
1946 ofs << "\\geometry{verbose";
1947 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1948 ofs << ",landscape";
1949 switch (params.papersize2) {
1950 case BufferParams::VM_PAPER_CUSTOM:
1951 if (!params.paperwidth.empty())
1952 ofs << ",paperwidth="
1953 << params.paperwidth;
1954 if (!params.paperheight.empty())
1955 ofs << ",paperheight="
1956 << params.paperheight;
1958 case BufferParams::VM_PAPER_USLETTER:
1959 ofs << ",letterpaper";
1961 case BufferParams::VM_PAPER_USLEGAL:
1962 ofs << ",legalpaper";
1964 case BufferParams::VM_PAPER_USEXECUTIVE:
1965 ofs << ",executivepaper";
1967 case BufferParams::VM_PAPER_A3:
1970 case BufferParams::VM_PAPER_A4:
1973 case BufferParams::VM_PAPER_A5:
1976 case BufferParams::VM_PAPER_B3:
1979 case BufferParams::VM_PAPER_B4:
1982 case BufferParams::VM_PAPER_B5:
1986 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1987 switch (lyxrc.default_papersize) {
1988 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1989 case BufferParams::PAPER_USLETTER:
1990 ofs << ",letterpaper";
1992 case BufferParams::PAPER_LEGALPAPER:
1993 ofs << ",legalpaper";
1995 case BufferParams::PAPER_EXECUTIVEPAPER:
1996 ofs << ",executivepaper";
1998 case BufferParams::PAPER_A3PAPER:
2001 case BufferParams::PAPER_A4PAPER:
2004 case BufferParams::PAPER_A5PAPER:
2007 case BufferParams::PAPER_B5PAPER:
2012 if (!params.topmargin.empty())
2013 ofs << ",tmargin=" << params.topmargin;
2014 if (!params.bottommargin.empty())
2015 ofs << ",bmargin=" << params.bottommargin;
2016 if (!params.leftmargin.empty())
2017 ofs << ",lmargin=" << params.leftmargin;
2018 if (!params.rightmargin.empty())
2019 ofs << ",rmargin=" << params.rightmargin;
2020 if (!params.headheight.empty())
2021 ofs << ",headheight=" << params.headheight;
2022 if (!params.headsep.empty())
2023 ofs << ",headsep=" << params.headsep;
2024 if (!params.footskip.empty())
2025 ofs << ",footskip=" << params.footskip;
2029 if (features.amsstyle
2030 && !tclass.provides(LyXTextClass::amsmath)) {
2031 ofs << "\\usepackage{amsmath}\n";
2035 if (tokenPos(tclass.opt_pagestyle(),
2036 '|', params.pagestyle) >= 0) {
2037 if (params.pagestyle == "fancy") {
2038 ofs << "\\usepackage{fancyhdr}\n";
2041 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2045 // We try to load babel late, in case it interferes
2046 // with other packages.
2048 string tmp = lyxrc.language_package;
2049 if (!lyxrc.language_global_options
2050 && tmp == "\\usepackage{babel}")
2051 tmp = string("\\usepackage[") +
2052 language_options.str().c_str() +
2058 if (params.secnumdepth != tclass.secnumdepth()) {
2059 ofs << "\\setcounter{secnumdepth}{"
2060 << params.secnumdepth
2064 if (params.tocdepth != tclass.tocdepth()) {
2065 ofs << "\\setcounter{tocdepth}{"
2071 if (params.paragraph_separation) {
2072 switch (params.defskip.kind()) {
2073 case VSpace::SMALLSKIP:
2074 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2076 case VSpace::MEDSKIP:
2077 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2079 case VSpace::BIGSKIP:
2080 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2082 case VSpace::LENGTH:
2083 ofs << "\\setlength\\parskip{"
2084 << params.defskip.length().asLatexString()
2087 default: // should never happen // Then delete it.
2088 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2093 ofs << "\\setlength\\parindent{0pt}\n";
2097 // Now insert the LyX specific LaTeX commands...
2099 // The optional packages;
2100 string preamble(features.getPackages());
2102 // this might be useful...
2103 preamble += "\n\\makeatletter\n";
2105 // Some macros LyX will need
2106 string tmppreamble(features.getMacros());
2108 if (!tmppreamble.empty()) {
2109 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2110 "LyX specific LaTeX commands.\n"
2111 + tmppreamble + '\n';
2114 // the text class specific preamble
2115 tmppreamble = features.getTClassPreamble();
2116 if (!tmppreamble.empty()) {
2117 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2118 "Textclass specific LaTeX commands.\n"
2119 + tmppreamble + '\n';
2122 /* the user-defined preamble */
2123 if (!params.preamble.empty()) {
2124 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2125 "User specified LaTeX commands.\n"
2126 + params.preamble + '\n';
2129 preamble += "\\makeatother\n";
2131 // Itemize bullet settings need to be last in case the user
2132 // defines their own bullets that use a package included
2133 // in the user-defined preamble -- ARRae
2134 // Actually it has to be done much later than that
2135 // since some packages like frenchb make modifications
2136 // at \begin{document} time -- JMarc
2138 for (int i = 0; i < 4; ++i) {
2139 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2140 if (bullets_def.empty())
2141 bullets_def="\\AtBeginDocument{\n";
2142 bullets_def += " \\renewcommand{\\labelitemi";
2144 // `i' is one less than the item to modify
2151 bullets_def += "ii";
2157 bullets_def += "}{" +
2158 params.user_defined_bullets[i].getText()
2163 if (!bullets_def.empty())
2164 preamble += bullets_def + "}\n\n";
2166 for (int j = countChar(preamble, '\n'); j-- ;) {
2173 ofs << "\\begin{document}\n";
2176 lyxerr.debug() << "preamble finished, now the body." << endl;
2178 if (!lyxrc.language_auto_begin) {
2179 ofs << subst(lyxrc.language_command_begin, "$$lang",
2180 params.language->babel())
2185 latexParagraphs(ofs, paragraph, 0, texrow);
2187 // add this just in case after all the paragraphs
2191 if (!lyxrc.language_auto_end) {
2192 ofs << subst(lyxrc.language_command_end, "$$lang",
2193 params.language->babel())
2199 ofs << "\\end{document}\n";
2202 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2204 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2208 // Just to be sure. (Asger)
2211 // tex_code_break_column's value is used to decide
2212 // if we are in batchmode or not (within mathed_write()
2213 // in math_write.C) so we must set it to a non-zero
2214 // value when we leave otherwise we save incorrect .lyx files.
2215 tex_code_break_column = lyxrc.ascii_linelen;
2219 lyxerr << "File was not closed properly." << endl;
2222 lyxerr.debug() << "Finished making latex file." << endl;
2227 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2229 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2230 LyXParagraph * endpar, TexRow & texrow) const
2232 bool was_title = false;
2233 bool already_title = false;
2236 while (par != endpar) {
2237 LyXLayout const & layout =
2238 textclasslist.Style(params.textclass,
2241 if (layout.intitle) {
2242 if (already_title) {
2243 lyxerr <<"Error in latexParagraphs: You"
2244 " should not mix title layouts"
2245 " with normal ones." << endl;
2248 } else if (was_title && !already_title) {
2249 ofs << "\\maketitle\n";
2251 already_title = true;
2255 if (layout.isEnvironment()) {
2256 par = par->TeXEnvironment(this, params, ofs, texrow);
2258 par = par->TeXOnePar(this, params, ofs, texrow, false);
2261 // It might be that we only have a title in this document
2262 if (was_title && !already_title) {
2263 ofs << "\\maketitle\n";
2269 bool Buffer::isLatex() const
2271 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2275 bool Buffer::isLinuxDoc() const
2277 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2281 bool Buffer::isLiterate() const
2283 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2287 bool Buffer::isDocBook() const
2289 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2293 bool Buffer::isSGML() const
2295 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2296 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2300 void Buffer::sgmlOpenTag(ostream & os, int depth,
2301 string const & latexname) const
2303 if (!latexname.empty() && latexname != "!-- --")
2304 os << string(depth, ' ') << "<" << latexname << ">\n";
2308 void Buffer::sgmlCloseTag(ostream & os, int depth,
2309 string const & latexname) const
2311 if (!latexname.empty() && latexname != "!-- --")
2312 os << string(depth, ' ') << "</" << latexname << ">\n";
2316 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2318 ofstream ofs(fname.c_str());
2321 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2325 niceFile = nice; // this will be used by included files.
2327 LyXTextClass const & tclass =
2328 textclasslist.TextClass(params.textclass);
2330 LaTeXFeatures features(params, tclass.numLayouts());
2335 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2338 string sgml_includedfiles=features.getIncludedFiles(fname);
2340 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2341 ofs << "<!doctype linuxdoc system>\n\n";
2343 ofs << "<!doctype linuxdoc system [ "
2344 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2347 if (params.options.empty())
2348 sgmlOpenTag(ofs, 0, top_element);
2350 string top = top_element;
2352 top += params.options;
2353 sgmlOpenTag(ofs, 0, top);
2357 ofs << "<!-- " << LYX_DOCVERSION
2358 << " created this file. For more info see http://www.lyx.org/"
2361 int depth = 0; // paragraph depth
2362 LyXParagraph * par = paragraph;
2364 vector<string> environment_stack(5);
2367 LyXLayout const & style =
2368 textclasslist.Style(params.textclass,
2371 // treat <toc> as a special case for compatibility with old code
2372 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2373 Inset * inset = par->GetInset(0);
2374 Inset::Code lyx_code = inset->LyxCode();
2375 if (lyx_code == Inset::TOC_CODE){
2376 string const temp = "toc";
2377 sgmlOpenTag(ofs, depth, temp);
2384 // environment tag closing
2385 for (; depth > par->params.depth(); --depth) {
2386 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2387 environment_stack[depth].erase();
2390 // write opening SGML tags
2391 switch (style.latextype) {
2392 case LATEX_PARAGRAPH:
2393 if (depth == par->params.depth()
2394 && !environment_stack[depth].empty()) {
2395 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2396 environment_stack[depth].erase();
2402 sgmlOpenTag(ofs, depth, style.latexname());
2407 LinuxDocError(par, 0,
2408 _("Error : Wrong depth for"
2409 " LatexType Command.\n"));
2411 if (!environment_stack[depth].empty()){
2412 sgmlCloseTag(ofs, depth,
2413 environment_stack[depth]);
2417 environment_stack[depth].erase();
2418 sgmlOpenTag(ofs, depth, style.latexname());
2421 case LATEX_ENVIRONMENT:
2422 case LATEX_ITEM_ENVIRONMENT:
2423 if (depth == par->params.depth()
2424 && environment_stack[depth] != style.latexname()) {
2425 sgmlCloseTag(ofs, depth,
2426 environment_stack[depth]);
2427 environment_stack[depth].erase();
2429 if (depth < par->params.depth()) {
2430 depth = par->params.depth();
2431 environment_stack[depth].erase();
2433 if (environment_stack[depth] != style.latexname()) {
2435 sgmlOpenTag(ofs, depth, "p");
2437 sgmlOpenTag(ofs, depth, style.latexname());
2439 if (environment_stack.size() == depth + 1)
2440 environment_stack.push_back("!-- --");
2441 environment_stack[depth] = style.latexname();
2444 if (style.latexparam() == "CDATA")
2447 if (style.latextype == LATEX_ENVIRONMENT) break;
2449 if (style.labeltype == LABEL_MANUAL)
2454 sgmlOpenTag(ofs, depth + 1, item_name);
2457 sgmlOpenTag(ofs, depth, style.latexname());
2461 SimpleLinuxDocOnePar(ofs, par, depth);
2466 // write closing SGML tags
2467 switch (style.latextype) {
2470 case LATEX_ENVIRONMENT:
2471 case LATEX_ITEM_ENVIRONMENT:
2472 if (style.latexparam() == "CDATA")
2476 sgmlCloseTag(ofs, depth, style.latexname());
2482 for (int i=depth; i >= 0; --i)
2483 sgmlCloseTag(ofs, depth, environment_stack[i]);
2487 sgmlCloseTag(ofs, 0, top_element);
2491 // How to check for successful close
2495 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2496 int depth, int desc_on,
2497 LyXParagraph * & par)
2499 LyXParagraph * tpar = par;
2501 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2503 tpar = tpar->next();
2506 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2507 "Caption").second) {
2508 sgmlOpenTag(os, depth + 1, inner_tag);
2510 SimpleDocBookOnePar(os, extra_par, tpar,
2511 desc_on, depth + 2);
2512 sgmlCloseTag(os, depth+1, inner_tag);
2513 if (!extra_par.empty())
2519 // checks, if newcol chars should be put into this line
2520 // writes newline, if necessary.
2523 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2524 string::size_type newcol)
2527 if (colcount > lyxrc.ascii_linelen) {
2529 colcount = newcol; // assume write after this call
2544 string tag_name(PAR_TAG const & pt) {
2546 case NONE: return "!-- --";
2547 case TT: return "tt";
2548 case SF: return "sf";
2549 case BF: return "bf";
2550 case IT: return "it";
2551 case SL: return "sl";
2552 case EM: return "em";
2559 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2561 p1 = static_cast<PAR_TAG>(p1 | p2);
2566 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2568 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2576 // Handle internal paragraph parsing -- layout already processed.
2577 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2578 LyXParagraph * par, int /*depth*/)
2580 LyXLayout const & style = textclasslist.Style(params.textclass,
2582 string::size_type char_line_count = 5; // Heuristic choice ;-)
2584 // gets paragraph main font
2587 if (style.labeltype == LABEL_MANUAL) {
2588 font_old = style.labelfont;
2591 font_old = style.font;
2595 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2596 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2597 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2600 stack < PAR_TAG > tag_state;
2601 // parsing main loop
2602 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
2604 PAR_TAG tag_close = NONE;
2605 list < PAR_TAG > tag_open;
2607 LyXFont const font = par->getFont(params, i);
2609 if (font_old.family() != font.family()) {
2610 switch (family_type) {
2611 case LyXFont::SANS_FAMILY:
2614 case LyXFont::TYPEWRITER_FAMILY:
2621 family_type = font.family();
2623 switch (family_type) {
2624 case LyXFont::SANS_FAMILY:
2625 tag_open.push_back(SF);
2627 case LyXFont::TYPEWRITER_FAMILY:
2628 tag_open.push_back(TT);
2635 if (font_old.series() != font.series()) {
2636 switch (series_type) {
2637 case LyXFont::BOLD_SERIES:
2644 series_type = font.series();
2646 switch (series_type) {
2647 case LyXFont::BOLD_SERIES:
2648 tag_open.push_back(BF);
2656 if (font_old.shape() != font.shape()) {
2657 switch (shape_type) {
2658 case LyXFont::ITALIC_SHAPE:
2661 case LyXFont::SLANTED_SHAPE:
2668 shape_type = font.shape();
2670 switch (shape_type) {
2671 case LyXFont::ITALIC_SHAPE:
2672 tag_open.push_back(IT);
2674 case LyXFont::SLANTED_SHAPE:
2675 tag_open.push_back(SL);
2682 if (font_old.emph() != font.emph()) {
2683 if (font.emph() == LyXFont::ON) {
2684 tag_open.push_back(EM);
2693 list < PAR_TAG > temp;
2694 while(!tag_state.empty() && tag_close ) {
2695 PAR_TAG k = tag_state.top();
2697 os << "</" << tag_name(k) << ">";
2704 for(list< PAR_TAG >::const_iterator j = temp.begin();
2705 j != temp.end(); ++j) {
2707 os << "<" << tag_name(*j) << ">";
2710 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2711 j != tag_open.end(); ++j) {
2713 os << "<" << tag_name(*j) << ">";
2716 char c = par->GetChar(i);
2718 if (c == LyXParagraph::META_INSET) {
2719 Inset * inset = par->GetInset(i);
2720 inset->Linuxdoc(this, os);
2725 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
2726 // "TeX"-Mode on == > SGML-Mode on.
2732 if (par->linuxDocConvertChar(c, sgml_string)
2733 && !style.free_spacing) {
2734 // in freespacing mode, spaces are
2735 // non-breaking characters
2736 if (desc_on) {// if char is ' ' then...
2739 linux_doc_line_break(os, char_line_count, 6);
2743 linux_doc_line_break(os, char_line_count, 1);
2748 char_line_count += sgml_string.length();
2754 while (!tag_state.empty()) {
2755 os << "</" << tag_name(tag_state.top()) << ">";
2759 // resets description flag correctly
2761 // <tag> not closed...
2762 linux_doc_line_break(os, char_line_count, 6);
2768 // Print an error message.
2769 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2770 string const & message)
2772 // insert an error marker in text
2773 InsetError * new_inset = new InsetError(message);
2774 par->InsertInset(pos, new_inset);
2778 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2780 ofstream ofs(fname.c_str());
2782 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2786 LyXParagraph * par = paragraph;
2788 niceFile = nice; // this will be used by Insetincludes.
2790 LyXTextClass const & tclass =
2791 textclasslist.TextClass(params.textclass);
2793 LaTeXFeatures features(params, tclass.numLayouts());
2798 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2801 string sgml_includedfiles = features.getIncludedFiles(fname);
2803 ofs << "<!doctype " << top_element
2804 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2806 if (params.preamble.empty() && sgml_includedfiles.empty())
2809 ofs << "\n [ " << params.preamble
2810 << sgml_includedfiles << " \n]>\n\n";
2813 string top = top_element;
2815 top += params.language->code();
2818 if (!params.options.empty()) {
2820 top += params.options;
2822 sgmlOpenTag(ofs, 0, top);
2824 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2825 << "\n See http://www.lyx.org/ for more information -->\n";
2827 vector<string> environment_stack(10);
2828 vector<string> environment_inner(10);
2829 vector<string> command_stack(10);
2831 bool command_flag = false;
2832 int command_depth = 0;
2833 int command_base = 0;
2835 int depth = 0; // paragraph depth
2838 string command_name;
2844 int desc_on = 0; // description mode
2846 LyXLayout const & style =
2847 textclasslist.Style(params.textclass,
2850 // environment tag closing
2851 for (; depth > par->params.depth(); --depth) {
2852 if (environment_inner[depth] != "!-- --") {
2853 item_name = "listitem";
2854 sgmlCloseTag(ofs, command_depth + depth,
2856 if (environment_inner[depth] == "varlistentry")
2857 sgmlCloseTag(ofs, depth+command_depth,
2858 environment_inner[depth]);
2860 sgmlCloseTag(ofs, depth + command_depth,
2861 environment_stack[depth]);
2862 environment_stack[depth].erase();
2863 environment_inner[depth].erase();
2866 if (depth == par->params.depth()
2867 && environment_stack[depth] != style.latexname()
2868 && !environment_stack[depth].empty()) {
2869 if (environment_inner[depth] != "!-- --") {
2870 item_name= "listitem";
2871 sgmlCloseTag(ofs, command_depth+depth,
2873 if (environment_inner[depth] == "varlistentry")
2875 depth + command_depth,
2876 environment_inner[depth]);
2879 sgmlCloseTag(ofs, depth + command_depth,
2880 environment_stack[depth]);
2882 environment_stack[depth].erase();
2883 environment_inner[depth].erase();
2886 // Write opening SGML tags.
2887 switch (style.latextype) {
2888 case LATEX_PARAGRAPH:
2889 sgmlOpenTag(ofs, depth + command_depth,
2895 LinuxDocError(par, 0,
2896 _("Error : Wrong depth for "
2897 "LatexType Command.\n"));
2899 command_name = style.latexname();
2901 sgmlparam = style.latexparam();
2902 c_params = split(sgmlparam, c_depth,'|');
2904 cmd_depth = lyx::atoi(c_depth);
2907 if (cmd_depth < command_base) {
2908 for (int j = command_depth; j >= command_base; --j)
2909 sgmlCloseTag(ofs, j, command_stack[j]);
2910 command_depth = command_base = cmd_depth;
2911 } else if (cmd_depth <= command_depth) {
2912 for (int j = command_depth; j >= cmd_depth; --j)
2913 sgmlCloseTag(ofs, j, command_stack[j]);
2914 command_depth = cmd_depth;
2916 command_depth = cmd_depth;
2918 command_depth = command_base = cmd_depth;
2919 command_flag = true;
2921 if (command_stack.size() == command_depth + 1)
2922 command_stack.push_back("");
2923 command_stack[command_depth] = command_name;
2925 // treat label as a special case for
2926 // more WYSIWYM handling.
2927 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2928 Inset * inset = par->GetInset(0);
2929 Inset::Code lyx_code = inset->LyxCode();
2930 if (lyx_code == Inset::LABEL_CODE){
2931 command_name += " id=\"";
2932 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2933 command_name += "\"";
2938 sgmlOpenTag(ofs, depth + command_depth, command_name);
2939 if (c_params.empty())
2940 item_name = "title";
2942 item_name = c_params;
2943 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2946 case LATEX_ENVIRONMENT:
2947 case LATEX_ITEM_ENVIRONMENT:
2948 if (depth < par->params.depth()) {
2949 depth = par->params.depth();
2950 environment_stack[depth].erase();
2953 if (environment_stack[depth] != style.latexname()) {
2954 if(environment_stack.size() == depth + 1) {
2955 environment_stack.push_back("!-- --");
2956 environment_inner.push_back("!-- --");
2958 environment_stack[depth] = style.latexname();
2959 environment_inner[depth] = "!-- --";
2960 sgmlOpenTag(ofs, depth + command_depth,
2961 environment_stack[depth]);
2963 if (environment_inner[depth] != "!-- --") {
2964 item_name= "listitem";
2966 command_depth + depth,
2968 if (environment_inner[depth] == "varlistentry")
2970 depth + command_depth,
2971 environment_inner[depth]);
2975 if (style.latextype == LATEX_ENVIRONMENT) {
2976 if (!style.latexparam().empty()) {
2977 if(style.latexparam() == "CDATA")
2980 sgmlOpenTag(ofs, depth + command_depth,
2981 style.latexparam());
2986 desc_on = (style.labeltype == LABEL_MANUAL);
2989 environment_inner[depth]= "varlistentry";
2991 environment_inner[depth]= "listitem";
2993 sgmlOpenTag(ofs, depth + 1 + command_depth,
2994 environment_inner[depth]);
2998 sgmlOpenTag(ofs, depth + 1 + command_depth,
3002 sgmlOpenTag(ofs, depth + 1 + command_depth,
3007 sgmlOpenTag(ofs, depth + command_depth,
3013 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3014 depth + 1 + command_depth);
3018 // write closing SGML tags
3019 switch (style.latextype) {
3021 if (c_params.empty())
3025 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3027 case LATEX_ENVIRONMENT:
3028 if (!style.latexparam().empty()) {
3029 if(style.latexparam() == "CDATA")
3032 sgmlCloseTag(ofs, depth + command_depth,
3033 style.latexparam());
3036 case LATEX_ITEM_ENVIRONMENT:
3037 if (desc_on == 1) break;
3039 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3041 case LATEX_PARAGRAPH:
3042 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3045 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3051 for (; depth >= 0; --depth) {
3052 if (!environment_stack[depth].empty()) {
3053 if (environment_inner[depth] != "!-- --") {
3054 item_name = "listitem";
3055 sgmlCloseTag(ofs, command_depth + depth,
3057 if (environment_inner[depth] == "varlistentry")
3058 sgmlCloseTag(ofs, depth + command_depth,
3059 environment_inner[depth]);
3062 sgmlCloseTag(ofs, depth + command_depth,
3063 environment_stack[depth]);
3067 for (int j = command_depth; j >= command_base; --j)
3068 if (!command_stack[j].empty())
3069 sgmlCloseTag(ofs, j, command_stack[j]);
3072 sgmlCloseTag(ofs, 0, top_element);
3075 // How to check for successful close
3079 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3080 LyXParagraph * par, int & desc_on,
3083 bool emph_flag = false;
3085 LyXLayout const & style = textclasslist.Style(params.textclass,
3088 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3090 int char_line_count = depth;
3091 if (!style.free_spacing)
3092 os << string(depth,' ');
3094 // parsing main loop
3095 for (LyXParagraph::size_type i = 0;
3096 i < par->size(); ++i) {
3097 LyXFont font = par->getFont(params, i);
3099 // handle <emphasis> tag
3100 if (font_old.emph() != font.emph()) {
3101 if (font.emph() == LyXFont::ON) {
3105 os << "</emphasis>";
3110 char c = par->GetChar(i);
3112 if (c == LyXParagraph::META_INSET) {
3113 Inset * inset = par->GetInset(i);
3114 std::ostringstream ost;
3115 inset->DocBook(this, ost);
3116 string tmp_out = ost.str().c_str();
3119 // This code needs some explanation:
3120 // Two insets are treated specially
3121 // label if it is the first element in a command paragraph
3123 // graphics inside tables or figure floats can't go on
3124 // title (the equivalente in latex for this case is caption
3125 // and title should come first
3128 if (desc_on!= 3 || i!= 0) {
3129 if (!tmp_out.empty() && tmp_out[0] == '@') {
3131 extra += frontStrip(tmp_out, '@');
3133 os << frontStrip(tmp_out, '@');
3138 } else if (font.latex() == LyXFont::ON) {
3139 // "TeX"-Mode on ==> SGML-Mode on.
3145 if (par->linuxDocConvertChar(c, sgml_string)
3146 && !style.free_spacing) { // in freespacing
3148 // non-breaking characters
3152 os << "\n</term><listitem><para>";
3165 os << "</emphasis>";
3168 // resets description flag correctly
3170 // <term> not closed...
3177 // This should be enabled when the Chktex class is implemented. (Asger)
3178 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3179 // Other flags: -wall -v0 -x
3180 int Buffer::runChktex()
3182 if (!users->text) return 0;
3184 ProhibitInput(users);
3186 // get LaTeX-Filename
3187 string const name = getLatexName();
3188 string path = OnlyPath(filename);
3190 string const org_path = path;
3191 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3195 Path p(path); // path to LaTeX file
3196 users->owner()->message(_("Running chktex..."));
3198 // Remove all error insets
3199 bool const removedErrorInsets = users->removeAutoInsets();
3201 // Generate the LaTeX file if neccessary
3202 makeLaTeXFile(name, org_path, false);
3205 Chktex chktex(lyxrc.chktex_command, name, filepath);
3206 int res = chktex.run(terr); // run chktex
3209 WriteAlert(_("chktex did not work!"),
3210 _("Could not run with file:"), name);
3211 } else if (res > 0) {
3212 // Insert all errors as errors boxes
3213 users->insertErrors(terr);
3216 // if we removed error insets before we ran chktex or if we inserted
3217 // error insets after we ran chktex, this must be run:
3218 if (removedErrorInsets || res){
3220 users->fitCursor(users->text);
3228 void Buffer::validate(LaTeXFeatures & features) const
3230 LyXParagraph * par = paragraph;
3231 LyXTextClass const & tclass =
3232 textclasslist.TextClass(params.textclass);
3234 // AMS Style is at document level
3236 features.amsstyle = (params.use_amsmath ||
3237 tclass.provides(LyXTextClass::amsmath));
3240 // We don't use "lyxerr.debug" because of speed. (Asger)
3241 if (lyxerr.debugging(Debug::LATEX))
3242 lyxerr << "Paragraph: " << par << endl;
3244 // Now just follow the list of paragraphs and run
3245 // validate on each of them.
3246 par->validate(features);
3248 // and then the next paragraph
3252 // the bullet shapes are buffer level not paragraph level
3253 // so they are tested here
3254 for (int i = 0; i < 4; ++i) {
3255 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3256 int const font = params.user_defined_bullets[i].getFont();
3258 int const c = params
3259 .user_defined_bullets[i]
3266 features.latexsym = true;
3268 } else if (font == 1) {
3269 features.amssymb = true;
3270 } else if ((font >= 2 && font <= 5)) {
3271 features.pifont = true;
3276 if (lyxerr.debugging(Debug::LATEX)) {
3277 features.showStruct();
3282 void Buffer::setPaperStuff()
3284 params.papersize = BufferParams::PAPER_DEFAULT;
3285 char const c1 = params.paperpackage;
3286 if (c1 == BufferParams::PACKAGE_NONE) {
3287 char const c2 = params.papersize2;
3288 if (c2 == BufferParams::VM_PAPER_USLETTER)
3289 params.papersize = BufferParams::PAPER_USLETTER;
3290 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3291 params.papersize = BufferParams::PAPER_LEGALPAPER;
3292 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3293 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3294 else if (c2 == BufferParams::VM_PAPER_A3)
3295 params.papersize = BufferParams::PAPER_A3PAPER;
3296 else if (c2 == BufferParams::VM_PAPER_A4)
3297 params.papersize = BufferParams::PAPER_A4PAPER;
3298 else if (c2 == BufferParams::VM_PAPER_A5)
3299 params.papersize = BufferParams::PAPER_A5PAPER;
3300 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3301 (c2 == BufferParams::VM_PAPER_B5))
3302 params.papersize = BufferParams::PAPER_B5PAPER;
3303 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3304 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3305 params.papersize = BufferParams::PAPER_A4PAPER;
3309 // This function should be in Buffer because it's a buffer's property (ale)
3310 string const Buffer::getIncludeonlyList(char delim)
3313 for (inset_iterator it = inset_iterator_begin();
3314 it != inset_iterator_end(); ++it) {
3315 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3316 InsetInclude * insetinc =
3317 static_cast<InsetInclude *>(*it);
3318 if (insetinc->isIncludeOnly()) {
3321 lst += insetinc->getRelFileBaseName();
3325 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3330 vector<string> const Buffer::getLabelList()
3332 /// if this is a child document and the parent is already loaded
3333 /// Use the parent's list instead [ale990407]
3334 if (!params.parentname.empty()
3335 && bufferlist.exists(params.parentname)) {
3336 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3338 return tmp->getLabelList();
3341 vector<string> label_list;
3342 for (inset_iterator it = inset_iterator_begin();
3343 it != inset_iterator_end(); ++it) {
3344 vector<string> const l = (*it)->getLabelList();
3345 label_list.insert(label_list.end(), l.begin(), l.end());
3351 Buffer::Lists const Buffer::getLists() const
3354 LyXParagraph * par = paragraph;
3356 LyXTextClassList::size_type cap;
3357 boost::tie(found, cap) = textclasslist
3358 .NumberOfLayout(params.textclass, "Caption");
3361 char const labeltype =
3362 textclasslist.Style(params.textclass,
3363 par->GetLayout()).labeltype;
3365 if (labeltype >= LABEL_COUNTER_CHAPTER
3366 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3367 // insert this into the table of contents
3368 SingleList & item = l["TOC"];
3371 textclasslist.TextClass(params.textclass).maxcounter());
3372 item.push_back(TocItem(par, depth, par->String(this, true)));
3374 // For each paragrph, traverse its insets and look for
3378 LyXParagraph::inset_iterator it =
3379 par->inset_iterator_begin();
3380 LyXParagraph::inset_iterator end =
3381 par->inset_iterator_end();
3383 for (; it != end; ++it) {
3384 if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3386 static_cast<InsetFloat*>(*it);
3388 string const type = il->type();
3390 // Now find the caption in the float...
3391 // We now tranverse the paragraphs of
3393 LyXParagraph * tmp = il->inset.par;
3395 if (tmp->layout == cap) {
3396 SingleList & item = l[type];
3398 tostr(item.size()+1) + ". " + tmp->String(this, false);
3399 item.push_back(TocItem(tmp, 0 , str));
3406 lyxerr << "caption not found" << endl;
3415 // This is also a buffer property (ale)
3416 vector<pair<string, string> > const Buffer::getBibkeyList()
3418 /// if this is a child document and the parent is already loaded
3419 /// Use the parent's list instead [ale990412]
3420 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3421 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3423 return tmp->getBibkeyList();
3426 vector<pair<string, string> > keys;
3427 LyXParagraph * par = paragraph;
3430 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3431 par->String(this, false)));
3435 // Might be either using bibtex or a child has bibliography
3437 for (inset_iterator it = inset_iterator_begin();
3438 it != inset_iterator_end(); ++it) {
3439 // Search for Bibtex or Include inset
3440 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3441 vector<pair<string,string> > tmp =
3442 static_cast<InsetBibtex*>(*it)->getKeys(this);
3443 keys.insert(keys.end(), tmp.begin(), tmp.end());
3444 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3445 vector<pair<string,string> > const tmp =
3446 static_cast<InsetInclude*>(*it)->getKeys();
3447 keys.insert(keys.end(), tmp.begin(), tmp.end());
3456 bool Buffer::isDepClean(string const & name) const
3458 DEPCLEAN * item = dep_clean;
3459 while (item && item->master != name)
3461 if (!item) return true;
3466 void Buffer::markDepClean(string const & name)
3469 dep_clean = new DEPCLEAN;
3470 dep_clean->clean = true;
3471 dep_clean->master = name;
3472 dep_clean->next = 0;
3474 DEPCLEAN * item = dep_clean;
3475 while (item && item->master != name)
3480 item = new DEPCLEAN;
3482 item->master = name;
3489 bool Buffer::Dispatch(string const & command)
3491 // Split command string into command and argument
3493 string line = frontStrip(command);
3494 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3496 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3500 bool Buffer::Dispatch(int action, string const & argument)
3502 bool dispatched = true;
3505 Exporter::Export(this, argument, false);
3515 void Buffer::resize()
3517 /// resize the BufferViews!
3523 void Buffer::resizeInsets(BufferView * bv)
3525 /// then remove all LyXText in text-insets
3526 LyXParagraph * par = paragraph;
3527 for (; par; par = par->next()) {
3528 par->resizeInsetsLyXText(bv);
3533 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3536 LyXParagraph * par = paragraph;
3538 par->ChangeLanguage(params, from, to);
3544 bool Buffer::isMultiLingual()
3546 LyXParagraph * par = paragraph;
3548 if (par->isMultiLingual(params))
3556 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3557 LyXParagraph::size_type pos)
3560 it = par->InsetIterator(pos);
3561 if (it == par->inset_iterator_end()) {
3568 void Buffer::inset_iterator::SetParagraph()
3571 it = par->inset_iterator_begin();
3572 if (it != par->inset_iterator_end())
3577 // We maintain an invariant that whenever par = 0 then it = 0