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"
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
113 extern LyXAction lyxaction;
117 static const float LYX_FORMAT = 2.17;
119 static const int LYX_FORMAT = 218;
122 extern int tex_code_break_column;
125 Buffer::Buffer(string const & file, bool ronly)
127 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
129 filepath = OnlyPath(file);
138 if (read_only || (lyxrc.use_tempdir)) {
139 tmppath = CreateBufferTmpDir();
140 } else tmppath.erase();
146 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
147 // here the buffer should take care that it is
148 // saved properly, before it goes into the void.
150 // make sure that views using this buffer
155 if (!tmppath.empty()) {
156 DestroyBufferTmpDir(tmppath);
159 LyXParagraph * par = paragraph;
160 LyXParagraph * tmppar;
170 string const Buffer::getLatexName(bool no_path) const
173 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
176 return ChangeExtension(MakeLatexName(filename),
181 void Buffer::setReadonly(bool flag)
183 if (read_only != flag) {
186 users->owner()->getDialogs()->updateBufferDependent(false);
189 WarnReadonly(filename);
194 bool Buffer::saveParamsAsDefaults() // const
196 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
198 Buffer defaults = Buffer(fname);
200 // Use the current buffer's parameters as default
201 defaults.params = params;
203 // add an empty paragraph. Is this enough?
204 defaults.paragraph = new LyXParagraph;
206 return defaults.writeFile(defaults.filename, false);
210 /// Update window titles of all users
211 // Should work on a list
212 void Buffer::updateTitles() const
214 if (users) users->owner()->updateWindowTitle();
218 /// Reset autosave timer of all users
219 // Should work on a list
220 void Buffer::resetAutosaveTimers() const
222 if (users) users->owner()->resetAutosaveTimer();
226 void Buffer::setFileName(string const & newfile)
228 filename = MakeAbsPath(newfile);
229 filepath = OnlyPath(filename);
230 setReadonly(IsFileWriteable(filename) == 0);
235 // candidate for move to BufferView
236 // (at least some parts in the beginning of the func)
239 // changed to be public and have one parameter
240 // if par = 0 normal behavior
241 // else insert behavior
242 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
243 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
246 char depth = 0; // signed or unsigned?
248 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
249 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
251 bool the_end_read = false;
253 LyXParagraph * return_par = 0;
254 LyXFont font(LyXFont::ALL_INHERIT, params.language);
256 if (format < 2.16 && params.language->lang() == "hebrew")
257 font.setLanguage(default_language);
259 if (file_format < 216 && params.language->lang() == "hebrew")
260 font.setLanguage(default_language);
262 // If we are inserting, we cheat and get a token in advance
263 bool has_token = false;
267 par = new LyXParagraph;
269 users->text->BreakParagraph(users);
270 return_par = users->text->FirstParagraph();
273 // We don't want to adopt the parameters from the
274 // document we insert, so we skip until the text begins:
277 pretoken = lex.GetString();
278 if (pretoken == "\\layout") {
290 pretoken = lex.GetString();
293 if (pretoken.empty()) continue;
296 parseSingleLyXformat2Token(lex, par, return_par,
297 pretoken, pos, depth,
309 paragraph = return_par;
315 // We'll remove this later. (Lgb)
316 static string last_inset_read;
320 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
321 LyXParagraph *& return_par,
322 string const & token, int & pos,
323 char & depth, LyXFont & font
325 , LyXParagraph::footnote_flag & footnoteflag,
326 LyXParagraph::footnote_kind & footnotekind
330 bool the_end_read = false;
332 if (token[0] != '\\') {
333 for (string::const_iterator cit = token.begin();
334 cit != token.end(); ++cit) {
335 par->InsertChar(pos, (*cit), font);
338 } else if (token == "\\i") {
339 Inset * inset = new InsetLatexAccent;
340 inset->Read(this, lex);
341 par->InsertInset(pos, inset, font);
343 } else if (token == "\\layout") {
348 par = new LyXParagraph(par);
352 string const layoutname = lex.GetString();
353 pair<bool, LyXTextClass::LayoutList::size_type> pp
354 = textclasslist.NumberOfLayout(params.textclass,
357 par->layout = pp.second;
358 } else { // layout not found
359 // use default layout "Standard" (0)
362 // Test whether the layout is obsolete.
363 LyXLayout const & layout =
364 textclasslist.Style(params.textclass,
366 if (!layout.obsoleted_by().empty())
368 textclasslist.NumberOfLayout(params.textclass,
369 layout.obsoleted_by()).second;
371 par->footnoteflag = footnoteflag;
372 par->footnotekind = footnotekind;
375 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
377 if (format < 2.16 && params.language->lang() == "hebrew")
378 font.setLanguage(default_language);
380 if (file_format < 216 && params.language->lang() == "hebrew")
381 font.setLanguage(default_language);
384 } else if (token == "\\end_float") {
389 par = new LyXParagraph(par);
391 footnotekind = LyXParagraph::FOOTNOTE;
392 footnoteflag = LyXParagraph::NO_FOOTNOTE;
395 par->layout = LYX_DUMMY_LAYOUT;
396 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
398 if (format < 2.16 && params.language->lang() == "hebrew")
399 font.setLanguage(default_language);
401 if (file_format < 216 && params.language->lang() == "hebrew")
402 font.setLanguage(default_language);
404 } else if (token == "\\begin_float") {
405 int tmpret = lex.FindToken(string_footnotekinds);
406 if (tmpret == -1) ++tmpret;
407 if (tmpret != LYX_LAYOUT_DEFAULT)
408 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
409 if (footnotekind == LyXParagraph::FOOTNOTE
410 || footnotekind == LyXParagraph::MARGIN)
411 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
413 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
415 } else if (token == "\\begin_float") {
416 // This is the compability reader, unfinished but tested.
419 string const tmptok = lex.GetString();
420 //lyxerr << "old float: " << tmptok << endl;
425 if (tmptok == "footnote") {
426 inset = new InsetFoot;
427 } else if (tmptok == "margin") {
428 inset = new InsetMarginal;
429 } else if (tmptok == "fig") {
430 inset = new InsetFloat("figure");
431 old_float += "placement htbp\n";
432 } else if (tmptok == "tab") {
433 inset = new InsetFloat("table");
434 old_float += "placement htbp\n";
435 } else if (tmptok == "alg") {
436 inset = new InsetFloat("algorithm");
437 old_float += "placement htbp\n";
438 } else if (tmptok == "wide-fig") {
439 InsetFloat * tmp = new InsetFloat("figure");
442 old_float += "placement htbp\n";
443 } else if (tmptok == "wide-tab") {
444 InsetFloat * tmp = new InsetFloat("table");
447 old_float += "placement htbp\n";
450 if (!inset) return false; // no end read yet
452 old_float += "collapsed true\n";
454 // Here we need to check for \end_deeper and handle that
455 // before we do the footnote parsing.
456 // This _is_ a hack! (Lgb)
459 string const tmp = lex.GetString();
460 if (tmp == "\\end_deeper") {
461 lyxerr << "\\end_deeper caught!" << endl;
463 lex.printError("\\end_deeper: "
464 "depth is already null");
475 old_float += lex.getLongString("\\end_float");
476 old_float += "\n\\end_inset\n";
477 //lyxerr << "float body: " << old_float << endl;
479 istringstream istr(old_float);
482 nylex.setStream(istr);
484 inset->Read(this, nylex);
485 par->InsertInset(pos, inset, font);
488 } else if (token == "\\begin_deeper") {
490 } else if (token == "\\end_deeper") {
492 lex.printError("\\end_deeper: "
493 "depth is already null");
497 } else if (token == "\\begin_preamble") {
498 params.readPreamble(lex);
499 } else if (token == "\\textclass") {
501 pair<bool, LyXTextClassList::size_type> pp =
502 textclasslist.NumberOfClass(lex.GetString());
504 params.textclass = pp.second;
506 WriteAlert(string(_("Textclass error")),
507 string(_("The document uses an unknown textclass \"")) +
508 lex.GetString() + string("\"."),
509 string(_("LyX will not be able to produce output correctly.")));
510 params.textclass = 0;
512 if (!textclasslist.Load(params.textclass)) {
513 // if the textclass wasn't loaded properly
514 // we need to either substitute another
515 // or stop loading the file.
516 // I can substitute but I don't see how I can
517 // stop loading... ideas?? ARRae980418
518 WriteAlert(_("Textclass Loading Error!"),
519 string(_("Can't load textclass ")) +
520 textclasslist.NameOfClass(params.textclass),
521 _("-- substituting default"));
522 params.textclass = 0;
524 } else if (token == "\\options") {
526 params.options = lex.GetString();
527 } else if (token == "\\language") {
528 params.readLanguage(lex);
529 } else if (token == "\\fontencoding") {
531 } else if (token == "\\inputencoding") {
533 params.inputenc = lex.GetString();
534 } else if (token == "\\graphics") {
535 params.readGraphicsDriver(lex);
536 } else if (token == "\\fontscheme") {
538 params.fonts = lex.GetString();
539 } else if (token == "\\noindent") {
540 par->noindent = true;
541 } else if (token == "\\fill_top") {
542 par->added_space_top = VSpace(VSpace::VFILL);
543 } else if (token == "\\fill_bottom") {
544 par->added_space_bottom = VSpace(VSpace::VFILL);
545 } else if (token == "\\line_top") {
546 par->line_top = true;
547 } else if (token == "\\line_bottom") {
548 par->line_bottom = true;
549 } else if (token == "\\pagebreak_top") {
550 par->pagebreak_top = true;
551 } else if (token == "\\pagebreak_bottom") {
552 par->pagebreak_bottom = true;
553 } else if (token == "\\start_of_appendix") {
554 par->start_of_appendix = true;
555 } else if (token == "\\paragraph_separation") {
556 int tmpret = lex.FindToken(string_paragraph_separation);
557 if (tmpret == -1) ++tmpret;
558 if (tmpret != LYX_LAYOUT_DEFAULT)
559 params.paragraph_separation =
560 static_cast<BufferParams::PARSEP>(tmpret);
561 } else if (token == "\\defskip") {
563 params.defskip = VSpace(lex.GetString());
564 } else if (token == "\\epsfig") { // obsolete
565 // Indeed it is obsolete, but we HAVE to be backwards
566 // compatible until 0.14, because otherwise all figures
567 // in existing documents are irretrivably lost. (Asger)
568 params.readGraphicsDriver(lex);
569 } else if (token == "\\quotes_language") {
570 int tmpret = lex.FindToken(string_quotes_language);
571 if (tmpret == -1) ++tmpret;
572 if (tmpret != LYX_LAYOUT_DEFAULT) {
573 InsetQuotes::quote_language tmpl =
574 InsetQuotes::EnglishQ;
577 tmpl = InsetQuotes::EnglishQ;
580 tmpl = InsetQuotes::SwedishQ;
583 tmpl = InsetQuotes::GermanQ;
586 tmpl = InsetQuotes::PolishQ;
589 tmpl = InsetQuotes::FrenchQ;
592 tmpl = InsetQuotes::DanishQ;
595 params.quotes_language = tmpl;
597 } else if (token == "\\quotes_times") {
599 switch (lex.GetInteger()) {
601 params.quotes_times = InsetQuotes::SingleQ;
604 params.quotes_times = InsetQuotes::DoubleQ;
607 } else if (token == "\\papersize") {
608 int tmpret = lex.FindToken(string_papersize);
612 params.papersize2 = tmpret;
613 } else if (token == "\\paperpackage") {
614 int tmpret = lex.FindToken(string_paperpackages);
617 params.paperpackage = BufferParams::PACKAGE_NONE;
619 params.paperpackage = tmpret;
620 } else if (token == "\\use_geometry") {
622 params.use_geometry = lex.GetInteger();
623 } else if (token == "\\use_amsmath") {
625 params.use_amsmath = lex.GetInteger();
626 } else if (token == "\\paperorientation") {
627 int tmpret = lex.FindToken(string_orientation);
628 if (tmpret == -1) ++tmpret;
629 if (tmpret != LYX_LAYOUT_DEFAULT)
630 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
631 } else if (token == "\\paperwidth") {
633 params.paperwidth = lex.GetString();
634 } else if (token == "\\paperheight") {
636 params.paperheight = lex.GetString();
637 } else if (token == "\\leftmargin") {
639 params.leftmargin = lex.GetString();
640 } else if (token == "\\topmargin") {
642 params.topmargin = lex.GetString();
643 } else if (token == "\\rightmargin") {
645 params.rightmargin = lex.GetString();
646 } else if (token == "\\bottommargin") {
648 params.bottommargin = lex.GetString();
649 } else if (token == "\\headheight") {
651 params.headheight = lex.GetString();
652 } else if (token == "\\headsep") {
654 params.headsep = lex.GetString();
655 } else if (token == "\\footskip") {
657 params.footskip = lex.GetString();
658 } else if (token == "\\paperfontsize") {
660 params.fontsize = strip(lex.GetString());
661 } else if (token == "\\papercolumns") {
663 params.columns = lex.GetInteger();
664 } else if (token == "\\papersides") {
666 switch (lex.GetInteger()) {
668 case 1: params.sides = LyXTextClass::OneSide; break;
669 case 2: params.sides = LyXTextClass::TwoSides; break;
671 } else if (token == "\\paperpagestyle") {
673 params.pagestyle = strip(lex.GetString());
674 } else if (token == "\\bullet") {
676 int const index = lex.GetInteger();
678 int temp_int = lex.GetInteger();
679 params.user_defined_bullets[index].setFont(temp_int);
680 params.temp_bullets[index].setFont(temp_int);
682 temp_int = lex.GetInteger();
683 params.user_defined_bullets[index].setCharacter(temp_int);
684 params.temp_bullets[index].setCharacter(temp_int);
686 temp_int = lex.GetInteger();
687 params.user_defined_bullets[index].setSize(temp_int);
688 params.temp_bullets[index].setSize(temp_int);
690 string const temp_str = lex.GetString();
691 if (temp_str != "\\end_bullet") {
692 // this element isn't really necessary for
693 // parsing but is easier for humans
694 // to understand bullets. Put it back and
695 // set a debug message?
696 lex.printError("\\end_bullet expected, got" + temp_str);
697 //how can I put it back?
699 } else if (token == "\\bulletLaTeX") {
701 int const index = lex.GetInteger();
703 string temp_str = lex.GetString();
705 while (temp_str != "\\end_bullet") {
706 // this loop structure is needed when user
707 // enters an empty string since the first
708 // thing returned will be the \\end_bullet
710 // if the LaTeX entry has spaces. Each element
711 // therefore needs to be read in turn
714 temp_str = lex.GetString();
716 params.user_defined_bullets[index].setText(sum_str);
717 params.temp_bullets[index].setText(sum_str);
718 } else if (token == "\\secnumdepth") {
720 params.secnumdepth = lex.GetInteger();
721 } else if (token == "\\tocdepth") {
723 params.tocdepth = lex.GetInteger();
724 } else if (token == "\\spacing") {
726 string const tmp = strip(lex.GetString());
727 Spacing::Space tmp_space = Spacing::Default;
729 if (tmp == "single") {
730 tmp_space = Spacing::Single;
731 } else if (tmp == "onehalf") {
732 tmp_space = Spacing::Onehalf;
733 } else if (tmp == "double") {
734 tmp_space = Spacing::Double;
735 } else if (tmp == "other") {
737 tmp_space = Spacing::Other;
738 tmp_val = lex.GetFloat();
740 lex.printError("Unknown spacing token: '$$Token'");
742 // Small hack so that files written with klyx will be
745 par->spacing.set(tmp_space, tmp_val);
747 params.spacing.set(tmp_space, tmp_val);
749 } else if (token == "\\paragraph_spacing") {
751 string const tmp = strip(lex.GetString());
752 if (tmp == "single") {
753 par->spacing.set(Spacing::Single);
754 } else if (tmp == "onehalf") {
755 par->spacing.set(Spacing::Onehalf);
756 } else if (tmp == "double") {
757 par->spacing.set(Spacing::Double);
758 } else if (tmp == "other") {
760 par->spacing.set(Spacing::Other,
763 lex.printError("Unknown spacing token: '$$Token'");
765 } else if (token == "\\float_placement") {
767 params.float_placement = lex.GetString();
768 } else if (token == "\\family") {
770 font.setLyXFamily(lex.GetString());
771 } else if (token == "\\series") {
773 font.setLyXSeries(lex.GetString());
774 } else if (token == "\\shape") {
776 font.setLyXShape(lex.GetString());
777 } else if (token == "\\size") {
779 font.setLyXSize(lex.GetString());
780 } else if (token == "\\latex") {
782 string const tok = lex.GetString();
783 // This is dirty, but gone with LyX3. (Asger)
784 if (tok == "no_latex")
785 font.setLatex(LyXFont::OFF);
786 else if (tok == "latex")
787 font.setLatex(LyXFont::ON);
788 else if (tok == "default")
789 font.setLatex(LyXFont::INHERIT);
791 lex.printError("Unknown LaTeX font flag "
793 } else if (token == "\\lang") {
795 string const tok = lex.GetString();
796 Language const * lang = languages.getLanguage(tok);
798 font.setLanguage(lang);
800 font.setLanguage(params.language);
801 lex.printError("Unknown language `$$Token'");
803 } else if (token == "\\numeric") {
805 font.setNumber(font.setLyXMisc(lex.GetString()));
806 } else if (token == "\\emph") {
808 font.setEmph(font.setLyXMisc(lex.GetString()));
809 } else if (token == "\\bar") {
811 string const tok = lex.GetString();
812 // This is dirty, but gone with LyX3. (Asger)
814 font.setUnderbar(LyXFont::ON);
815 else if (tok == "no")
816 font.setUnderbar(LyXFont::OFF);
817 else if (tok == "default")
818 font.setUnderbar(LyXFont::INHERIT);
820 lex.printError("Unknown bar font flag "
822 } else if (token == "\\noun") {
824 font.setNoun(font.setLyXMisc(lex.GetString()));
825 } else if (token == "\\color") {
827 font.setLyXColor(lex.GetString());
828 } else if (token == "\\align") {
829 int tmpret = lex.FindToken(string_align);
830 if (tmpret == -1) ++tmpret;
831 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
834 for (; tmpret > 0; --tmpret)
835 tmpret2 = tmpret2 * 2;
837 int const tmpret2 = int(pow(2.0, tmpret));
839 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
840 par->align = LyXAlignment(tmpret2);
842 } else if (token == "\\added_space_top") {
844 par->added_space_top = VSpace(lex.GetString());
845 } else if (token == "\\added_space_bottom") {
847 par->added_space_bottom = VSpace(lex.GetString());
848 } else if (token == "\\pextra_type") {
850 par->pextra_type = lex.GetInteger();
851 } else if (token == "\\pextra_width") {
853 par->pextra_width = lex.GetString();
854 } else if (token == "\\pextra_widthp") {
856 par->pextra_widthp = lex.GetString();
857 } else if (token == "\\pextra_alignment") {
859 par->pextra_alignment = lex.GetInteger();
860 } else if (token == "\\pextra_hfill") {
862 par->pextra_hfill = lex.GetInteger();
863 } else if (token == "\\pextra_start_minipage") {
865 par->pextra_start_minipage = lex.GetInteger();
866 } else if (token == "\\labelwidthstring") {
868 par->labelwidthstring = lex.GetString();
869 // do not delete this token, it is still needed!
870 } else if (token == "\\end_inset") {
871 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
872 << "Last inset read was: " << last_inset_read
874 // Simply ignore this. The insets do not have
876 // But insets should read it, it is a part of
877 // the inset isn't it? Lgb.
878 } else if (token == "\\begin_inset") {
879 readInset(lex, par, pos, font);
880 } else if (token == "\\SpecialChar") {
881 LyXLayout const & layout =
882 textclasslist.Style(params.textclass,
885 // Insets don't make sense in a free-spacing context! ---Kayvan
886 if (layout.free_spacing) {
889 string next_token = lex.GetString();
890 if (next_token == "\\-") {
891 par->InsertChar(pos, '-', font);
892 } else if (next_token == "\\protected_separator"
893 || next_token == "~") {
894 par->InsertChar(pos, ' ', font);
896 lex.printError("Token `$$Token' "
898 "paragraph layout!");
903 Inset * inset = new InsetSpecialChar;
904 inset->Read(this, lex);
905 par->InsertInset(pos, inset, font);
908 } else if (token == "\\newline") {
909 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
911 } else if (token == "\\LyXTable") {
912 Inset * inset = new InsetTabular(*this);
913 inset->Read(this, lex);
914 par->InsertInset(pos, inset, font);
916 } else if (token == "\\hfill") {
917 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
919 } else if (token == "\\protected_separator") { // obsolete
920 // This is a backward compability thingie. (Lgb)
921 // Remove it later some time...introduced with fileformat
923 LyXLayout const & layout =
924 textclasslist.Style(params.textclass,
927 if (layout.free_spacing) {
928 par->InsertChar(pos, ' ', font);
930 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
931 par->InsertInset(pos, inset, font);
934 } else if (token == "\\bibitem") { // ale970302
936 InsetCommandParams p( "bibitem" );
937 par->bibkey = new InsetBibKey(p);
939 par->bibkey->Read(this, lex);
940 } else if (token == "\\backslash") {
941 par->InsertChar(pos, '\\', font);
943 } else if (token == "\\the_end") {
946 // This should be insurance for the future: (Asger)
947 lex.printError("Unknown token `$$Token'. "
948 "Inserting as text.");
949 string::const_iterator cit = token.begin();
950 string::const_iterator end = token.end();
951 for (; cit != end; ++cit) {
952 par->InsertChar(pos, (*cit), font);
960 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
961 int & pos, LyXFont & font)
964 if (lex.GetString() != "\\begin_inset") {
965 lyxerr << "Buffer::readInset: Consistency check failed."
972 string const tmptok = lex.GetString();
973 last_inset_read = tmptok;
975 // test the different insets
976 if (tmptok == "LatexCommand") {
977 InsetCommandParams inscmd;
980 if (inscmd.getCmdName() == "cite") {
981 inset = new InsetCitation(inscmd);
982 } else if (inscmd.getCmdName() == "bibitem") {
983 lex.printError("Wrong place for bibitem");
984 inset = new InsetBibKey(inscmd);
985 } else if (inscmd.getCmdName() == "BibTeX") {
986 inset = new InsetBibtex(inscmd);
987 } else if (inscmd.getCmdName() == "index") {
988 inset = new InsetIndex(inscmd);
989 } else if (inscmd.getCmdName() == "include") {
990 inset = new InsetInclude(inscmd, *this);
991 } else if (inscmd.getCmdName() == "label") {
992 inset = new InsetLabel(inscmd);
993 } else if (inscmd.getCmdName() == "url"
994 || inscmd.getCmdName() == "htmlurl") {
995 inset = new InsetUrl(inscmd);
996 } else if (inscmd.getCmdName() == "ref"
997 || inscmd.getCmdName() == "pageref"
998 || inscmd.getCmdName() == "vref"
999 || inscmd.getCmdName() == "vpageref"
1000 || inscmd.getCmdName() == "prettyref") {
1001 if (!inscmd.getOptions().empty()
1002 || !inscmd.getContents().empty()) {
1003 inset = new InsetRef(inscmd, *this);
1005 } else if (inscmd.getCmdName() == "tableofcontents"
1006 || inscmd.getCmdName() == "listofalgorithms"
1007 || inscmd.getCmdName() == "listoffigures"
1008 || inscmd.getCmdName() == "listoftables") {
1009 inset = new InsetTOC(inscmd);
1010 } else if (inscmd.getCmdName() == "printindex") {
1011 inset = new InsetPrintIndex(inscmd);
1012 } else if (inscmd.getCmdName() == "lyxparent") {
1013 inset = new InsetParent(inscmd, *this);
1016 if (tmptok == "Quotes") {
1017 inset = new InsetQuotes;
1018 } else if (tmptok == "External") {
1019 inset = new InsetExternal;
1020 } else if (tmptok == "FormulaMacro") {
1021 inset = new InsetFormulaMacro;
1022 } else if (tmptok == "Formula") {
1023 inset = new InsetFormula;
1024 } else if (tmptok == "Figure") {
1025 inset = new InsetFig(100, 100, *this);
1026 } else if (tmptok == "Info") {
1027 inset = new InsetInfo;
1028 } else if (tmptok == "Include") {
1029 InsetCommandParams p( "Include" );
1030 inset = new InsetInclude(p, *this);
1031 } else if (tmptok == "ERT") {
1032 inset = new InsetERT;
1033 } else if (tmptok == "Tabular") {
1034 inset = new InsetTabular(*this);
1035 } else if (tmptok == "Text") {
1036 inset = new InsetText;
1037 } else if (tmptok == "Foot") {
1038 inset = new InsetFoot;
1039 } else if (tmptok == "Marginal") {
1040 inset = new InsetMarginal;
1041 } else if (tmptok == "Minipage") {
1042 inset = new InsetMinipage;
1043 } else if (tmptok == "Float") {
1045 string tmptok = lex.GetString();
1046 inset = new InsetFloat(tmptok);
1047 } else if (tmptok == "List") {
1048 inset = new InsetList;
1049 } else if (tmptok == "Theorem") {
1050 inset = new InsetList;
1051 } else if (tmptok == "Caption") {
1052 inset = new InsetCaption;
1053 } else if (tmptok == "GRAPHICS") {
1054 inset = new InsetGraphics;
1057 if (inset) inset->Read(this, lex);
1061 par->InsertInset(pos, inset, font);
1067 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1071 string const token(lex.GetString());
1072 if (token == "\\lyxformat") { // the first token _must_ be...
1075 format = lex.GetFloat();
1077 if (LYX_FORMAT - format > 0.05) {
1078 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1079 LYX_FORMAT, format) << endl;
1081 if (format - LYX_FORMAT > 0.05) {
1082 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1083 LYX_FORMAT, format) << endl;
1085 bool the_end = readLyXformat2(lex, par);
1086 // Formats >= 2.13 support "\the_end" marker
1093 WriteAlert(_("Warning!"),
1094 _("Reading of document is not complete"),
1095 _("Maybe the document is truncated"));
1096 // We simulate a safe reading anyways to allow
1097 // users to take the chance... (Asger)
1101 WriteAlert(_("ERROR!"),
1102 _("Old LyX file format found. "
1103 "Use LyX 0.10.x to read this!"));
1108 string tmp_format = lex.GetString();
1109 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1110 // if present remove ".," from string.
1111 string::size_type dot = tmp_format.find_first_of(".,");
1112 //lyxerr << " dot found at " << dot << endl;
1113 if (dot != string::npos)
1114 tmp_format.erase(dot, 1);
1115 file_format = strToInt(tmp_format);
1116 if (file_format == LYX_FORMAT) {
1118 } else if (file_format > LYX_FORMAT) {
1120 WriteAlert(_("Warning!"),
1121 _("LyX file format is newer that what"),
1122 _("is supported in this LyX version. Expect some problems."));
1124 } else if (file_format < LYX_FORMAT) {
1126 if (file_format < 200) {
1127 WriteAlert(_("ERROR!"),
1128 _("Old LyX file format found. "
1129 "Use LyX 0.10.x to read this!"));
1133 bool the_end = readLyXformat2(lex, par);
1135 // the_end was added in 213
1136 if (file_format < 213)
1140 WriteAlert(_("Warning!"),
1141 _("Reading of document is not complete"),
1142 _("Maybe the document is truncated"));
1145 } else { // "\\lyxformat" not found
1146 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1149 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1155 // Should probably be moved to somewhere else: BufferView? LyXView?
1156 bool Buffer::save() const
1158 // We don't need autosaves in the immediate future. (Asger)
1159 resetAutosaveTimers();
1163 if (lyxrc.make_backup) {
1164 s = fileName() + '~';
1165 if (!lyxrc.backupdir_path.empty())
1166 s = AddName(lyxrc.backupdir_path,
1167 subst(CleanupPath(s),'/','!'));
1169 // Rename is the wrong way of making a backup,
1170 // this is the correct way.
1171 /* truss cp fil fil2:
1172 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1173 stat("LyXVC.lyx", 0xEFFFF688) = 0
1174 open("LyXVC.lyx", O_RDONLY) = 3
1175 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1176 fstat(4, 0xEFFFF508) = 0
1177 fstat(3, 0xEFFFF508) = 0
1178 read(3, " # T h i s f i l e w".., 8192) = 5579
1179 write(4, " # T h i s f i l e w".., 5579) = 5579
1180 read(3, 0xEFFFD4A0, 8192) = 0
1183 chmod("LyXVC3.lyx", 0100644) = 0
1184 lseek(0, 0, SEEK_CUR) = 46440
1188 // Should proabaly have some more error checking here.
1189 // Should be cleaned up in 0.13, at least a bit.
1190 // Doing it this way, also makes the inodes stay the same.
1191 // This is still not a very good solution, in particular we
1192 // might loose the owner of the backup.
1193 FileInfo finfo(fileName());
1194 if (finfo.exist()) {
1195 mode_t fmode = finfo.getMode();
1196 struct utimbuf times = {
1197 finfo.getAccessTime(),
1198 finfo.getModificationTime() };
1200 ifstream ifs(fileName().c_str());
1201 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1206 ::chmod(s.c_str(), fmode);
1208 if (::utime(s.c_str(), ×)) {
1209 lyxerr << "utime error." << endl;
1212 lyxerr << "LyX was not able to make "
1213 "backupcopy. Beware." << endl;
1218 if (writeFile(fileName(), false)) {
1220 removeAutosaveFile(fileName());
1222 // Saving failed, so backup is not backup
1223 if (lyxrc.make_backup) {
1224 lyx::rename(s, fileName());
1232 // Returns false if unsuccesful
1233 bool Buffer::writeFile(string const & fname, bool flag) const
1235 // if flag is false writeFile will not create any GUI
1236 // warnings, only cerr.
1237 // Needed for autosave in background or panic save (Matthias 120496)
1239 if (read_only && (fname == filename)) {
1240 // Here we should come with a question if we should
1241 // perform the write anyway.
1243 lyxerr << _("Error! Document is read-only: ")
1246 WriteAlert(_("Error! Document is read-only: "),
1251 FileInfo finfo(fname);
1252 if (finfo.exist() && !finfo.writable()) {
1253 // Here we should come with a question if we should
1254 // try to do the save anyway. (i.e. do a chmod first)
1256 lyxerr << _("Error! Cannot write file: ")
1259 WriteFSAlert(_("Error! Cannot write file: "),
1264 ofstream ofs(fname.c_str());
1267 lyxerr << _("Error! Cannot open file: ")
1270 WriteFSAlert(_("Error! Cannot open file: "),
1276 // Use the standard "C" locale for file output.
1277 ofs.imbue(std::locale::classic());
1280 // The top of the file should not be written by params.
1282 // write out a comment in the top of the file
1283 ofs << '#' << LYX_DOCVERSION
1284 << " created this file. For more info see http://www.lyx.org/\n";
1286 ofs.setf(ios::showpoint|ios::fixed);
1289 char dummy_format[512];
1290 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1291 ofs << "\\lyxformat " << dummy_format << "\n";
1293 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1296 ofs << "\\lyxformat " << LYX_FORMAT << "\n";
1298 // now write out the buffer paramters.
1299 params.writeFile(ofs);
1301 char footnoteflag = 0;
1304 // this will write out all the paragraphs
1305 // using recursive descent.
1306 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1308 // Write marker that shows file is complete
1309 ofs << "\n\\the_end" << endl;
1313 // how to check if close went ok?
1314 // Following is an attempt... (BE 20001011)
1316 // good() returns false if any error occured, including some
1317 // formatting error.
1318 // bad() returns true if something bad happened in the buffer,
1319 // which should include file system full errors.
1326 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1328 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1338 string const Buffer::asciiParagraph(LyXParagraph const * par,
1339 unsigned int linelen) const
1341 ostringstream buffer;
1344 Inset const * inset;
1347 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1351 int ltype_depth = 0;
1352 unsigned int currlinelen = 0;
1353 bool ref_printed = false;
1359 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1363 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1367 /* begins a footnote environment ? */
1368 if (footnoteflag != par->footnoteflag) {
1369 footnoteflag = par->footnoteflag;
1371 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1372 if ((linelen > 0) &&
1373 ((currlinelen + j) > linelen)) {
1378 << string_footnotekinds[par->footnotekind]
1384 /* begins or ends a deeper area ?*/
1385 if (depth != par->depth) {
1386 if (par->depth > depth) {
1387 while (par->depth > depth) {
1392 while (par->depth < depth) {
1398 /* First write the layout */
1399 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1400 if (tmp == "Itemize") {
1402 ltype_depth = depth+1;
1403 } else if (tmp == "Enumerate") {
1405 ltype_depth = depth+1;
1406 } else if (strstr(tmp.c_str(), "ection")) {
1408 ltype_depth = depth+1;
1409 } else if (strstr(tmp.c_str(), "aragraph")) {
1411 ltype_depth = depth+1;
1412 } else if (tmp == "Description") {
1414 ltype_depth = depth+1;
1415 } else if (tmp == "Abstract") {
1418 } else if (tmp == "Bibliography") {
1426 /* maybe some vertical spaces */
1428 /* the labelwidthstring used in lists */
1432 /* some pagebreaks? */
1436 /* what about the alignment */
1439 /* dummy layout, that means a footnote ended */
1440 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1444 lyxerr << "Should this ever happen?" << endl;
1448 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1449 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1457 for (char j = 0; j < depth; ++j)
1459 currlinelen = depth * 2;
1461 case 0: /* Standard */
1462 case 4: /* (Sub)Paragraph */
1463 case 5: /* Description */
1465 case 6: /* Abstract */
1467 buffer << "Abstract\n\n";
1469 buffer << "Abstract: ";
1471 case 7: /* Bibliography */
1474 buffer << "References\n\n";
1476 buffer << "References: ";
1481 buffer << par->labelstring << " ";
1484 if (ltype_depth > depth) {
1485 for (char j = ltype_depth - 1; j > depth; --j)
1487 currlinelen += (ltype_depth-depth)*2;
1490 font2 = par->GetFontSettings(params, i);
1491 if (font1.latex() != font2.latex()) {
1492 if (font2.latex() == LyXFont::OFF)
1499 c = par->GetChar(i);
1503 case LyXParagraph::META_INSET:
1504 if ((inset = par->GetInset(i))) {
1505 if (!inset->Ascii(this, buffer)) {
1507 string s = rsplit(buffer.str().c_str(),
1509 currlinelen += s.length();
1511 // to be sure it breaks paragraph
1512 currlinelen += linelen;
1516 case LyXParagraph::META_NEWLINE:
1519 for (char j = 0; j < depth; ++j)
1522 currlinelen = depth * 2;
1523 if (ltype_depth > depth) {
1524 for (char j = ltype_depth;
1527 currlinelen += (ltype_depth - depth) * 2;
1530 case LyXParagraph::META_HFILL:
1537 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1538 (c == ' ') && ((i + 2) < par->size()))
1541 for (char j = 0; j < depth; ++j)
1543 currlinelen = depth * 2;
1544 if (ltype_depth > depth) {
1545 for (char j = ltype_depth;
1548 currlinelen += (ltype_depth-depth)*2;
1550 } else if (c != '\0')
1553 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1558 return buffer.str().c_str();
1562 void Buffer::writeFileAscii(string const & fname, int linelen)
1564 ofstream ofs(fname.c_str());
1566 WriteFSAlert(_("Error: Cannot write file:"), fname);
1569 writeFileAscii(ofs, linelen);
1573 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1575 LyXParagraph * par = paragraph;
1577 ofs << asciiParagraph(par, linelen);
1584 void Buffer::makeLaTeXFile(string const & fname,
1585 string const & original_path,
1586 bool nice, bool only_body)
1588 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1590 niceFile = nice; // this will be used by Insetincludes.
1592 tex_code_break_column = lyxrc.ascii_linelen;
1594 LyXTextClass const & tclass =
1595 textclasslist.TextClass(params.textclass);
1597 ofstream ofs(fname.c_str());
1599 WriteFSAlert(_("Error: Cannot open file: "), fname);
1603 // validate the buffer.
1604 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1605 LaTeXFeatures features(params, tclass.numLayouts());
1607 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1610 // The starting paragraph of the coming rows is the
1611 // first paragraph of the document. (Asger)
1612 texrow.start(paragraph, 0);
1614 if (!only_body && nice) {
1615 ofs << "%% " LYX_DOCVERSION " created this file. "
1616 "For more info, see http://www.lyx.org/.\n"
1617 "%% Do not edit unless you really know what "
1622 lyxerr.debug() << "lyx header finished" << endl;
1623 // There are a few differences between nice LaTeX and usual files:
1624 // usual is \batchmode and has a
1625 // special input@path to allow the including of figures
1626 // with either \input or \includegraphics (what figinsets do).
1627 // batchmode is not set if there is a tex_code_break_column.
1628 // In this case somebody is interested in the generated LaTeX,
1629 // so this is OK. input@path is set when the actual parameter
1630 // original_path is set. This is done for usual tex-file, but not
1631 // for nice-latex-file. (Matthias 250696)
1634 // code for usual, NOT nice-latex-file
1635 ofs << "\\batchmode\n"; // changed
1636 // from \nonstopmode
1639 if (!original_path.empty()) {
1640 ofs << "\\makeatletter\n"
1641 << "\\def\\input@path{{"
1642 << original_path << "/}}\n"
1643 << "\\makeatother\n";
1649 ofs << "\\documentclass";
1651 string options; // the document class options.
1653 if (tokenPos(tclass.opt_fontsize(),
1654 '|', params.fontsize) >= 0) {
1655 // only write if existing in list (and not default)
1656 options += params.fontsize;
1661 if (!params.use_geometry &&
1662 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1663 switch (params.papersize) {
1664 case BufferParams::PAPER_A4PAPER:
1665 options += "a4paper,";
1667 case BufferParams::PAPER_USLETTER:
1668 options += "letterpaper,";
1670 case BufferParams::PAPER_A5PAPER:
1671 options += "a5paper,";
1673 case BufferParams::PAPER_B5PAPER:
1674 options += "b5paper,";
1676 case BufferParams::PAPER_EXECUTIVEPAPER:
1677 options += "executivepaper,";
1679 case BufferParams::PAPER_LEGALPAPER:
1680 options += "legalpaper,";
1686 if (params.sides != tclass.sides()) {
1687 switch (params.sides) {
1688 case LyXTextClass::OneSide:
1689 options += "oneside,";
1691 case LyXTextClass::TwoSides:
1692 options += "twoside,";
1699 if (params.columns != tclass.columns()) {
1700 if (params.columns == 2)
1701 options += "twocolumn,";
1703 options += "onecolumn,";
1706 if (!params.use_geometry
1707 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1708 options += "landscape,";
1710 // language should be a parameter to \documentclass
1711 bool use_babel = false;
1712 if (params.language->babel() == "hebrew"
1713 && default_language->babel() != "hebrew")
1714 // This seems necessary
1715 features.UsedLanguages.insert(default_language);
1716 #ifdef DO_USE_DEFAULT_LANGUAGE
1717 if (params.language->lang() != "default" ||
1718 !features.UsedLanguages.empty()) {
1721 for (LaTeXFeatures::LanguageList::const_iterator cit =
1722 features.UsedLanguages.begin();
1723 cit != features.UsedLanguages.end(); ++cit)
1724 options += (*cit)->babel() + ",";
1725 options += params.language->babel() + ',';
1726 #ifdef DO_USE_DEFAULT_LANGUAGE
1730 // the user-defined options
1731 if (!params.options.empty()) {
1732 options += params.options + ',';
1735 if (!options.empty()){
1736 options = strip(options, ',');
1737 ofs << '[' << options << ']';
1741 << textclasslist.LatexnameOfClass(params.textclass)
1744 // end of \documentclass defs
1746 // font selection must be done before loading fontenc.sty
1747 // The ae package is not needed when using OT1 font encoding.
1748 if (params.fonts != "default" &&
1749 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1750 ofs << "\\usepackage{" << params.fonts << "}\n";
1752 if (params.fonts == "ae") {
1753 ofs << "\\usepackage{aecompl}\n";
1757 // this one is not per buffer
1758 if (lyxrc.fontenc != "default") {
1759 ofs << "\\usepackage[" << lyxrc.fontenc
1764 if (params.inputenc == "auto") {
1765 string const doc_encoding =
1766 params.language->encoding()->LatexName();
1768 // Create a list with all the input encodings used
1770 set<string> encodings;
1771 for (LaTeXFeatures::LanguageList::const_iterator it =
1772 features.UsedLanguages.begin();
1773 it != features.UsedLanguages.end(); ++it)
1774 if ((*it)->encoding()->LatexName() != doc_encoding)
1775 encodings.insert((*it)->encoding()->LatexName());
1777 ofs << "\\usepackage[";
1778 std::copy(encodings.begin(), encodings.end(),
1779 std::ostream_iterator<string>(ofs, ","));
1780 ofs << doc_encoding << "]{inputenc}\n";
1782 } else if (params.inputenc != "default") {
1783 ofs << "\\usepackage[" << params.inputenc
1788 // At the very beginning the text parameters.
1789 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1790 switch (params.paperpackage) {
1791 case BufferParams::PACKAGE_A4:
1792 ofs << "\\usepackage{a4}\n";
1795 case BufferParams::PACKAGE_A4WIDE:
1796 ofs << "\\usepackage{a4wide}\n";
1799 case BufferParams::PACKAGE_WIDEMARGINSA4:
1800 ofs << "\\usepackage[widemargins]{a4}\n";
1805 if (params.use_geometry) {
1806 ofs << "\\usepackage{geometry}\n";
1808 ofs << "\\geometry{verbose";
1809 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1810 ofs << ",landscape";
1811 switch (params.papersize2) {
1812 case BufferParams::VM_PAPER_CUSTOM:
1813 if (!params.paperwidth.empty())
1814 ofs << ",paperwidth="
1815 << params.paperwidth;
1816 if (!params.paperheight.empty())
1817 ofs << ",paperheight="
1818 << params.paperheight;
1820 case BufferParams::VM_PAPER_USLETTER:
1821 ofs << ",letterpaper";
1823 case BufferParams::VM_PAPER_USLEGAL:
1824 ofs << ",legalpaper";
1826 case BufferParams::VM_PAPER_USEXECUTIVE:
1827 ofs << ",executivepaper";
1829 case BufferParams::VM_PAPER_A3:
1832 case BufferParams::VM_PAPER_A4:
1835 case BufferParams::VM_PAPER_A5:
1838 case BufferParams::VM_PAPER_B3:
1841 case BufferParams::VM_PAPER_B4:
1844 case BufferParams::VM_PAPER_B5:
1848 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1849 switch (lyxrc.default_papersize) {
1850 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1851 case BufferParams::PAPER_USLETTER:
1852 ofs << ",letterpaper";
1854 case BufferParams::PAPER_LEGALPAPER:
1855 ofs << ",legalpaper";
1857 case BufferParams::PAPER_EXECUTIVEPAPER:
1858 ofs << ",executivepaper";
1860 case BufferParams::PAPER_A3PAPER:
1863 case BufferParams::PAPER_A4PAPER:
1866 case BufferParams::PAPER_A5PAPER:
1869 case BufferParams::PAPER_B5PAPER:
1874 if (!params.topmargin.empty())
1875 ofs << ",tmargin=" << params.topmargin;
1876 if (!params.bottommargin.empty())
1877 ofs << ",bmargin=" << params.bottommargin;
1878 if (!params.leftmargin.empty())
1879 ofs << ",lmargin=" << params.leftmargin;
1880 if (!params.rightmargin.empty())
1881 ofs << ",rmargin=" << params.rightmargin;
1882 if (!params.headheight.empty())
1883 ofs << ",headheight=" << params.headheight;
1884 if (!params.headsep.empty())
1885 ofs << ",headsep=" << params.headsep;
1886 if (!params.footskip.empty())
1887 ofs << ",footskip=" << params.footskip;
1891 if (params.use_amsmath
1892 && !tclass.provides(LyXTextClass::amsmath)) {
1893 ofs << "\\usepackage{amsmath}\n";
1897 if (tokenPos(tclass.opt_pagestyle(),
1898 '|', params.pagestyle) >= 0) {
1899 if (params.pagestyle == "fancy") {
1900 ofs << "\\usepackage{fancyhdr}\n";
1903 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1907 // We try to load babel late, in case it interferes
1908 // with other packages.
1910 ofs << lyxrc.language_package << endl;
1914 if (params.secnumdepth != tclass.secnumdepth()) {
1915 ofs << "\\setcounter{secnumdepth}{"
1916 << params.secnumdepth
1920 if (params.tocdepth != tclass.tocdepth()) {
1921 ofs << "\\setcounter{tocdepth}{"
1927 if (params.paragraph_separation) {
1928 switch (params.defskip.kind()) {
1929 case VSpace::SMALLSKIP:
1930 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1932 case VSpace::MEDSKIP:
1933 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1935 case VSpace::BIGSKIP:
1936 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1938 case VSpace::LENGTH:
1939 ofs << "\\setlength\\parskip{"
1940 << params.defskip.length().asLatexString()
1943 default: // should never happen // Then delete it.
1944 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1949 ofs << "\\setlength\\parindent{0pt}\n";
1953 // Now insert the LyX specific LaTeX commands...
1955 // The optional packages;
1956 string preamble(features.getPackages());
1958 // this might be useful...
1959 preamble += "\n\\makeatletter\n";
1961 // Some macros LyX will need
1962 string tmppreamble(features.getMacros());
1964 if (!tmppreamble.empty()) {
1965 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1966 "LyX specific LaTeX commands.\n"
1967 + tmppreamble + '\n';
1970 // the text class specific preamble
1971 tmppreamble = features.getTClassPreamble();
1972 if (!tmppreamble.empty()) {
1973 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1974 "Textclass specific LaTeX commands.\n"
1975 + tmppreamble + '\n';
1978 /* the user-defined preamble */
1979 if (!params.preamble.empty()) {
1980 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1981 "User specified LaTeX commands.\n"
1982 + params.preamble + '\n';
1985 preamble += "\\makeatother\n";
1987 // Itemize bullet settings need to be last in case the user
1988 // defines their own bullets that use a package included
1989 // in the user-defined preamble -- ARRae
1990 // Actually it has to be done much later than that
1991 // since some packages like frenchb make modifications
1992 // at \begin{document} time -- JMarc
1994 for (int i = 0; i < 4; ++i) {
1995 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1996 if (bullets_def.empty())
1997 bullets_def="\\AtBeginDocument{\n";
1998 bullets_def += " \\renewcommand{\\labelitemi";
2000 // `i' is one less than the item to modify
2007 bullets_def += "ii";
2013 bullets_def += "}{" +
2014 params.user_defined_bullets[i].getText()
2019 if (!bullets_def.empty())
2020 preamble += bullets_def + "}\n\n";
2022 for (int j = countChar(preamble, '\n'); j-- ;) {
2029 ofs << "\\begin{document}\n";
2032 lyxerr.debug() << "preamble finished, now the body." << endl;
2033 #ifdef DO_USE_DEFAULT_LANGUAGE
2034 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2036 if (!lyxrc.language_auto_begin) {
2038 ofs << subst(lyxrc.language_command_begin, "$$lang",
2039 params.language->babel())
2044 latexParagraphs(ofs, paragraph, 0, texrow);
2046 // add this just in case after all the paragraphs
2050 #ifdef DO_USE_DEFAULT_LANGUAGE
2051 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2053 if (!lyxrc.language_auto_end) {
2055 ofs << subst(lyxrc.language_command_end, "$$lang",
2056 params.language->babel())
2062 ofs << "\\end{document}\n";
2065 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2067 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2071 // Just to be sure. (Asger)
2074 // tex_code_break_column's value is used to decide
2075 // if we are in batchmode or not (within mathed_write()
2076 // in math_write.C) so we must set it to a non-zero
2077 // value when we leave otherwise we save incorrect .lyx files.
2078 tex_code_break_column = lyxrc.ascii_linelen;
2082 lyxerr << "File was not closed properly." << endl;
2085 lyxerr.debug() << "Finished making latex file." << endl;
2090 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2092 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2093 LyXParagraph * endpar, TexRow & texrow) const
2095 bool was_title = false;
2096 bool already_title = false;
2097 std::ostringstream ftnote;
2102 while (par != endpar) {
2105 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2108 LyXLayout const & layout =
2109 textclasslist.Style(params.textclass,
2112 if (layout.intitle) {
2113 if (already_title) {
2114 lyxerr <<"Error in latexParagraphs: You"
2115 " should not mix title layouts"
2116 " with normal ones." << endl;
2119 } else if (was_title && !already_title) {
2120 ofs << "\\maketitle\n";
2122 already_title = true;
2125 // We are at depth 0 so we can just use
2126 // ordinary \footnote{} generation
2127 // flag this with ftcount
2129 if (layout.isEnvironment()
2130 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2131 par = par->TeXEnvironment(this, params, ofs, texrow
2133 ,ftnote, ft_texrow, ftcount
2137 par = par->TeXOnePar(this, params, ofs, texrow, false
2140 ftnote, ft_texrow, ftcount
2145 // Write out what we've generated...
2148 ofs << "\\addtocounter{footnote}{-"
2152 ofs << ftnote.str();
2153 texrow += ft_texrow;
2155 // The extra .c_str() is needed when we use
2156 // lyxstring instead of the STL string class.
2157 ftnote.str(string().c_str());
2162 // It might be that we only have a title in this document
2163 if (was_title && !already_title) {
2164 ofs << "\\maketitle\n";
2170 bool Buffer::isLatex() const
2172 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2176 bool Buffer::isLinuxDoc() const
2178 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2182 bool Buffer::isLiterate() const
2184 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2188 bool Buffer::isDocBook() const
2190 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2194 bool Buffer::isSGML() const
2196 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2197 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2201 void Buffer::sgmlOpenTag(ostream & os, int depth,
2202 string const & latexname) const
2204 if (latexname != "!-- --")
2205 os << string(depth, ' ') << "<" << latexname << ">\n";
2209 void Buffer::sgmlCloseTag(ostream & os, int depth,
2210 string const & latexname) const
2212 if (latexname != "!-- --")
2213 os << string(depth, ' ') << "</" << latexname << ">\n";
2217 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2219 LyXParagraph * par = paragraph;
2221 niceFile = nice; // this will be used by Insetincludes.
2223 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2224 string environment_stack[10];
2227 int depth = 0; // paragraph depth
2229 ofstream ofs(fname.c_str());
2232 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2236 LyXTextClass const & tclass =
2237 textclasslist.TextClass(params.textclass);
2239 LaTeXFeatures features(params, tclass.numLayouts());
2243 tex_code_break_column = lyxrc.ascii_linelen;
2245 //tex_code_break_column = 0;
2250 string sgml_includedfiles=features.getIncludedFiles(fname);
2252 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2253 ofs << "<!doctype linuxdoc system>\n\n";
2255 ofs << "<!doctype linuxdoc system [ "
2256 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2259 if (params.options.empty())
2260 sgmlOpenTag(ofs, 0, top_element);
2262 string top = top_element;
2264 top += params.options;
2265 sgmlOpenTag(ofs, 0, top);
2269 ofs << "<!-- " << LYX_DOCVERSION
2270 << " created this file. For more info see http://www.lyx.org/"
2274 int desc_on = 0; // description mode
2275 LyXLayout const & style =
2276 textclasslist.Style(params.textclass,
2279 // treat <toc> as a special case for compatibility with old code
2280 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2281 Inset * inset = par->GetInset(0);
2282 Inset::Code lyx_code = inset->LyxCode();
2283 if (lyx_code == Inset::TOC_CODE){
2284 string const temp = "toc";
2285 sgmlOpenTag(ofs, depth, temp);
2289 linuxDocHandleFootnote(ofs, par, depth);
2295 // environment tag closing
2296 for (; depth > par->depth; --depth) {
2297 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2298 environment_stack[depth].erase();
2301 // write opening SGML tags
2302 switch (style.latextype) {
2303 case LATEX_PARAGRAPH:
2304 if (depth == par->depth
2305 && !environment_stack[depth].empty()) {
2306 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2307 environment_stack[depth].erase();
2313 sgmlOpenTag(ofs, depth, style.latexname());
2318 LinuxDocError(par, 0,
2319 _("Error : Wrong depth for"
2320 " LatexType Command.\n"));
2322 if (!environment_stack[depth].empty()){
2323 sgmlCloseTag(ofs, depth,
2324 environment_stack[depth]);
2328 environment_stack[depth].erase();
2329 sgmlOpenTag(ofs, depth, style.latexname());
2332 case LATEX_ENVIRONMENT:
2333 case LATEX_ITEM_ENVIRONMENT:
2334 if (depth == par->depth
2335 && environment_stack[depth] != style.latexname()
2336 && !environment_stack[depth].empty()) {
2338 sgmlCloseTag(ofs, depth,
2339 environment_stack[depth]);
2340 environment_stack[depth].erase();
2342 if (depth < par->depth) {
2344 environment_stack[depth].erase();
2346 if (environment_stack[depth] != style.latexname()) {
2348 string const temp = "p";
2349 sgmlOpenTag(ofs, depth, temp);
2351 environment_stack[depth] = style.latexname();
2352 sgmlOpenTag(ofs, depth,
2353 environment_stack[depth]);
2355 if (style.latextype == LATEX_ENVIRONMENT) break;
2357 desc_on = (style.labeltype == LABEL_MANUAL);
2364 sgmlOpenTag(ofs, depth + 1, item_name);
2367 sgmlOpenTag(ofs, depth, style.latexname());
2374 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2378 linuxDocHandleFootnote(ofs, par, depth);
2380 while(par && par->IsDummy());
2384 // write closing SGML tags
2385 switch (style.latextype) {
2387 case LATEX_ENVIRONMENT:
2388 case LATEX_ITEM_ENVIRONMENT:
2391 sgmlCloseTag(ofs, depth, style.latexname());
2397 for (; depth > 0; --depth)
2398 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2400 if (!environment_stack[depth].empty())
2401 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2405 sgmlCloseTag(ofs, 0, top_element);
2409 // How to check for successful close
2414 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2417 string const tag = "footnote";
2419 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2420 sgmlOpenTag(os, depth + 1, tag);
2421 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2422 sgmlCloseTag(os, depth + 1, tag);
2429 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2430 int depth, int desc_on,
2431 LyXParagraph * & par)
2433 LyXParagraph * tpar = par;
2436 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2438 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2442 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2443 "Caption").second) {
2444 sgmlOpenTag(os, depth + 1, inner_tag);
2446 SimpleDocBookOnePar(os, extra_par, tpar,
2447 desc_on, depth + 2);
2448 sgmlCloseTag(os, depth+1, inner_tag);
2449 if (!extra_par.empty())
2456 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2459 string tag, inner_tag;
2460 string tmp_par, extra_par;
2461 bool inner_span = false;
2464 // Someone should give this enum a proper name (Lgb)
2472 SOME_ENUM last = NO_ONE;
2473 SOME_ENUM present = FOOTNOTE_LIKE;
2475 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2476 if (last == present) {
2478 if (!tmp_par.empty()) {
2481 sgmlCloseTag(os, depth + 1, inner_tag);
2482 sgmlOpenTag(os, depth + 1, inner_tag);
2489 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2491 if (!extra_par.empty()) os << extra_par;
2492 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2495 switch (par->footnotekind) {
2496 case LyXParagraph::FOOTNOTE:
2497 case LyXParagraph::ALGORITHM:
2500 present = FOOTNOTE_LIKE;
2503 case LyXParagraph::MARGIN:
2506 present = MARGIN_LIKE;
2509 case LyXParagraph::FIG:
2510 case LyXParagraph::WIDE_FIG:
2512 inner_tag = "title";
2516 case LyXParagraph::TAB:
2517 case LyXParagraph::WIDE_TAB:
2519 inner_tag = "title";
2524 sgmlOpenTag(os, depth, tag);
2525 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2526 DocBookHandleCaption(os, inner_tag, depth,
2530 sgmlOpenTag(os, depth + 1, inner_tag);
2533 // ignore all caption here, we processed them above!!!
2534 if (par->layout != textclasslist
2535 .NumberOfLayout(params.textclass,
2536 "Caption").second) {
2537 std::ostringstream ost;
2538 SimpleDocBookOnePar(ost, extra_par, par,
2539 desc_on, depth + 2);
2540 tmp_par += ost.str().c_str();
2542 tmp_par = frontStrip(strip(tmp_par));
2548 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2549 if (!extra_par.empty()) os << extra_par;
2550 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2555 // push a tag in a style stack
2556 void Buffer::push_tag(ostream & os, string const & tag,
2557 int & pos, char stack[5][3])
2559 #ifdef WITH_WARNINGS
2560 #warning Use a real stack! (Lgb)
2562 // pop all previous tags
2563 for (int j = pos; j >= 0; --j)
2564 os << "</" << stack[j] << ">";
2567 sprintf(stack[++pos], "%s", tag.c_str());
2570 for (int i = 0; i <= pos; ++i)
2571 os << "<" << stack[i] << ">";
2575 void Buffer::pop_tag(ostream & os, string const & tag,
2576 int & pos, char stack[5][3])
2578 #ifdef WITH_WARNINGS
2579 #warning Use a real stack! (Lgb)
2581 // Please, Lars, do not remove the global variable. I already
2582 // had to reintroduce it twice! (JMarc)
2583 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2587 // pop all tags till specified one
2588 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2589 os << "</" << stack[j] << ">";
2592 os << "</" << tag << ">";
2594 // push all tags, but the specified one
2595 for (j = j + 1; j <= pos; ++j) {
2596 os << "<" << stack[j] << ">";
2597 strcpy(stack[j - 1], stack[j]);
2601 // pop all tags till specified one
2603 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2604 os << "</" << stack[j] << ">";
2607 os << "</" << tag << ">";
2609 // push all tags, but the specified one
2610 for (int i = j + 1; i <= pos; ++i) {
2611 os << "<" << stack[i] << ">";
2612 strcpy(stack[i - 1], stack[i]);
2619 // Handle internal paragraph parsing -- layout already processed.
2621 // checks, if newcol chars should be put into this line
2622 // writes newline, if necessary.
2624 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2625 string::size_type newcol)
2628 if (colcount > lyxrc.ascii_linelen) {
2630 colcount = newcol; // assume write after this call
2635 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2636 int desc_on, int /*depth*/)
2641 LyXParagraph::size_type main_body;
2643 LyXLayout const & style = textclasslist.Style(params.textclass,
2646 char family_type = 0; // family font flag
2647 bool is_bold = false; // series font flag
2648 char shape_type = 0; // shape font flag
2649 bool is_em = false; // emphasis (italic) font flag
2651 int stack_num = -1; // style stack position
2652 // Can this be rewritten to use a std::stack, please. (Lgb)
2653 char stack[5][3]; // style stack
2654 string::size_type char_line_count = 5; // Heuristic choice ;-)
2656 if (style.labeltype != LABEL_MANUAL)
2659 main_body = par->BeginningOfMainBody();
2661 // gets paragraph main font
2663 font1 = style.labelfont;
2668 // parsing main loop
2669 for (LyXParagraph::size_type i = 0;
2670 i < par->size(); ++i) {
2682 LyXFont const font2 = par->getFont(params, i);
2684 if (font1.family() != font2.family()) {
2685 switch (family_type) {
2687 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2688 push_tag(os, "tt", stack_num, stack);
2691 else if (font2.family() == LyXFont::SANS_FAMILY) {
2692 push_tag(os, "sf", stack_num, stack);
2697 pop_tag(os, "tt", stack_num, stack);
2698 if (font2.family() == LyXFont::SANS_FAMILY) {
2699 push_tag(os, "sf", stack_num, stack);
2706 pop_tag(os, "sf", stack_num, stack);
2707 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2708 push_tag(os, "tt", stack_num, stack);
2717 if (font1.series() != font2.series()) {
2718 if (font2.series() == LyXFont::BOLD_SERIES) {
2719 push_tag(os, "bf", stack_num, stack);
2721 } else if (is_bold) {
2722 pop_tag(os, "bf", stack_num, stack);
2727 // handle italic and slanted fonts
2728 if (font1.shape() != font2.shape()) {
2729 switch (shape_type) {
2731 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2732 push_tag(os, "it", stack_num, stack);
2734 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2735 push_tag(os, "sl", stack_num, stack);
2740 pop_tag(os, "it", stack_num, stack);
2741 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2742 push_tag(os, "sl", stack_num, stack);
2749 pop_tag(os, "sl", stack_num, stack);
2750 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2751 push_tag(os, "it", stack_num, stack);
2759 if (font1.emph() != font2.emph()) {
2760 if (font2.emph() == LyXFont::ON) {
2761 push_tag(os, "em", stack_num, stack);
2764 pop_tag(os, "em", stack_num, stack);
2769 c = par->GetChar(i);
2771 if (c == LyXParagraph::META_INSET) {
2772 inset = par->GetInset(i);
2773 inset->Linuxdoc(this, os);
2776 if (font2.latex() == LyXFont::ON) {
2777 // "TeX"-Mode on == > SGML-Mode on.
2779 os << c; // see LaTeX-Generation...
2783 if (par->linuxDocConvertChar(c, sgml_string)
2784 && !style.free_spacing) { // in freespacing
2786 // non-breaking characters
2790 linux_doc_line_break(os, char_line_count, 6);
2794 linux_doc_line_break(os, char_line_count, 1);
2799 char_line_count += sgml_string.length();
2805 // needed if there is an optional argument but no contents
2806 if (main_body > 0 && main_body == par->size()) {
2810 // pop all defined Styles
2811 for (j = stack_num; j >= 0; --j) {
2812 linux_doc_line_break(os,
2814 3 + strlen(stack[j]));
2815 os << "</" << stack[j] << ">";
2818 // resets description flag correctly
2821 // <tag> not closed...
2822 linux_doc_line_break(os, char_line_count, 6);
2826 // fprintf(file, "</p>");
2832 // Print an error message.
2833 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2834 string const & message)
2836 // insert an error marker in text
2837 InsetError * new_inset = new InsetError(message);
2838 par->InsertInset(pos, new_inset);
2841 // This constant defines the maximum number of
2842 // environment layouts that can be nesteded.
2843 // The same applies for command layouts.
2844 // These values should be more than enough.
2845 // José Matos (1999/07/22)
2847 enum { MAX_NEST_LEVEL = 25};
2849 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2851 LyXParagraph * par = paragraph;
2853 niceFile = nice; // this will be used by Insetincludes.
2855 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2856 // Please use a real stack.
2857 string environment_stack[MAX_NEST_LEVEL];
2858 string environment_inner[MAX_NEST_LEVEL];
2859 // Please use a real stack.
2860 string command_stack[MAX_NEST_LEVEL];
2861 bool command_flag= false;
2862 int command_depth= 0, command_base= 0, cmd_depth= 0;
2864 string item_name, command_name;
2865 string c_depth, c_params, tmps;
2867 int depth = 0; // paragraph depth
2868 LyXTextClass const & tclass =
2869 textclasslist.TextClass(params.textclass);
2871 LaTeXFeatures features(params, tclass.numLayouts());
2875 tex_code_break_column = lyxrc.ascii_linelen;
2877 //tex_code_break_column = 0;
2879 ofstream ofs(fname.c_str());
2881 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2888 string sgml_includedfiles=features.getIncludedFiles(fname);
2890 ofs << "<!doctype " << top_element
2891 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2893 if (params.preamble.empty() && sgml_includedfiles.empty())
2896 ofs << "\n [ " << params.preamble
2897 << sgml_includedfiles << " \n]>\n\n";
2900 if (params.options.empty())
2901 sgmlOpenTag(ofs, 0, top_element);
2903 string top = top_element;
2905 top += params.options;
2906 sgmlOpenTag(ofs, 0, top);
2909 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2910 << "\n See http://www.lyx.org/ for more information -->\n";
2913 int desc_on = 0; // description mode
2914 LyXLayout const & style =
2915 textclasslist.Style(params.textclass,
2918 // environment tag closing
2919 for (; depth > par->depth; --depth) {
2920 if (environment_inner[depth] != "!-- --") {
2921 item_name= "listitem";
2922 sgmlCloseTag(ofs, command_depth + depth,
2924 if (environment_inner[depth] == "varlistentry")
2925 sgmlCloseTag(ofs, depth+command_depth,
2926 environment_inner[depth]);
2928 sgmlCloseTag(ofs, depth + command_depth,
2929 environment_stack[depth]);
2930 environment_stack[depth].erase();
2931 environment_inner[depth].erase();
2934 if (depth == par->depth
2935 && environment_stack[depth] != style.latexname()
2936 && !environment_stack[depth].empty()) {
2937 if (environment_inner[depth] != "!-- --") {
2938 item_name= "listitem";
2939 sgmlCloseTag(ofs, command_depth+depth,
2941 if (environment_inner[depth] == "varlistentry")
2943 depth + command_depth,
2944 environment_inner[depth]);
2947 sgmlCloseTag(ofs, depth + command_depth,
2948 environment_stack[depth]);
2950 environment_stack[depth].erase();
2951 environment_inner[depth].erase();
2954 // Write opening SGML tags.
2955 switch (style.latextype) {
2956 case LATEX_PARAGRAPH:
2957 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2962 LinuxDocError(par, 0,
2963 _("Error : Wrong depth for "
2964 "LatexType Command.\n"));
2966 command_name = style.latexname();
2968 tmps = style.latexparam();
2969 c_params = split(tmps, c_depth,'|');
2971 cmd_depth= lyx::atoi(c_depth);
2974 if (cmd_depth<command_base) {
2975 for (int j = command_depth;
2976 j >= command_base; --j)
2977 if (!command_stack[j].empty())
2978 sgmlCloseTag(ofs, j, command_stack[j]);
2979 command_depth= command_base= cmd_depth;
2980 } else if (cmd_depth <= command_depth) {
2981 for (int j = command_depth;
2982 j >= cmd_depth; --j)
2984 if (!command_stack[j].empty())
2985 sgmlCloseTag(ofs, j, command_stack[j]);
2986 command_depth= cmd_depth;
2988 command_depth= cmd_depth;
2990 command_depth = command_base = cmd_depth;
2991 command_flag = true;
2993 command_stack[command_depth]= command_name;
2995 // treat label as a special case for
2996 // more WYSIWYM handling.
2997 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2998 Inset * inset = par->GetInset(0);
2999 Inset::Code lyx_code = inset->LyxCode();
3000 if (lyx_code == Inset::LABEL_CODE){
3001 command_name += " id=\"";
3002 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3003 command_name += "\"";
3008 sgmlOpenTag(ofs, depth + command_depth, command_name);
3009 item_name = "title";
3010 if (command_name != "!-- --")
3011 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3014 case LATEX_ENVIRONMENT:
3015 case LATEX_ITEM_ENVIRONMENT:
3016 if (depth < par->depth) {
3018 environment_stack[depth].erase();
3021 if (environment_stack[depth] != style.latexname()) {
3022 environment_stack[depth] = style.latexname();
3023 environment_inner[depth] = "!-- --";
3024 sgmlOpenTag(ofs, depth + command_depth,
3025 environment_stack[depth]);
3027 if (environment_inner[depth] != "!-- --") {
3028 item_name= "listitem";
3030 command_depth + depth,
3032 if (environment_inner[depth] == "varlistentry")
3034 depth + command_depth,
3035 environment_inner[depth]);
3039 if (style.latextype == LATEX_ENVIRONMENT) {
3040 if (!style.latexparam().empty())
3041 sgmlOpenTag(ofs, depth + command_depth,
3042 style.latexparam());
3046 desc_on = (style.labeltype == LABEL_MANUAL);
3049 environment_inner[depth]= "varlistentry";
3051 environment_inner[depth]= "listitem";
3053 sgmlOpenTag(ofs, depth + 1 + command_depth,
3054 environment_inner[depth]);
3058 sgmlOpenTag(ofs, depth + 1 + command_depth,
3062 sgmlOpenTag(ofs, depth + 1 + command_depth,
3067 sgmlOpenTag(ofs, depth + command_depth,
3076 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3077 depth + 1 + command_depth);
3080 DocBookHandleFootnote(ofs, par,
3081 depth + 1 + command_depth);
3083 while(par && par->IsDummy());
3086 // write closing SGML tags
3087 switch (style.latextype) {
3090 if (command_name != "!-- --")
3091 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3093 case LATEX_ENVIRONMENT:
3094 if (!style.latexparam().empty())
3095 sgmlCloseTag(ofs, depth + command_depth,
3096 style.latexparam());
3098 case LATEX_ITEM_ENVIRONMENT:
3099 if (desc_on == 1) break;
3101 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3103 case LATEX_PARAGRAPH:
3104 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3107 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3113 for (; depth >= 0; --depth) {
3114 if (!environment_stack[depth].empty()) {
3115 if (environment_inner[depth] != "!-- --") {
3116 item_name= "listitem";
3117 sgmlCloseTag(ofs, command_depth + depth,
3119 if (environment_inner[depth] == "varlistentry")
3120 sgmlCloseTag(ofs, depth + command_depth,
3121 environment_inner[depth]);
3124 sgmlCloseTag(ofs, depth + command_depth,
3125 environment_stack[depth]);
3129 for (int j = command_depth; j >= command_base; --j)
3130 if (!command_stack[j].empty())
3131 sgmlCloseTag(ofs, j, command_stack[j]);
3134 sgmlCloseTag(ofs, 0, top_element);
3137 // How to check for successful close
3141 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3142 LyXParagraph * par, int & desc_on,
3145 bool emph_flag = false;
3147 LyXLayout const & style = textclasslist.Style(params.textclass,
3150 LyXParagraph::size_type main_body;
3151 if (style.labeltype != LABEL_MANUAL)
3154 main_body = par->BeginningOfMainBody();
3156 // gets paragraph main font
3157 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3159 int char_line_count = depth;
3160 if (!style.free_spacing)
3161 for (int j = 0; j < depth; ++j)
3164 // parsing main loop
3165 for (LyXParagraph::size_type i = 0;
3166 i < par->size(); ++i) {
3167 LyXFont font2 = par->getFont(params, i);
3169 // handle <emphasis> tag
3170 if (font1.emph() != font2.emph() && i) {
3171 if (font2.emph() == LyXFont::ON) {
3175 os << "</emphasis>";
3180 char c = par->GetChar(i);
3182 if (c == LyXParagraph::META_INSET) {
3183 Inset * inset = par->GetInset(i);
3184 std::ostringstream ost;
3185 inset->DocBook(this, ost);
3186 string tmp_out = ost.str().c_str();
3189 // This code needs some explanation:
3190 // Two insets are treated specially
3191 // label if it is the first element in a command paragraph
3193 // graphics inside tables or figure floats can't go on
3194 // title (the equivalente in latex for this case is caption
3195 // and title should come first
3198 if (desc_on!= 3 || i!= 0) {
3199 if (!tmp_out.empty() && tmp_out[0] == '@') {
3201 extra += frontStrip(tmp_out, '@');
3203 os << frontStrip(tmp_out, '@');
3208 } else if (font2.latex() == LyXFont::ON) {
3209 // "TeX"-Mode on ==> SGML-Mode on.
3215 if (par->linuxDocConvertChar(c, sgml_string)
3216 && !style.free_spacing) { // in freespacing
3218 // non-breaking characters
3222 os << "\n</term><listitem><para>";
3234 // needed if there is an optional argument but no contents
3235 if (main_body > 0 && main_body == par->size()) {
3239 os << "</emphasis>";
3242 // resets description flag correctly
3245 // <term> not closed...
3253 // This should be enabled when the Chktex class is implemented. (Asger)
3254 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3255 // Other flags: -wall -v0 -x
3256 int Buffer::runChktex()
3258 if (!users->text) return 0;
3260 ProhibitInput(users);
3262 // get LaTeX-Filename
3263 string const name = getLatexName();
3264 string path = OnlyPath(filename);
3266 string const org_path = path;
3267 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3271 Path p(path); // path to LaTeX file
3272 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3274 // Remove all error insets
3275 bool const removedErrorInsets = users->removeAutoInsets();
3277 // Generate the LaTeX file if neccessary
3278 makeLaTeXFile(name, org_path, false);
3281 Chktex chktex(lyxrc.chktex_command, name, filepath);
3282 int res = chktex.run(terr); // run chktex
3285 WriteAlert(_("chktex did not work!"),
3286 _("Could not run with file:"), name);
3287 } else if (res > 0) {
3288 // Insert all errors as errors boxes
3289 users->insertErrors(terr);
3292 // if we removed error insets before we ran chktex or if we inserted
3293 // error insets after we ran chktex, this must be run:
3294 if (removedErrorInsets || res){
3296 users->fitCursor(users->text);
3304 void Buffer::validate(LaTeXFeatures & features) const
3306 LyXParagraph * par = paragraph;
3307 LyXTextClass const & tclass =
3308 textclasslist.TextClass(params.textclass);
3310 // AMS Style is at document level
3312 features.amsstyle = (params.use_amsmath ||
3313 tclass.provides(LyXTextClass::amsmath));
3316 // We don't use "lyxerr.debug" because of speed. (Asger)
3317 if (lyxerr.debugging(Debug::LATEX))
3318 lyxerr << "Paragraph: " << par << endl;
3320 // Now just follow the list of paragraphs and run
3321 // validate on each of them.
3322 par->validate(features);
3324 // and then the next paragraph
3328 // the bullet shapes are buffer level not paragraph level
3329 // so they are tested here
3330 for (int i = 0; i < 4; ++i) {
3331 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3332 int const font = params.user_defined_bullets[i].getFont();
3334 int const c = params
3335 .user_defined_bullets[i]
3342 features.latexsym = true;
3344 } else if (font == 1) {
3345 features.amssymb = true;
3346 } else if ((font >= 2 && font <= 5)) {
3347 features.pifont = true;
3352 if (lyxerr.debugging(Debug::LATEX)) {
3353 features.showStruct();
3358 void Buffer::setPaperStuff()
3360 params.papersize = BufferParams::PAPER_DEFAULT;
3361 char const c1 = params.paperpackage;
3362 if (c1 == BufferParams::PACKAGE_NONE) {
3363 char const c2 = params.papersize2;
3364 if (c2 == BufferParams::VM_PAPER_USLETTER)
3365 params.papersize = BufferParams::PAPER_USLETTER;
3366 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3367 params.papersize = BufferParams::PAPER_LEGALPAPER;
3368 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3369 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3370 else if (c2 == BufferParams::VM_PAPER_A3)
3371 params.papersize = BufferParams::PAPER_A3PAPER;
3372 else if (c2 == BufferParams::VM_PAPER_A4)
3373 params.papersize = BufferParams::PAPER_A4PAPER;
3374 else if (c2 == BufferParams::VM_PAPER_A5)
3375 params.papersize = BufferParams::PAPER_A5PAPER;
3376 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3377 (c2 == BufferParams::VM_PAPER_B5))
3378 params.papersize = BufferParams::PAPER_B5PAPER;
3379 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3380 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3381 params.papersize = BufferParams::PAPER_A4PAPER;
3385 // This function should be in Buffer because it's a buffer's property (ale)
3386 string const Buffer::getIncludeonlyList(char delim)
3389 for (inset_iterator it = inset_iterator_begin();
3390 it != inset_iterator_end(); ++it) {
3391 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3392 InsetInclude * insetinc =
3393 static_cast<InsetInclude *>(*it);
3394 if (insetinc->isInclude()
3395 && insetinc->isNoLoad()) {
3398 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3402 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3407 vector<string> const Buffer::getLabelList()
3409 /// if this is a child document and the parent is already loaded
3410 /// Use the parent's list instead [ale990407]
3411 if (!params.parentname.empty()
3412 && bufferlist.exists(params.parentname)) {
3413 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3415 return tmp->getLabelList();
3418 vector<string> label_list;
3419 for (inset_iterator it = inset_iterator_begin();
3420 it != inset_iterator_end(); ++it) {
3421 vector<string> const l = (*it)->getLabelList();
3422 label_list.insert(label_list.end(), l.begin(), l.end());
3428 vector<vector<Buffer::TocItem> > const Buffer::getTocList() const
3433 vector<vector<TocItem> > l(4);
3434 LyXParagraph * par = paragraph;
3437 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3438 if (textclasslist.Style(params.textclass,
3439 par->GetLayout()).labeltype
3440 == LABEL_SENSITIVE) {
3444 tmp.str = par->String(this, false);
3445 switch (par->footnotekind) {
3446 case LyXParagraph::FIG:
3447 case LyXParagraph::WIDE_FIG:
3448 tmp.str = tostr(++figs) + ". "
3450 l[TOC_LOF].push_back(tmp);
3452 case LyXParagraph::TAB:
3453 case LyXParagraph::WIDE_TAB:
3454 tmp.str = tostr(++tables) + ". "
3456 l[TOC_LOT].push_back(tmp);
3458 case LyXParagraph::ALGORITHM:
3459 tmp.str = tostr(++algs) + ". "
3461 l[TOC_LOA].push_back(tmp);
3463 case LyXParagraph::FOOTNOTE:
3464 case LyXParagraph::MARGIN:
3468 } else if (!par->IsDummy()) {
3470 char const labeltype =
3471 textclasslist.Style(params.textclass,
3472 par->GetLayout()).labeltype;
3474 if (labeltype >= LABEL_COUNTER_CHAPTER
3475 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3476 // insert this into the table of contents
3481 textclasslist.TextClass(params.textclass).maxcounter());
3482 tmp.str = par->String(this, true);
3483 l[TOC_TOC].push_back(tmp);
3494 // This is also a buffer property (ale)
3495 vector<pair<string,string> > const Buffer::getBibkeyList()
3497 /// if this is a child document and the parent is already loaded
3498 /// Use the parent's list instead [ale990412]
3499 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3500 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3502 return tmp->getBibkeyList();
3505 vector<pair<string, string> > keys;
3506 LyXParagraph * par = paragraph;
3509 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3510 par->String(this, false)));
3514 // Might be either using bibtex or a child has bibliography
3516 for (inset_iterator it = inset_iterator_begin();
3517 it != inset_iterator_end(); ++it) {
3518 // Search for Bibtex or Include inset
3519 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3520 vector<pair<string,string> > tmp =
3521 static_cast<InsetBibtex*>(*it)->getKeys(this);
3522 keys.insert(keys.end(), tmp.begin(), tmp.end());
3523 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3524 vector<pair<string,string> > const tmp =
3525 static_cast<InsetInclude*>(*it)->getKeys();
3526 keys.insert(keys.end(), tmp.begin(), tmp.end());
3535 bool Buffer::isDepClean(string const & name) const
3537 DEPCLEAN * item = dep_clean;
3538 while (item && item->master != name)
3540 if (!item) return true;
3545 void Buffer::markDepClean(string const & name)
3548 dep_clean = new DEPCLEAN;
3549 dep_clean->clean = true;
3550 dep_clean->master = name;
3551 dep_clean->next = 0;
3553 DEPCLEAN * item = dep_clean;
3554 while (item && item->master != name)
3559 item = new DEPCLEAN;
3561 item->master = name;
3568 bool Buffer::Dispatch(string const & command)
3570 // Split command string into command and argument
3572 string line = frontStrip(command);
3573 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3575 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3579 bool Buffer::Dispatch(int action, string const & argument)
3581 bool dispatched = true;
3584 Exporter::Export(this, argument, false);
3594 void Buffer::resize()
3596 /// resize the BufferViews!
3602 void Buffer::resizeInsets(BufferView * bv)
3604 /// then remove all LyXText in text-insets
3605 LyXParagraph * par = paragraph;
3606 for (; par; par = par->next) {
3607 par->resizeInsetsLyXText(bv);
3611 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3614 LyXParagraph * par = paragraph;
3616 par->ChangeLanguage(params, from, to);
3622 bool Buffer::isMultiLingual()
3624 LyXParagraph * par = paragraph;
3626 if (par->isMultiLingual(params))
3634 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3635 LyXParagraph::size_type pos)
3638 it = par->InsetIterator(pos);
3639 if (it == par->inset_iterator_end()) {
3646 void Buffer::inset_iterator::SetParagraph()
3649 it = par->inset_iterator_begin();
3650 if (it != par->inset_iterator_end())
3655 // We maintain an invariant that whenever par = 0 then it = 0