1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
23 #include <sys/types.h>
33 #pragma implementation "buffer.h"
37 #include "bufferlist.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
43 #include "tex-strings.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h"
59 #include "insets/insetcite.h"
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h"
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
92 #include "lyx_gui_misc.h" // WarnReadonly()
93 #include "frontends/Dialogs.h"
97 #include "converter.h"
107 using std::make_pair;
112 // all these externs should eventually be removed.
113 extern BufferList bufferlist;
115 extern LyXAction lyxaction;
118 static const int LYX_FORMAT = 218;
120 extern int tex_code_break_column;
123 Buffer::Buffer(string const & file, bool ronly)
125 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
127 filepath = OnlyPath(file);
136 if (read_only || (lyxrc.use_tempdir)) {
137 tmppath = CreateBufferTmpDir();
138 } else tmppath.erase();
144 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
145 // here the buffer should take care that it is
146 // saved properly, before it goes into the void.
148 // make sure that views using this buffer
153 if (!tmppath.empty()) {
154 DestroyBufferTmpDir(tmppath);
157 LyXParagraph * par = paragraph;
158 LyXParagraph * tmppar;
168 string const Buffer::getLatexName(bool no_path) const
171 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
174 return ChangeExtension(MakeLatexName(filename),
178 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
180 string filename, fname, bname, path;
182 filename = getLatexName(false);
184 if (filename.empty())
185 return make_pair(Buffer::latexlog, string());
187 path = OnlyPath(filename);
189 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
192 fname = AddName(path, OnlyFilename(ChangeExtension(filename, ".log")));
193 bname = AddName(path, OnlyFilename(ChangeExtension(filename,
194 formats.Extension("literate") + ".out")));
196 // If no Latex log or Build log is newer, show Build log
198 FileInfo f_fi(fname), b_fi(bname);
201 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
202 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
203 return make_pair(Buffer::buildlog, bname);
205 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
206 return make_pair(Buffer::latexlog, fname);
209 void Buffer::setReadonly(bool flag)
211 if (read_only != flag) {
214 users->owner()->getDialogs()->updateBufferDependent(false);
217 WarnReadonly(filename);
222 bool Buffer::saveParamsAsDefaults() // const
224 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
226 Buffer defaults = Buffer(fname);
228 // Use the current buffer's parameters as default
229 defaults.params = params;
231 // add an empty paragraph. Is this enough?
232 defaults.paragraph = new LyXParagraph;
234 return defaults.writeFile(defaults.filename, false);
238 /// Update window titles of all users
239 // Should work on a list
240 void Buffer::updateTitles() const
242 if (users) users->owner()->updateWindowTitle();
246 /// Reset autosave timer of all users
247 // Should work on a list
248 void Buffer::resetAutosaveTimers() const
250 if (users) users->owner()->resetAutosaveTimer();
254 void Buffer::setFileName(string const & newfile)
256 filename = MakeAbsPath(newfile);
257 filepath = OnlyPath(filename);
258 setReadonly(IsFileWriteable(filename) == 0);
263 // candidate for move to BufferView
264 // (at least some parts in the beginning of the func)
267 // changed to be public and have one parameter
268 // if par = 0 normal behavior
269 // else insert behavior
270 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
271 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
274 char depth = 0; // signed or unsigned?
276 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
277 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
279 bool the_end_read = false;
281 LyXParagraph * return_par = 0;
282 LyXFont font(LyXFont::ALL_INHERIT, params.language);
283 if (file_format < 216 && params.language->lang() == "hebrew")
284 font.setLanguage(default_language);
285 // If we are inserting, we cheat and get a token in advance
286 bool has_token = false;
290 par = new LyXParagraph;
292 users->text->BreakParagraph(users);
293 return_par = users->text->FirstParagraph();
296 // We don't want to adopt the parameters from the
297 // document we insert, so we skip until the text begins:
300 pretoken = lex.GetString();
301 if (pretoken == "\\layout") {
313 pretoken = lex.GetString();
316 if (pretoken.empty()) continue;
319 parseSingleLyXformat2Token(lex, par, return_par,
320 pretoken, pos, depth,
332 paragraph = return_par;
338 // We'll remove this later. (Lgb)
339 static string last_inset_read;
343 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
344 LyXParagraph *& return_par,
345 string const & token, int & pos,
346 char & depth, LyXFont & font
348 , LyXParagraph::footnote_flag & footnoteflag,
349 LyXParagraph::footnote_kind & footnotekind
353 bool the_end_read = false;
355 if (token[0] != '\\') {
356 for (string::const_iterator cit = token.begin();
357 cit != token.end(); ++cit) {
358 par->InsertChar(pos, (*cit), font);
361 } else if (token == "\\i") {
362 Inset * inset = new InsetLatexAccent;
363 inset->Read(this, lex);
364 par->InsertInset(pos, inset, font);
366 } else if (token == "\\layout") {
371 par = new LyXParagraph(par);
375 string const layoutname = lex.GetString();
376 pair<bool, LyXTextClass::LayoutList::size_type> pp
377 = textclasslist.NumberOfLayout(params.textclass,
380 par->layout = pp.second;
381 } else { // layout not found
382 // use default layout "Standard" (0)
385 // Test whether the layout is obsolete.
386 LyXLayout const & layout =
387 textclasslist.Style(params.textclass,
389 if (!layout.obsoleted_by().empty())
391 textclasslist.NumberOfLayout(params.textclass,
392 layout.obsoleted_by()).second;
394 par->footnoteflag = footnoteflag;
395 par->footnotekind = footnotekind;
397 par->params.depth(depth);
398 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
399 if (file_format < 216 && params.language->lang() == "hebrew")
400 font.setLanguage(default_language);
402 } else if (token == "\\end_float") {
407 par = new LyXParagraph(par);
409 footnotekind = LyXParagraph::FOOTNOTE;
410 footnoteflag = LyXParagraph::NO_FOOTNOTE;
413 par->layout = LYX_DUMMY_LAYOUT;
414 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
415 if (file_format < 216 && params.language->lang() == "hebrew")
416 font.setLanguage(default_language);
417 } else if (token == "\\begin_float") {
418 int tmpret = lex.FindToken(string_footnotekinds);
419 if (tmpret == -1) ++tmpret;
420 if (tmpret != LYX_LAYOUT_DEFAULT)
421 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
422 if (footnotekind == LyXParagraph::FOOTNOTE
423 || footnotekind == LyXParagraph::MARGIN)
424 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
426 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
428 } else if (token == "\\begin_float") {
429 // This is the compability reader, unfinished but tested.
432 string const tmptok = lex.GetString();
433 //lyxerr << "old float: " << tmptok << endl;
438 if (tmptok == "footnote") {
439 inset = new InsetFoot;
440 } else if (tmptok == "margin") {
441 inset = new InsetMarginal;
442 } else if (tmptok == "fig") {
443 inset = new InsetFloat("figure");
444 old_float += "placement htbp\n";
445 } else if (tmptok == "tab") {
446 inset = new InsetFloat("table");
447 old_float += "placement htbp\n";
448 } else if (tmptok == "alg") {
449 inset = new InsetFloat("algorithm");
450 old_float += "placement htbp\n";
451 } else if (tmptok == "wide-fig") {
452 InsetFloat * tmp = new InsetFloat("figure");
455 old_float += "placement htbp\n";
456 } else if (tmptok == "wide-tab") {
457 InsetFloat * tmp = new InsetFloat("table");
460 old_float += "placement htbp\n";
463 if (!inset) return false; // no end read yet
465 old_float += "collapsed true\n";
467 // Here we need to check for \end_deeper and handle that
468 // before we do the footnote parsing.
469 // This _is_ a hack! (Lgb)
472 string const tmp = lex.GetString();
473 if (tmp == "\\end_deeper") {
474 lyxerr << "\\end_deeper caught!" << endl;
476 lex.printError("\\end_deeper: "
477 "depth is already null");
488 old_float += lex.getLongString("\\end_float");
489 old_float += "\n\\end_inset\n";
490 //lyxerr << "float body: " << old_float << endl;
492 istringstream istr(old_float);
495 nylex.setStream(istr);
497 inset->Read(this, nylex);
498 par->InsertInset(pos, inset, font);
501 } else if (token == "\\begin_deeper") {
503 } else if (token == "\\end_deeper") {
505 lex.printError("\\end_deeper: "
506 "depth is already null");
510 } else if (token == "\\begin_preamble") {
511 params.readPreamble(lex);
512 } else if (token == "\\textclass") {
514 pair<bool, LyXTextClassList::size_type> pp =
515 textclasslist.NumberOfClass(lex.GetString());
517 params.textclass = pp.second;
519 WriteAlert(string(_("Textclass error")),
520 string(_("The document uses an unknown textclass \"")) +
521 lex.GetString() + string("\"."),
522 string(_("LyX will not be able to produce output correctly.")));
523 params.textclass = 0;
525 if (!textclasslist.Load(params.textclass)) {
526 // if the textclass wasn't loaded properly
527 // we need to either substitute another
528 // or stop loading the file.
529 // I can substitute but I don't see how I can
530 // stop loading... ideas?? ARRae980418
531 WriteAlert(_("Textclass Loading Error!"),
532 string(_("Can't load textclass ")) +
533 textclasslist.NameOfClass(params.textclass),
534 _("-- substituting default"));
535 params.textclass = 0;
537 } else if (token == "\\options") {
539 params.options = lex.GetString();
540 } else if (token == "\\language") {
541 params.readLanguage(lex);
542 } else if (token == "\\fontencoding") {
544 } else if (token == "\\inputencoding") {
546 params.inputenc = lex.GetString();
547 } else if (token == "\\graphics") {
548 params.readGraphicsDriver(lex);
549 } else if (token == "\\fontscheme") {
551 params.fonts = lex.GetString();
552 } else if (token == "\\noindent") {
553 par->params.noindent(true);
554 } else if (token == "\\fill_top") {
555 par->params.spaceTop(VSpace(VSpace::VFILL));
556 } else if (token == "\\fill_bottom") {
557 par->params.spaceBottom(VSpace(VSpace::VFILL));
558 } else if (token == "\\line_top") {
559 par->params.lineTop(true);
560 } else if (token == "\\line_bottom") {
561 par->params.lineBottom(true);
562 } else if (token == "\\pagebreak_top") {
563 par->params.pagebreakTop(true);
564 } else if (token == "\\pagebreak_bottom") {
565 par->params.pagebreakBottom(true);
566 } else if (token == "\\start_of_appendix") {
567 par->params.startOfAppendix(true);
568 } else if (token == "\\paragraph_separation") {
569 int tmpret = lex.FindToken(string_paragraph_separation);
570 if (tmpret == -1) ++tmpret;
571 if (tmpret != LYX_LAYOUT_DEFAULT)
572 params.paragraph_separation =
573 static_cast<BufferParams::PARSEP>(tmpret);
574 } else if (token == "\\defskip") {
576 params.defskip = VSpace(lex.GetString());
577 } else if (token == "\\epsfig") { // obsolete
578 // Indeed it is obsolete, but we HAVE to be backwards
579 // compatible until 0.14, because otherwise all figures
580 // in existing documents are irretrivably lost. (Asger)
581 params.readGraphicsDriver(lex);
582 } else if (token == "\\quotes_language") {
583 int tmpret = lex.FindToken(string_quotes_language);
584 if (tmpret == -1) ++tmpret;
585 if (tmpret != LYX_LAYOUT_DEFAULT) {
586 InsetQuotes::quote_language tmpl =
587 InsetQuotes::EnglishQ;
590 tmpl = InsetQuotes::EnglishQ;
593 tmpl = InsetQuotes::SwedishQ;
596 tmpl = InsetQuotes::GermanQ;
599 tmpl = InsetQuotes::PolishQ;
602 tmpl = InsetQuotes::FrenchQ;
605 tmpl = InsetQuotes::DanishQ;
608 params.quotes_language = tmpl;
610 } else if (token == "\\quotes_times") {
612 switch (lex.GetInteger()) {
614 params.quotes_times = InsetQuotes::SingleQ;
617 params.quotes_times = InsetQuotes::DoubleQ;
620 } else if (token == "\\papersize") {
621 int tmpret = lex.FindToken(string_papersize);
625 params.papersize2 = tmpret;
626 } else if (token == "\\paperpackage") {
627 int tmpret = lex.FindToken(string_paperpackages);
630 params.paperpackage = BufferParams::PACKAGE_NONE;
632 params.paperpackage = tmpret;
633 } else if (token == "\\use_geometry") {
635 params.use_geometry = lex.GetInteger();
636 } else if (token == "\\use_amsmath") {
638 params.use_amsmath = lex.GetInteger();
639 } else if (token == "\\paperorientation") {
640 int tmpret = lex.FindToken(string_orientation);
641 if (tmpret == -1) ++tmpret;
642 if (tmpret != LYX_LAYOUT_DEFAULT)
643 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
644 } else if (token == "\\paperwidth") {
646 params.paperwidth = lex.GetString();
647 } else if (token == "\\paperheight") {
649 params.paperheight = lex.GetString();
650 } else if (token == "\\leftmargin") {
652 params.leftmargin = lex.GetString();
653 } else if (token == "\\topmargin") {
655 params.topmargin = lex.GetString();
656 } else if (token == "\\rightmargin") {
658 params.rightmargin = lex.GetString();
659 } else if (token == "\\bottommargin") {
661 params.bottommargin = lex.GetString();
662 } else if (token == "\\headheight") {
664 params.headheight = lex.GetString();
665 } else if (token == "\\headsep") {
667 params.headsep = lex.GetString();
668 } else if (token == "\\footskip") {
670 params.footskip = lex.GetString();
671 } else if (token == "\\paperfontsize") {
673 params.fontsize = strip(lex.GetString());
674 } else if (token == "\\papercolumns") {
676 params.columns = lex.GetInteger();
677 } else if (token == "\\papersides") {
679 switch (lex.GetInteger()) {
681 case 1: params.sides = LyXTextClass::OneSide; break;
682 case 2: params.sides = LyXTextClass::TwoSides; break;
684 } else if (token == "\\paperpagestyle") {
686 params.pagestyle = strip(lex.GetString());
687 } else if (token == "\\bullet") {
689 int const index = lex.GetInteger();
691 int temp_int = lex.GetInteger();
692 params.user_defined_bullets[index].setFont(temp_int);
693 params.temp_bullets[index].setFont(temp_int);
695 temp_int = lex.GetInteger();
696 params.user_defined_bullets[index].setCharacter(temp_int);
697 params.temp_bullets[index].setCharacter(temp_int);
699 temp_int = lex.GetInteger();
700 params.user_defined_bullets[index].setSize(temp_int);
701 params.temp_bullets[index].setSize(temp_int);
703 string const temp_str = lex.GetString();
704 if (temp_str != "\\end_bullet") {
705 // this element isn't really necessary for
706 // parsing but is easier for humans
707 // to understand bullets. Put it back and
708 // set a debug message?
709 lex.printError("\\end_bullet expected, got" + temp_str);
710 //how can I put it back?
712 } else if (token == "\\bulletLaTeX") {
714 int const index = lex.GetInteger();
716 string temp_str = lex.GetString();
718 while (temp_str != "\\end_bullet") {
719 // this loop structure is needed when user
720 // enters an empty string since the first
721 // thing returned will be the \\end_bullet
723 // if the LaTeX entry has spaces. Each element
724 // therefore needs to be read in turn
727 temp_str = lex.GetString();
729 params.user_defined_bullets[index].setText(sum_str);
730 params.temp_bullets[index].setText(sum_str);
731 } else if (token == "\\secnumdepth") {
733 params.secnumdepth = lex.GetInteger();
734 } else if (token == "\\tocdepth") {
736 params.tocdepth = lex.GetInteger();
737 } else if (token == "\\spacing") {
739 string const tmp = strip(lex.GetString());
740 Spacing::Space tmp_space = Spacing::Default;
742 if (tmp == "single") {
743 tmp_space = Spacing::Single;
744 } else if (tmp == "onehalf") {
745 tmp_space = Spacing::Onehalf;
746 } else if (tmp == "double") {
747 tmp_space = Spacing::Double;
748 } else if (tmp == "other") {
750 tmp_space = Spacing::Other;
751 tmp_val = lex.GetFloat();
753 lex.printError("Unknown spacing token: '$$Token'");
755 // Small hack so that files written with klyx will be
758 par->params.spacing(Spacing(tmp_space, tmp_val));
760 params.spacing.set(tmp_space, tmp_val);
762 } else if (token == "\\paragraph_spacing") {
764 string const tmp = strip(lex.GetString());
765 if (tmp == "single") {
766 par->params.spacing(Spacing(Spacing::Single));
767 } else if (tmp == "onehalf") {
768 par->params.spacing(Spacing(Spacing::Onehalf));
769 } else if (tmp == "double") {
770 par->params.spacing(Spacing(Spacing::Double));
771 } else if (tmp == "other") {
773 par->params.spacing(Spacing(Spacing::Other,
776 lex.printError("Unknown spacing token: '$$Token'");
778 } else if (token == "\\float_placement") {
780 params.float_placement = lex.GetString();
781 } else if (token == "\\family") {
783 font.setLyXFamily(lex.GetString());
784 } else if (token == "\\series") {
786 font.setLyXSeries(lex.GetString());
787 } else if (token == "\\shape") {
789 font.setLyXShape(lex.GetString());
790 } else if (token == "\\size") {
792 font.setLyXSize(lex.GetString());
793 } else if (token == "\\latex") {
795 string const tok = lex.GetString();
796 // This is dirty, but gone with LyX3. (Asger)
797 if (tok == "no_latex")
798 font.setLatex(LyXFont::OFF);
799 else if (tok == "latex")
800 font.setLatex(LyXFont::ON);
801 else if (tok == "default")
802 font.setLatex(LyXFont::INHERIT);
804 lex.printError("Unknown LaTeX font flag "
806 } else if (token == "\\lang") {
808 string const tok = lex.GetString();
809 Language const * lang = languages.getLanguage(tok);
811 font.setLanguage(lang);
813 font.setLanguage(params.language);
814 lex.printError("Unknown language `$$Token'");
816 } else if (token == "\\numeric") {
818 font.setNumber(font.setLyXMisc(lex.GetString()));
819 } else if (token == "\\emph") {
821 font.setEmph(font.setLyXMisc(lex.GetString()));
822 } else if (token == "\\bar") {
824 string const tok = lex.GetString();
825 // This is dirty, but gone with LyX3. (Asger)
827 font.setUnderbar(LyXFont::ON);
828 else if (tok == "no")
829 font.setUnderbar(LyXFont::OFF);
830 else if (tok == "default")
831 font.setUnderbar(LyXFont::INHERIT);
833 lex.printError("Unknown bar font flag "
835 } else if (token == "\\noun") {
837 font.setNoun(font.setLyXMisc(lex.GetString()));
838 } else if (token == "\\color") {
840 font.setLyXColor(lex.GetString());
841 } else if (token == "\\align") {
842 int tmpret = lex.FindToken(string_align);
843 if (tmpret == -1) ++tmpret;
844 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
845 int const tmpret2 = int(pow(2.0, tmpret));
846 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
847 par->params.align(LyXAlignment(tmpret2));
849 } else if (token == "\\added_space_top") {
851 par->params.spaceTop(VSpace(lex.GetString()));
852 } else if (token == "\\added_space_bottom") {
854 par->params.spaceBottom(VSpace(lex.GetString()));
855 } else if (token == "\\pextra_type") {
857 par->params.pextraType(lex.GetInteger());
858 } else if (token == "\\pextra_width") {
860 par->params.pextraWidth(lex.GetString());
861 } else if (token == "\\pextra_widthp") {
863 par->params.pextraWidthp(lex.GetString());
864 } else if (token == "\\pextra_alignment") {
866 par->params.pextraAlignment(lex.GetInteger());
867 } else if (token == "\\pextra_hfill") {
869 par->params.pextraHfill(lex.GetInteger());
870 } else if (token == "\\pextra_start_minipage") {
872 par->params.pextraStartMinipage(lex.GetInteger());
873 } else if (token == "\\labelwidthstring") {
875 par->params.labelWidthString(lex.GetString());
876 // do not delete this token, it is still needed!
877 } else if (token == "\\end_inset") {
878 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
879 << "Last inset read was: " << last_inset_read
881 // Simply ignore this. The insets do not have
883 // But insets should read it, it is a part of
884 // the inset isn't it? Lgb.
885 } else if (token == "\\begin_inset") {
886 readInset(lex, par, pos, font);
887 } else if (token == "\\SpecialChar") {
888 LyXLayout const & layout =
889 textclasslist.Style(params.textclass,
892 // Insets don't make sense in a free-spacing context! ---Kayvan
893 if (layout.free_spacing) {
896 string next_token = lex.GetString();
897 if (next_token == "\\-") {
898 par->InsertChar(pos, '-', font);
899 } else if (next_token == "\\protected_separator"
900 || next_token == "~") {
901 par->InsertChar(pos, ' ', font);
903 lex.printError("Token `$$Token' "
905 "paragraph layout!");
910 Inset * inset = new InsetSpecialChar;
911 inset->Read(this, lex);
912 par->InsertInset(pos, inset, font);
915 } else if (token == "\\newline") {
916 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
918 } else if (token == "\\LyXTable") {
919 Inset * inset = new InsetTabular(*this);
920 inset->Read(this, lex);
921 par->InsertInset(pos, inset, font);
923 } else if (token == "\\hfill") {
924 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
926 } else if (token == "\\protected_separator") { // obsolete
927 // This is a backward compability thingie. (Lgb)
928 // Remove it later some time...introduced with fileformat
930 LyXLayout const & layout =
931 textclasslist.Style(params.textclass,
934 if (layout.free_spacing) {
935 par->InsertChar(pos, ' ', font);
937 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
938 par->InsertInset(pos, inset, font);
941 } else if (token == "\\bibitem") { // ale970302
943 InsetCommandParams p("bibitem", "dummy");
944 par->bibkey = new InsetBibKey(p);
946 par->bibkey->Read(this, lex);
947 } else if (token == "\\backslash") {
948 par->InsertChar(pos, '\\', font);
950 } else if (token == "\\the_end") {
953 // This should be insurance for the future: (Asger)
954 lex.printError("Unknown token `$$Token'. "
955 "Inserting as text.");
956 string::const_iterator cit = token.begin();
957 string::const_iterator end = token.end();
958 for (; cit != end; ++cit) {
959 par->InsertChar(pos, (*cit), font);
967 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
968 int & pos, LyXFont & font)
971 if (lex.GetString() != "\\begin_inset") {
972 lyxerr << "Buffer::readInset: Consistency check failed."
979 string const tmptok = lex.GetString();
980 last_inset_read = tmptok;
982 // test the different insets
983 if (tmptok == "LatexCommand") {
984 InsetCommandParams inscmd;
987 if (inscmd.getCmdName() == "cite") {
988 inset = new InsetCitation(inscmd);
989 } else if (inscmd.getCmdName() == "bibitem") {
990 lex.printError("Wrong place for bibitem");
991 inset = new InsetBibKey(inscmd);
992 } else if (inscmd.getCmdName() == "BibTeX") {
993 inset = new InsetBibtex(inscmd);
994 } else if (inscmd.getCmdName() == "index") {
995 inset = new InsetIndex(inscmd);
996 } else if (inscmd.getCmdName() == "include") {
997 inset = new InsetInclude(inscmd, *this);
998 } else if (inscmd.getCmdName() == "label") {
999 inset = new InsetLabel(inscmd);
1000 } else if (inscmd.getCmdName() == "url"
1001 || inscmd.getCmdName() == "htmlurl") {
1002 inset = new InsetUrl(inscmd);
1003 } else if (inscmd.getCmdName() == "ref"
1004 || inscmd.getCmdName() == "pageref"
1005 || inscmd.getCmdName() == "vref"
1006 || inscmd.getCmdName() == "vpageref"
1007 || inscmd.getCmdName() == "prettyref") {
1008 if (!inscmd.getOptions().empty()
1009 || !inscmd.getContents().empty()) {
1010 inset = new InsetRef(inscmd, *this);
1012 } else if (inscmd.getCmdName() == "tableofcontents"
1013 || inscmd.getCmdName() == "listofalgorithms"
1014 || inscmd.getCmdName() == "listoffigures"
1015 || inscmd.getCmdName() == "listoftables") {
1016 inset = new InsetTOC(inscmd);
1017 } else if (inscmd.getCmdName() == "printindex") {
1018 inset = new InsetPrintIndex(inscmd);
1019 } else if (inscmd.getCmdName() == "lyxparent") {
1020 inset = new InsetParent(inscmd, *this);
1023 if (tmptok == "Quotes") {
1024 inset = new InsetQuotes;
1025 } else if (tmptok == "External") {
1026 inset = new InsetExternal;
1027 } else if (tmptok == "FormulaMacro") {
1028 inset = new InsetFormulaMacro;
1029 } else if (tmptok == "Formula") {
1030 inset = new InsetFormula;
1031 } else if (tmptok == "Figure") {
1032 inset = new InsetFig(100, 100, *this);
1033 } else if (tmptok == "Info") {
1034 inset = new InsetInfo;
1035 } else if (tmptok == "Include") {
1036 InsetCommandParams p( "Include" );
1037 inset = new InsetInclude(p, *this);
1038 } else if (tmptok == "ERT") {
1039 inset = new InsetERT;
1040 } else if (tmptok == "Tabular") {
1041 inset = new InsetTabular(*this);
1042 } else if (tmptok == "Text") {
1043 inset = new InsetText;
1044 } else if (tmptok == "Foot") {
1045 inset = new InsetFoot;
1046 } else if (tmptok == "Marginal") {
1047 inset = new InsetMarginal;
1048 } else if (tmptok == "Minipage") {
1049 inset = new InsetMinipage;
1050 } else if (tmptok == "Float") {
1052 string tmptok = lex.GetString();
1053 inset = new InsetFloat(tmptok);
1054 } else if (tmptok == "List") {
1055 inset = new InsetList;
1056 } else if (tmptok == "Theorem") {
1057 inset = new InsetList;
1058 } else if (tmptok == "Caption") {
1059 inset = new InsetCaption;
1060 } else if (tmptok == "GRAPHICS") {
1061 inset = new InsetGraphics;
1064 if (inset) inset->Read(this, lex);
1068 par->InsertInset(pos, inset, font);
1074 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1078 string const token(lex.GetString());
1079 if (token == "\\lyxformat") { // the first token _must_ be...
1081 string tmp_format = lex.GetString();
1082 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1083 // if present remove ".," from string.
1084 string::size_type dot = tmp_format.find_first_of(".,");
1085 //lyxerr << " dot found at " << dot << endl;
1086 if (dot != string::npos)
1087 tmp_format.erase(dot, 1);
1088 file_format = strToInt(tmp_format);
1089 if (file_format == LYX_FORMAT) {
1091 } else if (file_format > LYX_FORMAT) {
1093 WriteAlert(_("Warning!"),
1094 _("LyX file format is newer that what"),
1095 _("is supported in this LyX version. Expect some problems."));
1097 } else if (file_format < LYX_FORMAT) {
1099 if (file_format < 200) {
1100 WriteAlert(_("ERROR!"),
1101 _("Old LyX file format found. "
1102 "Use LyX 0.10.x to read this!"));
1106 bool the_end = readLyXformat2(lex, par);
1108 // the_end was added in 213
1109 if (file_format < 213)
1113 WriteAlert(_("Warning!"),
1114 _("Reading of document is not complete"),
1115 _("Maybe the document is truncated"));
1117 } else { // "\\lyxformat" not found
1118 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1121 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1127 // Should probably be moved to somewhere else: BufferView? LyXView?
1128 bool Buffer::save() const
1130 // We don't need autosaves in the immediate future. (Asger)
1131 resetAutosaveTimers();
1135 if (lyxrc.make_backup) {
1136 s = fileName() + '~';
1137 if (!lyxrc.backupdir_path.empty())
1138 s = AddName(lyxrc.backupdir_path,
1139 subst(CleanupPath(s),'/','!'));
1141 // Rename is the wrong way of making a backup,
1142 // this is the correct way.
1143 /* truss cp fil fil2:
1144 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1145 stat("LyXVC.lyx", 0xEFFFF688) = 0
1146 open("LyXVC.lyx", O_RDONLY) = 3
1147 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1148 fstat(4, 0xEFFFF508) = 0
1149 fstat(3, 0xEFFFF508) = 0
1150 read(3, " # T h i s f i l e w".., 8192) = 5579
1151 write(4, " # T h i s f i l e w".., 5579) = 5579
1152 read(3, 0xEFFFD4A0, 8192) = 0
1155 chmod("LyXVC3.lyx", 0100644) = 0
1156 lseek(0, 0, SEEK_CUR) = 46440
1160 // Should proabaly have some more error checking here.
1161 // Should be cleaned up in 0.13, at least a bit.
1162 // Doing it this way, also makes the inodes stay the same.
1163 // This is still not a very good solution, in particular we
1164 // might loose the owner of the backup.
1165 FileInfo finfo(fileName());
1166 if (finfo.exist()) {
1167 mode_t fmode = finfo.getMode();
1168 struct utimbuf times = {
1169 finfo.getAccessTime(),
1170 finfo.getModificationTime() };
1172 ifstream ifs(fileName().c_str());
1173 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1178 ::chmod(s.c_str(), fmode);
1180 if (::utime(s.c_str(), ×)) {
1181 lyxerr << "utime error." << endl;
1184 lyxerr << "LyX was not able to make "
1185 "backupcopy. Beware." << endl;
1190 if (writeFile(fileName(), false)) {
1192 removeAutosaveFile(fileName());
1194 // Saving failed, so backup is not backup
1195 if (lyxrc.make_backup) {
1196 lyx::rename(s, fileName());
1204 // Returns false if unsuccesful
1205 bool Buffer::writeFile(string const & fname, bool flag) const
1207 // if flag is false writeFile will not create any GUI
1208 // warnings, only cerr.
1209 // Needed for autosave in background or panic save (Matthias 120496)
1211 if (read_only && (fname == filename)) {
1212 // Here we should come with a question if we should
1213 // perform the write anyway.
1215 lyxerr << _("Error! Document is read-only: ")
1218 WriteAlert(_("Error! Document is read-only: "),
1223 FileInfo finfo(fname);
1224 if (finfo.exist() && !finfo.writable()) {
1225 // Here we should come with a question if we should
1226 // try to do the save anyway. (i.e. do a chmod first)
1228 lyxerr << _("Error! Cannot write file: ")
1231 WriteFSAlert(_("Error! Cannot write file: "),
1236 ofstream ofs(fname.c_str());
1239 lyxerr << _("Error! Cannot open file: ")
1242 WriteFSAlert(_("Error! Cannot open file: "),
1248 // Use the standard "C" locale for file output.
1249 ofs.imbue(std::locale::classic());
1252 // The top of the file should not be written by params.
1254 // write out a comment in the top of the file
1255 ofs << '#' << LYX_DOCVERSION
1256 << " created this file. For more info see http://www.lyx.org/\n"
1257 << "\\lyxformat " << LYX_FORMAT << "\n";
1259 // now write out the buffer paramters.
1260 params.writeFile(ofs);
1262 char footnoteflag = 0;
1265 // this will write out all the paragraphs
1266 // using recursive descent.
1267 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1269 // Write marker that shows file is complete
1270 ofs << "\n\\the_end" << endl;
1274 // how to check if close went ok?
1275 // Following is an attempt... (BE 20001011)
1277 // good() returns false if any error occured, including some
1278 // formatting error.
1279 // bad() returns true if something bad happened in the buffer,
1280 // which should include file system full errors.
1287 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1289 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1299 string const Buffer::asciiParagraph(LyXParagraph const * par,
1300 unsigned int linelen) const
1302 ostringstream buffer;
1305 Inset const * inset;
1308 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1312 int ltype_depth = 0;
1313 unsigned int currlinelen = 0;
1314 bool ref_printed = false;
1320 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1324 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1328 /* begins a footnote environment ? */
1329 if (footnoteflag != par->footnoteflag) {
1330 footnoteflag = par->footnoteflag;
1332 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1333 if ((linelen > 0) &&
1334 ((currlinelen + j) > linelen)) {
1339 << string_footnotekinds[par->footnotekind]
1345 /* begins or ends a deeper area ?*/
1346 if (depth != par->params.depth()) {
1347 if (par->params.depth() > depth) {
1348 while (par->params.depth() > depth) {
1352 while (par->params.depth() < depth) {
1358 /* First write the layout */
1359 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1360 if (tmp == "Itemize") {
1362 ltype_depth = depth+1;
1363 } else if (tmp == "Enumerate") {
1365 ltype_depth = depth+1;
1366 } else if (strstr(tmp.c_str(), "ection")) {
1368 ltype_depth = depth+1;
1369 } else if (strstr(tmp.c_str(), "aragraph")) {
1371 ltype_depth = depth+1;
1372 } else if (tmp == "Description") {
1374 ltype_depth = depth+1;
1375 } else if (tmp == "Abstract") {
1378 } else if (tmp == "Bibliography") {
1386 /* maybe some vertical spaces */
1388 /* the labelwidthstring used in lists */
1392 /* some pagebreaks? */
1396 /* what about the alignment */
1399 /* dummy layout, that means a footnote ended */
1400 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1404 lyxerr << "Should this ever happen?" << endl;
1408 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1409 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1417 for (char j = 0; j < depth; ++j)
1419 currlinelen = depth * 2;
1421 case 0: /* Standard */
1422 case 4: /* (Sub)Paragraph */
1423 case 5: /* Description */
1425 case 6: /* Abstract */
1427 buffer << "Abstract\n\n";
1429 buffer << "Abstract: ";
1431 case 7: /* Bibliography */
1434 buffer << "References\n\n";
1436 buffer << "References: ";
1441 buffer << par->params.labelString() << " ";
1444 if (ltype_depth > depth) {
1445 for (char j = ltype_depth - 1; j > depth; --j)
1447 currlinelen += (ltype_depth-depth)*2;
1450 font2 = par->GetFontSettings(params, i);
1451 if (font1.latex() != font2.latex()) {
1452 if (font2.latex() == LyXFont::OFF)
1459 c = par->GetUChar(params, i);
1463 case LyXParagraph::META_INSET:
1464 if ((inset = par->GetInset(i))) {
1465 if (!inset->Ascii(this, buffer)) {
1467 string s = rsplit(buffer.str().c_str(),
1469 currlinelen += s.length();
1471 // to be sure it breaks paragraph
1472 currlinelen += linelen;
1476 case LyXParagraph::META_NEWLINE:
1479 for (char j = 0; j < depth; ++j)
1482 currlinelen = depth * 2;
1483 if (ltype_depth > depth) {
1484 for (char j = ltype_depth;
1487 currlinelen += (ltype_depth - depth) * 2;
1490 case LyXParagraph::META_HFILL:
1497 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1498 (c == ' ') && ((i + 2) < par->size()))
1501 for (char j = 0; j < depth; ++j)
1503 currlinelen = depth * 2;
1504 if (ltype_depth > depth) {
1505 for (char j = ltype_depth;
1508 currlinelen += (ltype_depth-depth)*2;
1510 } else if (c != '\0')
1513 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1518 return buffer.str().c_str();
1522 void Buffer::writeFileAscii(string const & fname, int linelen)
1524 ofstream ofs(fname.c_str());
1526 WriteFSAlert(_("Error: Cannot write file:"), fname);
1529 writeFileAscii(ofs, linelen);
1533 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1535 LyXParagraph * par = paragraph;
1537 ofs << asciiParagraph(par, linelen);
1545 void Buffer::makeLaTeXFile(string const & fname,
1546 string const & original_path,
1547 bool nice, bool only_body)
1549 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1551 niceFile = nice; // this will be used by Insetincludes.
1553 tex_code_break_column = lyxrc.ascii_linelen;
1555 LyXTextClass const & tclass =
1556 textclasslist.TextClass(params.textclass);
1558 ofstream ofs(fname.c_str());
1560 WriteFSAlert(_("Error: Cannot open file: "), fname);
1564 // validate the buffer.
1565 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1566 LaTeXFeatures features(params, tclass.numLayouts());
1568 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1571 // The starting paragraph of the coming rows is the
1572 // first paragraph of the document. (Asger)
1573 texrow.start(paragraph, 0);
1575 if (!only_body && nice) {
1576 ofs << "%% " LYX_DOCVERSION " created this file. "
1577 "For more info, see http://www.lyx.org/.\n"
1578 "%% Do not edit unless you really know what "
1583 lyxerr.debug() << "lyx header finished" << endl;
1584 // There are a few differences between nice LaTeX and usual files:
1585 // usual is \batchmode and has a
1586 // special input@path to allow the including of figures
1587 // with either \input or \includegraphics (what figinsets do).
1588 // batchmode is not set if there is a tex_code_break_column.
1589 // In this case somebody is interested in the generated LaTeX,
1590 // so this is OK. input@path is set when the actual parameter
1591 // original_path is set. This is done for usual tex-file, but not
1592 // for nice-latex-file. (Matthias 250696)
1595 // code for usual, NOT nice-latex-file
1596 ofs << "\\batchmode\n"; // changed
1597 // from \nonstopmode
1600 if (!original_path.empty()) {
1601 ofs << "\\makeatletter\n"
1602 << "\\def\\input@path{{"
1603 << original_path << "/}}\n"
1604 << "\\makeatother\n";
1610 ofs << "\\documentclass";
1612 string options; // the document class options.
1614 if (tokenPos(tclass.opt_fontsize(),
1615 '|', params.fontsize) >= 0) {
1616 // only write if existing in list (and not default)
1617 options += params.fontsize;
1622 if (!params.use_geometry &&
1623 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1624 switch (params.papersize) {
1625 case BufferParams::PAPER_A4PAPER:
1626 options += "a4paper,";
1628 case BufferParams::PAPER_USLETTER:
1629 options += "letterpaper,";
1631 case BufferParams::PAPER_A5PAPER:
1632 options += "a5paper,";
1634 case BufferParams::PAPER_B5PAPER:
1635 options += "b5paper,";
1637 case BufferParams::PAPER_EXECUTIVEPAPER:
1638 options += "executivepaper,";
1640 case BufferParams::PAPER_LEGALPAPER:
1641 options += "legalpaper,";
1647 if (params.sides != tclass.sides()) {
1648 switch (params.sides) {
1649 case LyXTextClass::OneSide:
1650 options += "oneside,";
1652 case LyXTextClass::TwoSides:
1653 options += "twoside,";
1660 if (params.columns != tclass.columns()) {
1661 if (params.columns == 2)
1662 options += "twocolumn,";
1664 options += "onecolumn,";
1667 if (!params.use_geometry
1668 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1669 options += "landscape,";
1671 // language should be a parameter to \documentclass
1673 string language_options;
1674 if (params.language->babel() == "hebrew"
1675 && default_language->babel() != "hebrew")
1676 // This seems necessary
1677 features.UsedLanguages.insert(default_language);
1679 if (lyxrc.language_use_babel ||
1680 params.language->lang() != lyxrc.default_language ||
1681 !features.UsedLanguages.empty()) {
1683 for (LaTeXFeatures::LanguageList::const_iterator cit =
1684 features.UsedLanguages.begin();
1685 cit != features.UsedLanguages.end(); ++cit)
1686 language_options += (*cit)->babel() + ',';
1687 language_options += params.language->babel();
1688 if (lyxrc.language_global_options)
1689 options += language_options + ',';
1692 // the user-defined options
1693 if (!params.options.empty()) {
1694 options += params.options + ',';
1697 if (!options.empty()){
1698 options = strip(options, ',');
1699 ofs << '[' << options << ']';
1703 << textclasslist.LatexnameOfClass(params.textclass)
1706 // end of \documentclass defs
1708 // font selection must be done before loading fontenc.sty
1709 // The ae package is not needed when using OT1 font encoding.
1710 if (params.fonts != "default" &&
1711 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1712 ofs << "\\usepackage{" << params.fonts << "}\n";
1714 if (params.fonts == "ae") {
1715 ofs << "\\usepackage{aecompl}\n";
1719 // this one is not per buffer
1720 if (lyxrc.fontenc != "default") {
1721 ofs << "\\usepackage[" << lyxrc.fontenc
1726 if (params.inputenc == "auto") {
1727 string const doc_encoding =
1728 params.language->encoding()->LatexName();
1730 // Create a list with all the input encodings used
1732 set<string> encodings;
1733 for (LaTeXFeatures::LanguageList::const_iterator it =
1734 features.UsedLanguages.begin();
1735 it != features.UsedLanguages.end(); ++it)
1736 if ((*it)->encoding()->LatexName() != doc_encoding)
1737 encodings.insert((*it)->encoding()->LatexName());
1739 ofs << "\\usepackage[";
1740 std::copy(encodings.begin(), encodings.end(),
1741 std::ostream_iterator<string>(ofs, ","));
1742 ofs << doc_encoding << "]{inputenc}\n";
1744 } else if (params.inputenc != "default") {
1745 ofs << "\\usepackage[" << params.inputenc
1750 // At the very beginning the text parameters.
1751 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1752 switch (params.paperpackage) {
1753 case BufferParams::PACKAGE_A4:
1754 ofs << "\\usepackage{a4}\n";
1757 case BufferParams::PACKAGE_A4WIDE:
1758 ofs << "\\usepackage{a4wide}\n";
1761 case BufferParams::PACKAGE_WIDEMARGINSA4:
1762 ofs << "\\usepackage[widemargins]{a4}\n";
1767 if (params.use_geometry) {
1768 ofs << "\\usepackage{geometry}\n";
1770 ofs << "\\geometry{verbose";
1771 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1772 ofs << ",landscape";
1773 switch (params.papersize2) {
1774 case BufferParams::VM_PAPER_CUSTOM:
1775 if (!params.paperwidth.empty())
1776 ofs << ",paperwidth="
1777 << params.paperwidth;
1778 if (!params.paperheight.empty())
1779 ofs << ",paperheight="
1780 << params.paperheight;
1782 case BufferParams::VM_PAPER_USLETTER:
1783 ofs << ",letterpaper";
1785 case BufferParams::VM_PAPER_USLEGAL:
1786 ofs << ",legalpaper";
1788 case BufferParams::VM_PAPER_USEXECUTIVE:
1789 ofs << ",executivepaper";
1791 case BufferParams::VM_PAPER_A3:
1794 case BufferParams::VM_PAPER_A4:
1797 case BufferParams::VM_PAPER_A5:
1800 case BufferParams::VM_PAPER_B3:
1803 case BufferParams::VM_PAPER_B4:
1806 case BufferParams::VM_PAPER_B5:
1810 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1811 switch (lyxrc.default_papersize) {
1812 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1813 case BufferParams::PAPER_USLETTER:
1814 ofs << ",letterpaper";
1816 case BufferParams::PAPER_LEGALPAPER:
1817 ofs << ",legalpaper";
1819 case BufferParams::PAPER_EXECUTIVEPAPER:
1820 ofs << ",executivepaper";
1822 case BufferParams::PAPER_A3PAPER:
1825 case BufferParams::PAPER_A4PAPER:
1828 case BufferParams::PAPER_A5PAPER:
1831 case BufferParams::PAPER_B5PAPER:
1836 if (!params.topmargin.empty())
1837 ofs << ",tmargin=" << params.topmargin;
1838 if (!params.bottommargin.empty())
1839 ofs << ",bmargin=" << params.bottommargin;
1840 if (!params.leftmargin.empty())
1841 ofs << ",lmargin=" << params.leftmargin;
1842 if (!params.rightmargin.empty())
1843 ofs << ",rmargin=" << params.rightmargin;
1844 if (!params.headheight.empty())
1845 ofs << ",headheight=" << params.headheight;
1846 if (!params.headsep.empty())
1847 ofs << ",headsep=" << params.headsep;
1848 if (!params.footskip.empty())
1849 ofs << ",footskip=" << params.footskip;
1853 if (features.amsstyle
1854 && !tclass.provides(LyXTextClass::amsmath)) {
1855 ofs << "\\usepackage{amsmath}\n";
1859 if (tokenPos(tclass.opt_pagestyle(),
1860 '|', params.pagestyle) >= 0) {
1861 if (params.pagestyle == "fancy") {
1862 ofs << "\\usepackage{fancyhdr}\n";
1865 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1869 // We try to load babel late, in case it interferes
1870 // with other packages.
1872 string tmp = lyxrc.language_package;
1873 if (!lyxrc.language_global_options
1874 && tmp == "\\usepackage{babel}")
1875 tmp = "\\usepackage[" +
1876 language_options + "]{babel}";
1881 if (params.secnumdepth != tclass.secnumdepth()) {
1882 ofs << "\\setcounter{secnumdepth}{"
1883 << params.secnumdepth
1887 if (params.tocdepth != tclass.tocdepth()) {
1888 ofs << "\\setcounter{tocdepth}{"
1894 if (params.paragraph_separation) {
1895 switch (params.defskip.kind()) {
1896 case VSpace::SMALLSKIP:
1897 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1899 case VSpace::MEDSKIP:
1900 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1902 case VSpace::BIGSKIP:
1903 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1905 case VSpace::LENGTH:
1906 ofs << "\\setlength\\parskip{"
1907 << params.defskip.length().asLatexString()
1910 default: // should never happen // Then delete it.
1911 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1916 ofs << "\\setlength\\parindent{0pt}\n";
1920 // Now insert the LyX specific LaTeX commands...
1922 // The optional packages;
1923 string preamble(features.getPackages());
1925 // this might be useful...
1926 preamble += "\n\\makeatletter\n";
1928 // Some macros LyX will need
1929 string tmppreamble(features.getMacros());
1931 if (!tmppreamble.empty()) {
1932 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1933 "LyX specific LaTeX commands.\n"
1934 + tmppreamble + '\n';
1937 // the text class specific preamble
1938 tmppreamble = features.getTClassPreamble();
1939 if (!tmppreamble.empty()) {
1940 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1941 "Textclass specific LaTeX commands.\n"
1942 + tmppreamble + '\n';
1945 /* the user-defined preamble */
1946 if (!params.preamble.empty()) {
1947 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1948 "User specified LaTeX commands.\n"
1949 + params.preamble + '\n';
1952 preamble += "\\makeatother\n";
1954 // Itemize bullet settings need to be last in case the user
1955 // defines their own bullets that use a package included
1956 // in the user-defined preamble -- ARRae
1957 // Actually it has to be done much later than that
1958 // since some packages like frenchb make modifications
1959 // at \begin{document} time -- JMarc
1961 for (int i = 0; i < 4; ++i) {
1962 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1963 if (bullets_def.empty())
1964 bullets_def="\\AtBeginDocument{\n";
1965 bullets_def += " \\renewcommand{\\labelitemi";
1967 // `i' is one less than the item to modify
1974 bullets_def += "ii";
1980 bullets_def += "}{" +
1981 params.user_defined_bullets[i].getText()
1986 if (!bullets_def.empty())
1987 preamble += bullets_def + "}\n\n";
1989 for (int j = countChar(preamble, '\n'); j-- ;) {
1996 ofs << "\\begin{document}\n";
1999 lyxerr.debug() << "preamble finished, now the body." << endl;
2001 if (!lyxrc.language_auto_begin) {
2002 ofs << subst(lyxrc.language_command_begin, "$$lang",
2003 params.language->babel())
2008 latexParagraphs(ofs, paragraph, 0, texrow);
2010 // add this just in case after all the paragraphs
2014 if (!lyxrc.language_auto_end) {
2015 ofs << subst(lyxrc.language_command_end, "$$lang",
2016 params.language->babel())
2022 ofs << "\\end{document}\n";
2025 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2027 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2031 // Just to be sure. (Asger)
2034 // tex_code_break_column's value is used to decide
2035 // if we are in batchmode or not (within mathed_write()
2036 // in math_write.C) so we must set it to a non-zero
2037 // value when we leave otherwise we save incorrect .lyx files.
2038 tex_code_break_column = lyxrc.ascii_linelen;
2042 lyxerr << "File was not closed properly." << endl;
2045 lyxerr.debug() << "Finished making latex file." << endl;
2050 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2052 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2053 LyXParagraph * endpar, TexRow & texrow) const
2055 bool was_title = false;
2056 bool already_title = false;
2057 std::ostringstream ftnote;
2062 while (par != endpar) {
2065 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2068 LyXLayout const & layout =
2069 textclasslist.Style(params.textclass,
2072 if (layout.intitle) {
2073 if (already_title) {
2074 lyxerr <<"Error in latexParagraphs: You"
2075 " should not mix title layouts"
2076 " with normal ones." << endl;
2079 } else if (was_title && !already_title) {
2080 ofs << "\\maketitle\n";
2082 already_title = true;
2085 // We are at depth 0 so we can just use
2086 // ordinary \footnote{} generation
2087 // flag this with ftcount
2089 if (layout.isEnvironment()
2090 || par->params.pextraType() != LyXParagraph::PEXTRA_NONE) {
2091 par = par->TeXEnvironment(this, params, ofs, texrow
2093 ,ftnote, ft_texrow, ftcount
2097 par = par->TeXOnePar(this, params, ofs, texrow, false
2100 ftnote, ft_texrow, ftcount
2105 // Write out what we've generated...
2108 ofs << "\\addtocounter{footnote}{-"
2112 ofs << ftnote.str();
2113 texrow += ft_texrow;
2115 // The extra .c_str() is needed when we use
2116 // lyxstring instead of the STL string class.
2117 ftnote.str(string().c_str());
2122 // It might be that we only have a title in this document
2123 if (was_title && !already_title) {
2124 ofs << "\\maketitle\n";
2130 bool Buffer::isLatex() const
2132 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2136 bool Buffer::isLinuxDoc() const
2138 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2142 bool Buffer::isLiterate() const
2144 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2148 bool Buffer::isDocBook() const
2150 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2154 bool Buffer::isSGML() const
2156 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2157 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2161 void Buffer::sgmlOpenTag(ostream & os, int depth,
2162 string const & latexname) const
2164 if (latexname != "!-- --")
2165 os << string(depth, ' ') << "<" << latexname << ">\n";
2169 void Buffer::sgmlCloseTag(ostream & os, int depth,
2170 string const & latexname) const
2172 if (latexname != "!-- --")
2173 os << string(depth, ' ') << "</" << latexname << ">\n";
2177 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2179 LyXParagraph * par = paragraph;
2181 niceFile = nice; // this will be used by Insetincludes.
2183 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2184 string environment_stack[10];
2187 int depth = 0; // paragraph depth
2189 ofstream ofs(fname.c_str());
2192 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2196 LyXTextClass const & tclass =
2197 textclasslist.TextClass(params.textclass);
2199 LaTeXFeatures features(params, tclass.numLayouts());
2203 tex_code_break_column = lyxrc.ascii_linelen;
2205 //tex_code_break_column = 0;
2210 string sgml_includedfiles=features.getIncludedFiles(fname);
2212 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2213 ofs << "<!doctype linuxdoc system>\n\n";
2215 ofs << "<!doctype linuxdoc system [ "
2216 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2219 if (params.options.empty())
2220 sgmlOpenTag(ofs, 0, top_element);
2222 string top = top_element;
2224 top += params.options;
2225 sgmlOpenTag(ofs, 0, top);
2229 ofs << "<!-- " << LYX_DOCVERSION
2230 << " created this file. For more info see http://www.lyx.org/"
2234 int desc_on = 0; // description mode
2235 LyXLayout const & style =
2236 textclasslist.Style(params.textclass,
2239 // treat <toc> as a special case for compatibility with old code
2240 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2241 Inset * inset = par->GetInset(0);
2242 Inset::Code lyx_code = inset->LyxCode();
2243 if (lyx_code == Inset::TOC_CODE){
2244 string const temp = "toc";
2245 sgmlOpenTag(ofs, depth, temp);
2249 linuxDocHandleFootnote(ofs, par, depth);
2255 // environment tag closing
2256 for (; depth > par->params.depth(); --depth) {
2257 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2258 environment_stack[depth].erase();
2261 // write opening SGML tags
2262 switch (style.latextype) {
2263 case LATEX_PARAGRAPH:
2264 if (depth == par->params.depth()
2265 && !environment_stack[depth].empty()) {
2266 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2267 environment_stack[depth].erase();
2273 sgmlOpenTag(ofs, depth, style.latexname());
2278 LinuxDocError(par, 0,
2279 _("Error : Wrong depth for"
2280 " LatexType Command.\n"));
2282 if (!environment_stack[depth].empty()){
2283 sgmlCloseTag(ofs, depth,
2284 environment_stack[depth]);
2288 environment_stack[depth].erase();
2289 sgmlOpenTag(ofs, depth, style.latexname());
2292 case LATEX_ENVIRONMENT:
2293 case LATEX_ITEM_ENVIRONMENT:
2294 if (depth == par->params.depth()
2295 && environment_stack[depth] != style.latexname()
2296 && !environment_stack[depth].empty()) {
2298 sgmlCloseTag(ofs, depth,
2299 environment_stack[depth]);
2300 environment_stack[depth].erase();
2302 if (depth < par->params.depth()) {
2303 depth = par->params.depth();
2304 environment_stack[depth].erase();
2306 if (environment_stack[depth] != style.latexname()) {
2308 string const temp = "p";
2309 sgmlOpenTag(ofs, depth, temp);
2311 environment_stack[depth] = style.latexname();
2312 sgmlOpenTag(ofs, depth,
2313 environment_stack[depth]);
2315 if (style.latextype == LATEX_ENVIRONMENT) break;
2317 desc_on = (style.labeltype == LABEL_MANUAL);
2324 sgmlOpenTag(ofs, depth + 1, item_name);
2327 sgmlOpenTag(ofs, depth, style.latexname());
2334 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2338 linuxDocHandleFootnote(ofs, par, depth);
2340 while(par && par->IsDummy());
2344 // write closing SGML tags
2345 switch (style.latextype) {
2347 case LATEX_ENVIRONMENT:
2348 case LATEX_ITEM_ENVIRONMENT:
2351 sgmlCloseTag(ofs, depth, style.latexname());
2357 for (; depth > 0; --depth)
2358 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2360 if (!environment_stack[depth].empty())
2361 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2365 sgmlCloseTag(ofs, 0, top_element);
2369 // How to check for successful close
2374 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2377 string const tag = "footnote";
2379 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2380 sgmlOpenTag(os, depth + 1, tag);
2381 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2382 sgmlCloseTag(os, depth + 1, tag);
2389 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2390 int depth, int desc_on,
2391 LyXParagraph * & par)
2393 LyXParagraph * tpar = par;
2396 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2398 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2402 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2403 "Caption").second) {
2404 sgmlOpenTag(os, depth + 1, inner_tag);
2406 SimpleDocBookOnePar(os, extra_par, tpar,
2407 desc_on, depth + 2);
2408 sgmlCloseTag(os, depth+1, inner_tag);
2409 if (!extra_par.empty())
2416 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2419 string tag, inner_tag;
2420 string tmp_par, extra_par;
2421 bool inner_span = false;
2424 // Someone should give this enum a proper name (Lgb)
2432 SOME_ENUM last = NO_ONE;
2433 SOME_ENUM present = FOOTNOTE_LIKE;
2435 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2436 if (last == present) {
2438 if (!tmp_par.empty()) {
2441 sgmlCloseTag(os, depth + 1, inner_tag);
2442 sgmlOpenTag(os, depth + 1, inner_tag);
2449 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2451 if (!extra_par.empty()) os << extra_par;
2452 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2455 switch (par->footnotekind) {
2456 case LyXParagraph::FOOTNOTE:
2457 case LyXParagraph::ALGORITHM:
2460 present = FOOTNOTE_LIKE;
2463 case LyXParagraph::MARGIN:
2466 present = MARGIN_LIKE;
2469 case LyXParagraph::FIG:
2470 case LyXParagraph::WIDE_FIG:
2472 inner_tag = "title";
2476 case LyXParagraph::TAB:
2477 case LyXParagraph::WIDE_TAB:
2479 inner_tag = "title";
2484 sgmlOpenTag(os, depth, tag);
2485 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2486 DocBookHandleCaption(os, inner_tag, depth,
2490 sgmlOpenTag(os, depth + 1, inner_tag);
2493 // ignore all caption here, we processed them above!!!
2494 if (par->layout != textclasslist
2495 .NumberOfLayout(params.textclass,
2496 "Caption").second) {
2497 std::ostringstream ost;
2498 SimpleDocBookOnePar(ost, extra_par, par,
2499 desc_on, depth + 2);
2500 tmp_par += ost.str().c_str();
2502 tmp_par = frontStrip(strip(tmp_par));
2508 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2509 if (!extra_par.empty()) os << extra_par;
2510 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2515 // push a tag in a style stack
2516 void Buffer::push_tag(ostream & os, string const & tag,
2517 int & pos, char stack[5][3])
2519 #ifdef WITH_WARNINGS
2520 #warning Use a real stack! (Lgb)
2522 // pop all previous tags
2523 for (int j = pos; j >= 0; --j)
2524 os << "</" << stack[j] << ">";
2527 sprintf(stack[++pos], "%s", tag.c_str());
2530 for (int i = 0; i <= pos; ++i)
2531 os << "<" << stack[i] << ">";
2535 void Buffer::pop_tag(ostream & os, string const & tag,
2536 int & pos, char stack[5][3])
2538 #ifdef WITH_WARNINGS
2539 #warning Use a real stack! (Lgb)
2541 // Please, Lars, do not remove the global variable. I already
2542 // had to reintroduce it twice! (JMarc)
2543 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2547 // pop all tags till specified one
2548 for (j = pos; (j >= 0) && tag != stack[j]; --j)
2549 os << "</" << stack[j] << ">";
2552 os << "</" << tag << ">";
2554 // push all tags, but the specified one
2555 for (j = j + 1; j <= pos; ++j) {
2556 os << "<" << stack[j] << ">";
2557 strcpy(stack[j - 1], stack[j]);
2561 // pop all tags till specified one
2563 for (int j = pos; (j >= 0) && tag != stack[j]; --j)
2564 os << "</" << stack[j] << ">";
2567 os << "</" << tag << ">";
2569 // push all tags, but the specified one
2570 for (int i = j + 1; i <= pos; ++i) {
2571 os << "<" << stack[i] << ">";
2572 strcpy(stack[i - 1], stack[i]);
2579 // Handle internal paragraph parsing -- layout already processed.
2581 // checks, if newcol chars should be put into this line
2582 // writes newline, if necessary.
2584 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2585 string::size_type newcol)
2588 if (colcount > lyxrc.ascii_linelen) {
2590 colcount = newcol; // assume write after this call
2595 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2596 int desc_on, int /*depth*/)
2601 LyXParagraph::size_type main_body;
2603 LyXLayout const & style = textclasslist.Style(params.textclass,
2606 char family_type = 0; // family font flag
2607 bool is_bold = false; // series font flag
2608 char shape_type = 0; // shape font flag
2609 bool is_em = false; // emphasis (italic) font flag
2611 int stack_num = -1; // style stack position
2612 // Can this be rewritten to use a std::stack, please. (Lgb)
2613 char stack[5][3]; // style stack
2614 string::size_type char_line_count = 5; // Heuristic choice ;-)
2616 if (style.labeltype != LABEL_MANUAL)
2619 main_body = par->BeginningOfMainBody();
2621 // gets paragraph main font
2623 font1 = style.labelfont;
2628 // parsing main loop
2629 for (LyXParagraph::size_type i = 0;
2630 i < par->size(); ++i) {
2642 LyXFont const font2 = par->getFont(params, i);
2644 if (font1.family() != font2.family()) {
2645 switch (family_type) {
2647 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2648 push_tag(os, "tt", stack_num, stack);
2651 else if (font2.family() == LyXFont::SANS_FAMILY) {
2652 push_tag(os, "sf", stack_num, stack);
2657 pop_tag(os, "tt", stack_num, stack);
2658 if (font2.family() == LyXFont::SANS_FAMILY) {
2659 push_tag(os, "sf", stack_num, stack);
2666 pop_tag(os, "sf", stack_num, stack);
2667 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2668 push_tag(os, "tt", stack_num, stack);
2677 if (font1.series() != font2.series()) {
2678 if (font2.series() == LyXFont::BOLD_SERIES) {
2679 push_tag(os, "bf", stack_num, stack);
2681 } else if (is_bold) {
2682 pop_tag(os, "bf", stack_num, stack);
2687 // handle italic and slanted fonts
2688 if (font1.shape() != font2.shape()) {
2689 switch (shape_type) {
2691 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2692 push_tag(os, "it", stack_num, stack);
2694 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2695 push_tag(os, "sl", stack_num, stack);
2700 pop_tag(os, "it", stack_num, stack);
2701 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2702 push_tag(os, "sl", stack_num, stack);
2709 pop_tag(os, "sl", stack_num, stack);
2710 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2711 push_tag(os, "it", stack_num, stack);
2719 if (font1.emph() != font2.emph()) {
2720 if (font2.emph() == LyXFont::ON) {
2721 push_tag(os, "em", stack_num, stack);
2724 pop_tag(os, "em", stack_num, stack);
2729 c = par->GetChar(i);
2731 if (c == LyXParagraph::META_INSET) {
2732 inset = par->GetInset(i);
2733 inset->Linuxdoc(this, os);
2736 if (font2.latex() == LyXFont::ON) {
2737 // "TeX"-Mode on == > SGML-Mode on.
2739 os << c; // see LaTeX-Generation...
2743 if (par->linuxDocConvertChar(c, sgml_string)
2744 && !style.free_spacing) { // in freespacing
2746 // non-breaking characters
2750 linux_doc_line_break(os, char_line_count, 6);
2754 linux_doc_line_break(os, char_line_count, 1);
2759 char_line_count += sgml_string.length();
2765 // needed if there is an optional argument but no contents
2766 if (main_body > 0 && main_body == par->size()) {
2770 // pop all defined Styles
2771 for (j = stack_num; j >= 0; --j) {
2772 linux_doc_line_break(os,
2774 3 + strlen(stack[j]));
2775 os << "</" << stack[j] << ">";
2778 // resets description flag correctly
2781 // <tag> not closed...
2782 linux_doc_line_break(os, char_line_count, 6);
2786 // fprintf(file, "</p>");
2792 // Print an error message.
2793 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2794 string const & message)
2796 // insert an error marker in text
2797 InsetError * new_inset = new InsetError(message);
2798 par->InsertInset(pos, new_inset);
2801 // This constant defines the maximum number of
2802 // environment layouts that can be nesteded.
2803 // The same applies for command layouts.
2804 // These values should be more than enough.
2805 // José Matos (1999/07/22)
2807 enum { MAX_NEST_LEVEL = 25};
2809 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2811 LyXParagraph * par = paragraph;
2813 niceFile = nice; // this will be used by Insetincludes.
2815 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2816 // Please use a real stack.
2817 string environment_stack[MAX_NEST_LEVEL];
2818 string environment_inner[MAX_NEST_LEVEL];
2819 // Please use a real stack.
2820 string command_stack[MAX_NEST_LEVEL];
2821 bool command_flag= false;
2822 int command_depth= 0, command_base= 0, cmd_depth= 0;
2824 string item_name, command_name;
2825 string c_depth, c_params, tmps;
2827 int depth = 0; // paragraph depth
2828 LyXTextClass const & tclass =
2829 textclasslist.TextClass(params.textclass);
2831 LaTeXFeatures features(params, tclass.numLayouts());
2835 tex_code_break_column = lyxrc.ascii_linelen;
2837 //tex_code_break_column = 0;
2839 ofstream ofs(fname.c_str());
2841 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2848 string sgml_includedfiles=features.getIncludedFiles(fname);
2850 ofs << "<!doctype " << top_element
2851 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2853 if (params.preamble.empty() && sgml_includedfiles.empty())
2856 ofs << "\n [ " << params.preamble
2857 << sgml_includedfiles << " \n]>\n\n";
2860 string top = top_element;
2862 top += params.language->code();
2865 if (!params.options.empty()) {
2867 top += params.options;
2869 sgmlOpenTag(ofs, 0, top);
2871 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2872 << "\n See http://www.lyx.org/ for more information -->\n";
2875 int desc_on = 0; // description mode
2876 LyXLayout const & style =
2877 textclasslist.Style(params.textclass,
2880 // environment tag closing
2881 for (; depth > par->params.depth(); --depth) {
2882 if (environment_inner[depth] != "!-- --") {
2883 item_name= "listitem";
2884 sgmlCloseTag(ofs, command_depth + depth,
2886 if (environment_inner[depth] == "varlistentry")
2887 sgmlCloseTag(ofs, depth+command_depth,
2888 environment_inner[depth]);
2890 sgmlCloseTag(ofs, depth + command_depth,
2891 environment_stack[depth]);
2892 environment_stack[depth].erase();
2893 environment_inner[depth].erase();
2896 if (depth == par->params.depth()
2897 && environment_stack[depth] != style.latexname()
2898 && !environment_stack[depth].empty()) {
2899 if (environment_inner[depth] != "!-- --") {
2900 item_name= "listitem";
2901 sgmlCloseTag(ofs, command_depth+depth,
2903 if (environment_inner[depth] == "varlistentry")
2905 depth + command_depth,
2906 environment_inner[depth]);
2909 sgmlCloseTag(ofs, depth + command_depth,
2910 environment_stack[depth]);
2912 environment_stack[depth].erase();
2913 environment_inner[depth].erase();
2916 // Write opening SGML tags.
2917 switch (style.latextype) {
2918 case LATEX_PARAGRAPH:
2919 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2924 LinuxDocError(par, 0,
2925 _("Error : Wrong depth for "
2926 "LatexType Command.\n"));
2928 command_name = style.latexname();
2930 tmps = style.latexparam();
2931 c_params = split(tmps, c_depth,'|');
2933 cmd_depth= lyx::atoi(c_depth);
2936 if (cmd_depth<command_base) {
2937 for (int j = command_depth;
2938 j >= command_base; --j)
2939 if (!command_stack[j].empty())
2940 sgmlCloseTag(ofs, j, command_stack[j]);
2941 command_depth= command_base= cmd_depth;
2942 } else if (cmd_depth <= command_depth) {
2943 for (int j = command_depth;
2944 j >= cmd_depth; --j)
2946 if (!command_stack[j].empty())
2947 sgmlCloseTag(ofs, j, command_stack[j]);
2948 command_depth= cmd_depth;
2950 command_depth= cmd_depth;
2952 command_depth = command_base = cmd_depth;
2953 command_flag = true;
2955 command_stack[command_depth]= command_name;
2957 // treat label as a special case for
2958 // more WYSIWYM handling.
2959 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2960 Inset * inset = par->GetInset(0);
2961 Inset::Code lyx_code = inset->LyxCode();
2962 if (lyx_code == Inset::LABEL_CODE){
2963 command_name += " id=\"";
2964 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2965 command_name += "\"";
2970 sgmlOpenTag(ofs, depth + command_depth, command_name);
2971 if (c_params.empty())
2972 item_name = "title";
2974 item_name = c_params;
2975 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2978 case LATEX_ENVIRONMENT:
2979 case LATEX_ITEM_ENVIRONMENT:
2980 if (depth < par->params.depth()) {
2981 depth = par->params.depth();
2982 environment_stack[depth].erase();
2985 if (environment_stack[depth] != style.latexname()) {
2986 environment_stack[depth] = style.latexname();
2987 environment_inner[depth] = "!-- --";
2988 sgmlOpenTag(ofs, depth + command_depth,
2989 environment_stack[depth]);
2991 if (environment_inner[depth] != "!-- --") {
2992 item_name= "listitem";
2994 command_depth + depth,
2996 if (environment_inner[depth] == "varlistentry")
2998 depth + command_depth,
2999 environment_inner[depth]);
3003 if (style.latextype == LATEX_ENVIRONMENT) {
3004 if (!style.latexparam().empty()) {
3005 if(style.latexparam() == "CDATA")
3006 ofs << "<![ CDATA [";
3008 sgmlOpenTag(ofs, depth + command_depth,
3009 style.latexparam());
3014 desc_on = (style.labeltype == LABEL_MANUAL);
3017 environment_inner[depth]= "varlistentry";
3019 environment_inner[depth]= "listitem";
3021 sgmlOpenTag(ofs, depth + 1 + command_depth,
3022 environment_inner[depth]);
3026 sgmlOpenTag(ofs, depth + 1 + command_depth,
3030 sgmlOpenTag(ofs, depth + 1 + command_depth,
3035 sgmlOpenTag(ofs, depth + command_depth,
3044 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3045 depth + 1 + command_depth);
3048 DocBookHandleFootnote(ofs, par,
3049 depth + 1 + command_depth);
3051 while(par && par->IsDummy());
3054 // write closing SGML tags
3055 switch (style.latextype) {
3057 if (c_params.empty())
3061 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3063 case LATEX_ENVIRONMENT:
3064 if (!style.latexparam().empty()) {
3065 if(style.latexparam() == "CDATA")
3068 sgmlCloseTag(ofs, depth + command_depth,
3069 style.latexparam());
3072 case LATEX_ITEM_ENVIRONMENT:
3073 if (desc_on == 1) break;
3075 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3077 case LATEX_PARAGRAPH:
3078 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3081 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3087 for (; depth >= 0; --depth) {
3088 if (!environment_stack[depth].empty()) {
3089 if (environment_inner[depth] != "!-- --") {
3090 item_name= "listitem";
3091 sgmlCloseTag(ofs, command_depth + depth,
3093 if (environment_inner[depth] == "varlistentry")
3094 sgmlCloseTag(ofs, depth + command_depth,
3095 environment_inner[depth]);
3098 sgmlCloseTag(ofs, depth + command_depth,
3099 environment_stack[depth]);
3103 for (int j = command_depth; j >= command_base; --j)
3104 if (!command_stack[j].empty())
3105 sgmlCloseTag(ofs, j, command_stack[j]);
3108 sgmlCloseTag(ofs, 0, top_element);
3111 // How to check for successful close
3115 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3116 LyXParagraph * par, int & desc_on,
3119 bool emph_flag = false;
3121 LyXLayout const & style = textclasslist.Style(params.textclass,
3124 LyXParagraph::size_type main_body;
3125 if (style.labeltype != LABEL_MANUAL)
3128 main_body = par->BeginningOfMainBody();
3130 // gets paragraph main font
3131 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3133 int char_line_count = depth;
3134 if (!style.free_spacing)
3135 for (int j = 0; j < depth; ++j)
3138 // parsing main loop
3139 for (LyXParagraph::size_type i = 0;
3140 i < par->size(); ++i) {
3141 LyXFont font2 = par->getFont(params, i);
3143 // handle <emphasis> tag
3144 if (font1.emph() != font2.emph() && i) {
3145 if (font2.emph() == LyXFont::ON) {
3149 os << "</emphasis>";
3154 char c = par->GetChar(i);
3156 if (c == LyXParagraph::META_INSET) {
3157 Inset * inset = par->GetInset(i);
3158 std::ostringstream ost;
3159 inset->DocBook(this, ost);
3160 string tmp_out = ost.str().c_str();
3163 // This code needs some explanation:
3164 // Two insets are treated specially
3165 // label if it is the first element in a command paragraph
3167 // graphics inside tables or figure floats can't go on
3168 // title (the equivalente in latex for this case is caption
3169 // and title should come first
3172 if (desc_on!= 3 || i!= 0) {
3173 if (!tmp_out.empty() && tmp_out[0] == '@') {
3175 extra += frontStrip(tmp_out, '@');
3177 os << frontStrip(tmp_out, '@');
3182 } else if (font2.latex() == LyXFont::ON) {
3183 // "TeX"-Mode on ==> SGML-Mode on.
3189 if (par->linuxDocConvertChar(c, sgml_string)
3190 && !style.free_spacing) { // in freespacing
3192 // non-breaking characters
3196 os << "\n</term><listitem><para>";
3208 // needed if there is an optional argument but no contents
3209 if (main_body > 0 && main_body == par->size()) {
3213 os << "</emphasis>";
3216 // resets description flag correctly
3219 // <term> not closed...
3227 // This should be enabled when the Chktex class is implemented. (Asger)
3228 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3229 // Other flags: -wall -v0 -x
3230 int Buffer::runChktex()
3232 if (!users->text) return 0;
3234 ProhibitInput(users);
3236 // get LaTeX-Filename
3237 string const name = getLatexName();
3238 string path = OnlyPath(filename);
3240 string const org_path = path;
3241 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3245 Path p(path); // path to LaTeX file
3246 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3248 // Remove all error insets
3249 bool const removedErrorInsets = users->removeAutoInsets();
3251 // Generate the LaTeX file if neccessary
3252 makeLaTeXFile(name, org_path, false);
3255 Chktex chktex(lyxrc.chktex_command, name, filepath);
3256 int res = chktex.run(terr); // run chktex
3259 WriteAlert(_("chktex did not work!"),
3260 _("Could not run with file:"), name);
3261 } else if (res > 0) {
3262 // Insert all errors as errors boxes
3263 users->insertErrors(terr);
3266 // if we removed error insets before we ran chktex or if we inserted
3267 // error insets after we ran chktex, this must be run:
3268 if (removedErrorInsets || res){
3270 users->fitCursor(users->text);
3278 void Buffer::validate(LaTeXFeatures & features) const
3280 LyXParagraph * par = paragraph;
3281 LyXTextClass const & tclass =
3282 textclasslist.TextClass(params.textclass);
3284 // AMS Style is at document level
3286 features.amsstyle = (params.use_amsmath ||
3287 tclass.provides(LyXTextClass::amsmath));
3290 // We don't use "lyxerr.debug" because of speed. (Asger)
3291 if (lyxerr.debugging(Debug::LATEX))
3292 lyxerr << "Paragraph: " << par << endl;
3294 // Now just follow the list of paragraphs and run
3295 // validate on each of them.
3296 par->validate(features);
3298 // and then the next paragraph
3302 // the bullet shapes are buffer level not paragraph level
3303 // so they are tested here
3304 for (int i = 0; i < 4; ++i) {
3305 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3306 int const font = params.user_defined_bullets[i].getFont();
3308 int const c = params
3309 .user_defined_bullets[i]
3316 features.latexsym = true;
3318 } else if (font == 1) {
3319 features.amssymb = true;
3320 } else if ((font >= 2 && font <= 5)) {
3321 features.pifont = true;
3326 if (lyxerr.debugging(Debug::LATEX)) {
3327 features.showStruct();
3332 void Buffer::setPaperStuff()
3334 params.papersize = BufferParams::PAPER_DEFAULT;
3335 char const c1 = params.paperpackage;
3336 if (c1 == BufferParams::PACKAGE_NONE) {
3337 char const c2 = params.papersize2;
3338 if (c2 == BufferParams::VM_PAPER_USLETTER)
3339 params.papersize = BufferParams::PAPER_USLETTER;
3340 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3341 params.papersize = BufferParams::PAPER_LEGALPAPER;
3342 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3343 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3344 else if (c2 == BufferParams::VM_PAPER_A3)
3345 params.papersize = BufferParams::PAPER_A3PAPER;
3346 else if (c2 == BufferParams::VM_PAPER_A4)
3347 params.papersize = BufferParams::PAPER_A4PAPER;
3348 else if (c2 == BufferParams::VM_PAPER_A5)
3349 params.papersize = BufferParams::PAPER_A5PAPER;
3350 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3351 (c2 == BufferParams::VM_PAPER_B5))
3352 params.papersize = BufferParams::PAPER_B5PAPER;
3353 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3354 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3355 params.papersize = BufferParams::PAPER_A4PAPER;
3359 // This function should be in Buffer because it's a buffer's property (ale)
3360 string const Buffer::getIncludeonlyList(char delim)
3363 for (inset_iterator it = inset_iterator_begin();
3364 it != inset_iterator_end(); ++it) {
3365 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3366 InsetInclude * insetinc =
3367 static_cast<InsetInclude *>(*it);
3368 if (insetinc->isInclude()
3369 && insetinc->isNoLoad()) {
3372 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3376 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3381 vector<string> const Buffer::getLabelList()
3383 /// if this is a child document and the parent is already loaded
3384 /// Use the parent's list instead [ale990407]
3385 if (!params.parentname.empty()
3386 && bufferlist.exists(params.parentname)) {
3387 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3389 return tmp->getLabelList();
3392 vector<string> label_list;
3393 for (inset_iterator it = inset_iterator_begin();
3394 it != inset_iterator_end(); ++it) {
3395 vector<string> const l = (*it)->getLabelList();
3396 label_list.insert(label_list.end(), l.begin(), l.end());
3402 vector<vector<Buffer::TocItem> > const Buffer::getTocList() const
3407 vector<vector<TocItem> > l(4);
3408 LyXParagraph * par = paragraph;
3411 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3412 if (textclasslist.Style(params.textclass,
3413 par->GetLayout()).labeltype
3414 == LABEL_SENSITIVE) {
3418 tmp.str = par->String(this, false);
3419 switch (par->footnotekind) {
3420 case LyXParagraph::FIG:
3421 case LyXParagraph::WIDE_FIG:
3422 tmp.str = tostr(++figs) + ". "
3424 l[TOC_LOF].push_back(tmp);
3426 case LyXParagraph::TAB:
3427 case LyXParagraph::WIDE_TAB:
3428 tmp.str = tostr(++tables) + ". "
3430 l[TOC_LOT].push_back(tmp);
3432 case LyXParagraph::ALGORITHM:
3433 tmp.str = tostr(++algs) + ". "
3435 l[TOC_LOA].push_back(tmp);
3437 case LyXParagraph::FOOTNOTE:
3438 case LyXParagraph::MARGIN:
3442 } else if (!par->IsDummy()) {
3444 char const labeltype =
3445 textclasslist.Style(params.textclass,
3446 par->GetLayout()).labeltype;
3448 if (labeltype >= LABEL_COUNTER_CHAPTER
3449 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3450 // insert this into the table of contents
3455 textclasslist.TextClass(params.textclass).maxcounter());
3456 tmp.str = par->String(this, true);
3457 l[TOC_TOC].push_back(tmp);
3468 // This is also a buffer property (ale)
3469 vector<pair<string,string> > const Buffer::getBibkeyList()
3471 /// if this is a child document and the parent is already loaded
3472 /// Use the parent's list instead [ale990412]
3473 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3474 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3476 return tmp->getBibkeyList();
3479 vector<pair<string, string> > keys;
3480 LyXParagraph * par = paragraph;
3483 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3484 par->String(this, false)));
3488 // Might be either using bibtex or a child has bibliography
3490 for (inset_iterator it = inset_iterator_begin();
3491 it != inset_iterator_end(); ++it) {
3492 // Search for Bibtex or Include inset
3493 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3494 vector<pair<string,string> > tmp =
3495 static_cast<InsetBibtex*>(*it)->getKeys(this);
3496 keys.insert(keys.end(), tmp.begin(), tmp.end());
3497 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3498 vector<pair<string,string> > const tmp =
3499 static_cast<InsetInclude*>(*it)->getKeys();
3500 keys.insert(keys.end(), tmp.begin(), tmp.end());
3509 bool Buffer::isDepClean(string const & name) const
3511 DEPCLEAN * item = dep_clean;
3512 while (item && item->master != name)
3514 if (!item) return true;
3519 void Buffer::markDepClean(string const & name)
3522 dep_clean = new DEPCLEAN;
3523 dep_clean->clean = true;
3524 dep_clean->master = name;
3525 dep_clean->next = 0;
3527 DEPCLEAN * item = dep_clean;
3528 while (item && item->master != name)
3533 item = new DEPCLEAN;
3535 item->master = name;
3542 bool Buffer::Dispatch(string const & command)
3544 // Split command string into command and argument
3546 string line = frontStrip(command);
3547 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3549 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3553 bool Buffer::Dispatch(int action, string const & argument)
3555 bool dispatched = true;
3558 Exporter::Export(this, argument, false);
3568 void Buffer::resize()
3570 /// resize the BufferViews!
3576 void Buffer::resizeInsets(BufferView * bv)
3578 /// then remove all LyXText in text-insets
3579 LyXParagraph * par = paragraph;
3580 for (; par; par = par->next) {
3581 par->resizeInsetsLyXText(bv);
3585 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3588 LyXParagraph * par = paragraph;
3590 par->ChangeLanguage(params, from, to);
3596 bool Buffer::isMultiLingual()
3598 LyXParagraph * par = paragraph;
3600 if (par->isMultiLingual(params))
3608 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3609 LyXParagraph::size_type pos)
3612 it = par->InsetIterator(pos);
3613 if (it == par->inset_iterator_end()) {
3620 void Buffer::inset_iterator::SetParagraph()
3623 it = par->inset_iterator_begin();
3624 if (it != par->inset_iterator_end())
3629 // We maintain an invariant that whenever par = 0 then it = 0