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") // This seems necessary
1713 features.UsedLanguages.insert(default_language);
1714 #ifdef DO_USE_DEFAULT_LANGUAGE
1715 if (params.language->lang() != "default" ||
1716 !features.UsedLanguages.empty()) {
1719 for (LaTeXFeatures::LanguageList::const_iterator cit =
1720 features.UsedLanguages.begin();
1721 cit != features.UsedLanguages.end(); ++cit)
1722 options += (*cit)->babel() + ",";
1723 options += params.language->babel() + ',';
1724 #ifdef DO_USE_DEFAULT_LANGUAGE
1728 // the user-defined options
1729 if (!params.options.empty()) {
1730 options += params.options + ',';
1733 if (!options.empty()){
1734 options = strip(options, ',');
1735 ofs << '[' << options << ']';
1739 << textclasslist.LatexnameOfClass(params.textclass)
1742 // end of \documentclass defs
1744 // font selection must be done before loading fontenc.sty
1745 if (params.fonts != "default") {
1746 ofs << "\\usepackage{" << params.fonts << "}\n";
1749 // this one is not per buffer
1750 if (lyxrc.fontenc != "default") {
1751 ofs << "\\usepackage[" << lyxrc.fontenc
1756 if (params.inputenc == "auto") {
1757 string const doc_encoding =
1758 params.language->encoding()->LatexName();
1760 // Create a list with all the input encodings used
1762 set<string> encodings;
1763 for (LaTeXFeatures::LanguageList::const_iterator it =
1764 features.UsedLanguages.begin();
1765 it != features.UsedLanguages.end(); ++it)
1766 if ((*it)->encoding()->LatexName() != doc_encoding)
1767 encodings.insert((*it)->encoding()->LatexName());
1769 ofs << "\\usepackage[";
1770 std::copy(encodings.begin(), encodings.end(),
1771 std::ostream_iterator<string>(ofs, ","));
1772 ofs << doc_encoding << "]{inputenc}\n";
1774 } else if (params.inputenc != "default") {
1775 ofs << "\\usepackage[" << params.inputenc
1780 // At the very beginning the text parameters.
1781 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1782 switch (params.paperpackage) {
1783 case BufferParams::PACKAGE_A4:
1784 ofs << "\\usepackage{a4}\n";
1787 case BufferParams::PACKAGE_A4WIDE:
1788 ofs << "\\usepackage{a4wide}\n";
1791 case BufferParams::PACKAGE_WIDEMARGINSA4:
1792 ofs << "\\usepackage[widemargins]{a4}\n";
1797 if (params.use_geometry) {
1798 ofs << "\\usepackage{geometry}\n";
1800 ofs << "\\geometry{verbose";
1801 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1802 ofs << ",landscape";
1803 switch (params.papersize2) {
1804 case BufferParams::VM_PAPER_CUSTOM:
1805 if (!params.paperwidth.empty())
1806 ofs << ",paperwidth="
1807 << params.paperwidth;
1808 if (!params.paperheight.empty())
1809 ofs << ",paperheight="
1810 << params.paperheight;
1812 case BufferParams::VM_PAPER_USLETTER:
1813 ofs << ",letterpaper";
1815 case BufferParams::VM_PAPER_USLEGAL:
1816 ofs << ",legalpaper";
1818 case BufferParams::VM_PAPER_USEXECUTIVE:
1819 ofs << ",executivepaper";
1821 case BufferParams::VM_PAPER_A3:
1824 case BufferParams::VM_PAPER_A4:
1827 case BufferParams::VM_PAPER_A5:
1830 case BufferParams::VM_PAPER_B3:
1833 case BufferParams::VM_PAPER_B4:
1836 case BufferParams::VM_PAPER_B5:
1840 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1841 switch (lyxrc.default_papersize) {
1842 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1843 case BufferParams::PAPER_USLETTER:
1844 ofs << ",letterpaper";
1846 case BufferParams::PAPER_LEGALPAPER:
1847 ofs << ",legalpaper";
1849 case BufferParams::PAPER_EXECUTIVEPAPER:
1850 ofs << ",executivepaper";
1852 case BufferParams::PAPER_A3PAPER:
1855 case BufferParams::PAPER_A4PAPER:
1858 case BufferParams::PAPER_A5PAPER:
1861 case BufferParams::PAPER_B5PAPER:
1866 if (!params.topmargin.empty())
1867 ofs << ",tmargin=" << params.topmargin;
1868 if (!params.bottommargin.empty())
1869 ofs << ",bmargin=" << params.bottommargin;
1870 if (!params.leftmargin.empty())
1871 ofs << ",lmargin=" << params.leftmargin;
1872 if (!params.rightmargin.empty())
1873 ofs << ",rmargin=" << params.rightmargin;
1874 if (!params.headheight.empty())
1875 ofs << ",headheight=" << params.headheight;
1876 if (!params.headsep.empty())
1877 ofs << ",headsep=" << params.headsep;
1878 if (!params.footskip.empty())
1879 ofs << ",footskip=" << params.footskip;
1883 if (params.use_amsmath
1884 && !tclass.provides(LyXTextClass::amsmath)) {
1885 ofs << "\\usepackage{amsmath}\n";
1889 if (tokenPos(tclass.opt_pagestyle(),
1890 '|', params.pagestyle) >= 0) {
1891 if (params.pagestyle == "fancy") {
1892 ofs << "\\usepackage{fancyhdr}\n";
1895 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1899 // We try to load babel late, in case it interferes
1900 // with other packages.
1902 ofs << lyxrc.language_package << endl;
1906 if (params.secnumdepth != tclass.secnumdepth()) {
1907 ofs << "\\setcounter{secnumdepth}{"
1908 << params.secnumdepth
1912 if (params.tocdepth != tclass.tocdepth()) {
1913 ofs << "\\setcounter{tocdepth}{"
1919 if (params.paragraph_separation) {
1920 switch (params.defskip.kind()) {
1921 case VSpace::SMALLSKIP:
1922 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1924 case VSpace::MEDSKIP:
1925 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1927 case VSpace::BIGSKIP:
1928 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1930 case VSpace::LENGTH:
1931 ofs << "\\setlength\\parskip{"
1932 << params.defskip.length().asLatexString()
1935 default: // should never happen // Then delete it.
1936 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1941 ofs << "\\setlength\\parindent{0pt}\n";
1945 // Now insert the LyX specific LaTeX commands...
1947 // The optional packages;
1948 string preamble(features.getPackages());
1950 // this might be useful...
1951 preamble += "\n\\makeatletter\n";
1953 // Some macros LyX will need
1954 string tmppreamble(features.getMacros());
1956 if (!tmppreamble.empty()) {
1957 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1958 "LyX specific LaTeX commands.\n"
1959 + tmppreamble + '\n';
1962 // the text class specific preamble
1963 tmppreamble = features.getTClassPreamble();
1964 if (!tmppreamble.empty()) {
1965 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1966 "Textclass specific LaTeX commands.\n"
1967 + tmppreamble + '\n';
1970 /* the user-defined preamble */
1971 if (!params.preamble.empty()) {
1972 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1973 "User specified LaTeX commands.\n"
1974 + params.preamble + '\n';
1977 preamble += "\\makeatother\n";
1979 // Itemize bullet settings need to be last in case the user
1980 // defines their own bullets that use a package included
1981 // in the user-defined preamble -- ARRae
1982 // Actually it has to be done much later than that
1983 // since some packages like frenchb make modifications
1984 // at \begin{document} time -- JMarc
1986 for (int i = 0; i < 4; ++i) {
1987 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1988 if (bullets_def.empty())
1989 bullets_def="\\AtBeginDocument{\n";
1990 bullets_def += " \\renewcommand{\\labelitemi";
1992 // `i' is one less than the item to modify
1999 bullets_def += "ii";
2005 bullets_def += "}{" +
2006 params.user_defined_bullets[i].getText()
2011 if (!bullets_def.empty())
2012 preamble += bullets_def + "}\n\n";
2014 for (int j = countChar(preamble, '\n'); j-- ;) {
2021 ofs << "\\begin{document}\n";
2024 lyxerr.debug() << "preamble finished, now the body." << endl;
2025 #ifdef DO_USE_DEFAULT_LANGUAGE
2026 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2028 if (!lyxrc.language_auto_begin) {
2030 ofs << subst(lyxrc.language_command_begin, "$$lang",
2031 params.language->babel())
2036 latexParagraphs(ofs, paragraph, 0, texrow);
2038 // add this just in case after all the paragraphs
2042 #ifdef DO_USE_DEFAULT_LANGUAGE
2043 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2045 if (!lyxrc.language_auto_end) {
2047 ofs << subst(lyxrc.language_command_end, "$$lang",
2048 params.language->babel())
2054 ofs << "\\end{document}\n";
2057 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2059 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2063 // Just to be sure. (Asger)
2066 // tex_code_break_column's value is used to decide
2067 // if we are in batchmode or not (within mathed_write()
2068 // in math_write.C) so we must set it to a non-zero
2069 // value when we leave otherwise we save incorrect .lyx files.
2070 tex_code_break_column = lyxrc.ascii_linelen;
2074 lyxerr << "File was not closed properly." << endl;
2077 lyxerr.debug() << "Finished making latex file." << endl;
2082 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2084 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2085 LyXParagraph * endpar, TexRow & texrow) const
2087 bool was_title = false;
2088 bool already_title = false;
2089 std::ostringstream ftnote;
2094 while (par != endpar) {
2097 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2100 LyXLayout const & layout =
2101 textclasslist.Style(params.textclass,
2104 if (layout.intitle) {
2105 if (already_title) {
2106 lyxerr <<"Error in latexParagraphs: You"
2107 " should not mix title layouts"
2108 " with normal ones." << endl;
2111 } else if (was_title && !already_title) {
2112 ofs << "\\maketitle\n";
2114 already_title = true;
2117 // We are at depth 0 so we can just use
2118 // ordinary \footnote{} generation
2119 // flag this with ftcount
2121 if (layout.isEnvironment()
2122 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2123 par = par->TeXEnvironment(this, params, ofs, texrow
2125 ,ftnote, ft_texrow, ftcount
2129 par = par->TeXOnePar(this, params, ofs, texrow, false
2132 ftnote, ft_texrow, ftcount
2137 // Write out what we've generated...
2140 ofs << "\\addtocounter{footnote}{-"
2144 ofs << ftnote.str();
2145 texrow += ft_texrow;
2147 // The extra .c_str() is needed when we use
2148 // lyxstring instead of the STL string class.
2149 ftnote.str(string().c_str());
2154 // It might be that we only have a title in this document
2155 if (was_title && !already_title) {
2156 ofs << "\\maketitle\n";
2162 bool Buffer::isLatex() const
2164 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2168 bool Buffer::isLinuxDoc() const
2170 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2174 bool Buffer::isLiterate() const
2176 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2180 bool Buffer::isDocBook() const
2182 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2186 bool Buffer::isSGML() const
2188 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2189 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2193 void Buffer::sgmlOpenTag(ostream & os, int depth,
2194 string const & latexname) const
2196 if (latexname != "!-- --")
2197 os << string(depth, ' ') << "<" << latexname << ">\n";
2201 void Buffer::sgmlCloseTag(ostream & os, int depth,
2202 string const & latexname) const
2204 if (latexname != "!-- --")
2205 os << string(depth, ' ') << "</" << latexname << ">\n";
2209 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2211 LyXParagraph * par = paragraph;
2213 niceFile = nice; // this will be used by Insetincludes.
2215 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2216 string environment_stack[10];
2219 int depth = 0; // paragraph depth
2221 ofstream ofs(fname.c_str());
2224 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2228 LyXTextClass const & tclass =
2229 textclasslist.TextClass(params.textclass);
2231 LaTeXFeatures features(params, tclass.numLayouts());
2235 tex_code_break_column = lyxrc.ascii_linelen;
2237 //tex_code_break_column = 0;
2242 string sgml_includedfiles=features.getIncludedFiles(fname);
2244 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2245 ofs << "<!doctype linuxdoc system>\n\n";
2247 ofs << "<!doctype linuxdoc system [ "
2248 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2251 if (params.options.empty())
2252 sgmlOpenTag(ofs, 0, top_element);
2254 string top = top_element;
2256 top += params.options;
2257 sgmlOpenTag(ofs, 0, top);
2261 ofs << "<!-- " << LYX_DOCVERSION
2262 << " created this file. For more info see http://www.lyx.org/"
2266 int desc_on = 0; // description mode
2267 LyXLayout const & style =
2268 textclasslist.Style(params.textclass,
2271 // treat <toc> as a special case for compatibility with old code
2272 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2273 Inset * inset = par->GetInset(0);
2274 Inset::Code lyx_code = inset->LyxCode();
2275 if (lyx_code == Inset::TOC_CODE){
2276 string const temp = "toc";
2277 sgmlOpenTag(ofs, depth, temp);
2281 linuxDocHandleFootnote(ofs, par, depth);
2287 // environment tag closing
2288 for (; depth > par->depth; --depth) {
2289 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2290 environment_stack[depth].erase();
2293 // write opening SGML tags
2294 switch (style.latextype) {
2295 case LATEX_PARAGRAPH:
2296 if (depth == par->depth
2297 && !environment_stack[depth].empty()) {
2298 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2299 environment_stack[depth].erase();
2305 sgmlOpenTag(ofs, depth, style.latexname());
2310 LinuxDocError(par, 0,
2311 _("Error : Wrong depth for"
2312 " LatexType Command.\n"));
2314 if (!environment_stack[depth].empty()){
2315 sgmlCloseTag(ofs, depth,
2316 environment_stack[depth]);
2320 environment_stack[depth].erase();
2321 sgmlOpenTag(ofs, depth, style.latexname());
2324 case LATEX_ENVIRONMENT:
2325 case LATEX_ITEM_ENVIRONMENT:
2326 if (depth == par->depth
2327 && environment_stack[depth] != style.latexname()
2328 && !environment_stack[depth].empty()) {
2330 sgmlCloseTag(ofs, depth,
2331 environment_stack[depth]);
2332 environment_stack[depth].erase();
2334 if (depth < par->depth) {
2336 environment_stack[depth].erase();
2338 if (environment_stack[depth] != style.latexname()) {
2340 string const temp = "p";
2341 sgmlOpenTag(ofs, depth, temp);
2343 environment_stack[depth] = style.latexname();
2344 sgmlOpenTag(ofs, depth,
2345 environment_stack[depth]);
2347 if (style.latextype == LATEX_ENVIRONMENT) break;
2349 desc_on = (style.labeltype == LABEL_MANUAL);
2356 sgmlOpenTag(ofs, depth + 1, item_name);
2359 sgmlOpenTag(ofs, depth, style.latexname());
2366 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2370 linuxDocHandleFootnote(ofs, par, depth);
2372 while(par && par->IsDummy());
2376 // write closing SGML tags
2377 switch (style.latextype) {
2379 case LATEX_ENVIRONMENT:
2380 case LATEX_ITEM_ENVIRONMENT:
2383 sgmlCloseTag(ofs, depth, style.latexname());
2389 for (; depth > 0; --depth)
2390 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2392 if (!environment_stack[depth].empty())
2393 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2397 sgmlCloseTag(ofs, 0, top_element);
2401 // How to check for successful close
2406 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2409 string const tag = "footnote";
2411 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2412 sgmlOpenTag(os, depth + 1, tag);
2413 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2414 sgmlCloseTag(os, depth + 1, tag);
2421 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2422 int depth, int desc_on,
2423 LyXParagraph * & par)
2425 LyXParagraph * tpar = par;
2428 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2430 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2434 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2435 "Caption").second) {
2436 sgmlOpenTag(os, depth + 1, inner_tag);
2438 SimpleDocBookOnePar(os, extra_par, tpar,
2439 desc_on, depth + 2);
2440 sgmlCloseTag(os, depth+1, inner_tag);
2441 if (!extra_par.empty())
2448 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2451 string tag, inner_tag;
2452 string tmp_par, extra_par;
2453 bool inner_span = false;
2456 // Someone should give this enum a proper name (Lgb)
2464 SOME_ENUM last = NO_ONE;
2465 SOME_ENUM present = FOOTNOTE_LIKE;
2467 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2468 if (last == present) {
2470 if (!tmp_par.empty()) {
2473 sgmlCloseTag(os, depth + 1, inner_tag);
2474 sgmlOpenTag(os, depth + 1, inner_tag);
2481 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2483 if (!extra_par.empty()) os << extra_par;
2484 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2487 switch (par->footnotekind) {
2488 case LyXParagraph::FOOTNOTE:
2489 case LyXParagraph::ALGORITHM:
2492 present = FOOTNOTE_LIKE;
2495 case LyXParagraph::MARGIN:
2498 present = MARGIN_LIKE;
2501 case LyXParagraph::FIG:
2502 case LyXParagraph::WIDE_FIG:
2504 inner_tag = "title";
2508 case LyXParagraph::TAB:
2509 case LyXParagraph::WIDE_TAB:
2511 inner_tag = "title";
2516 sgmlOpenTag(os, depth, tag);
2517 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2518 DocBookHandleCaption(os, inner_tag, depth,
2522 sgmlOpenTag(os, depth + 1, inner_tag);
2525 // ignore all caption here, we processed them above!!!
2526 if (par->layout != textclasslist
2527 .NumberOfLayout(params.textclass,
2528 "Caption").second) {
2529 std::ostringstream ost;
2530 SimpleDocBookOnePar(ost, extra_par, par,
2531 desc_on, depth + 2);
2532 tmp_par += ost.str().c_str();
2534 tmp_par = frontStrip(strip(tmp_par));
2540 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2541 if (!extra_par.empty()) os << extra_par;
2542 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2547 // push a tag in a style stack
2548 void Buffer::push_tag(ostream & os, string const & tag,
2549 int & pos, char stack[5][3])
2551 #ifdef WITH_WARNINGS
2552 #warning Use a real stack! (Lgb)
2554 // pop all previous tags
2555 for (int j = pos; j >= 0; --j)
2556 os << "</" << stack[j] << ">";
2559 sprintf(stack[++pos], "%s", tag.c_str());
2562 for (int i = 0; i <= pos; ++i)
2563 os << "<" << stack[i] << ">";
2567 void Buffer::pop_tag(ostream & os, string const & tag,
2568 int & pos, char stack[5][3])
2570 #ifdef WITH_WARNINGS
2571 #warning Use a real stack! (Lgb)
2573 // Please, Lars, do not remove the global variable. I already
2574 // had to reintroduce it twice! (JMarc)
2575 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2579 // pop all tags till specified one
2580 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2581 os << "</" << stack[j] << ">";
2584 os << "</" << tag << ">";
2586 // push all tags, but the specified one
2587 for (j = j + 1; j <= pos; ++j) {
2588 os << "<" << stack[j] << ">";
2589 strcpy(stack[j - 1], stack[j]);
2593 // pop all tags till specified one
2595 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2596 os << "</" << stack[j] << ">";
2599 os << "</" << tag << ">";
2601 // push all tags, but the specified one
2602 for (int i = j + 1; i <= pos; ++i) {
2603 os << "<" << stack[i] << ">";
2604 strcpy(stack[i - 1], stack[i]);
2611 // Handle internal paragraph parsing -- layout already processed.
2613 // checks, if newcol chars should be put into this line
2614 // writes newline, if necessary.
2616 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2617 string::size_type newcol)
2620 if (colcount > lyxrc.ascii_linelen) {
2622 colcount = newcol; // assume write after this call
2627 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2628 int desc_on, int /*depth*/)
2633 LyXParagraph::size_type main_body;
2635 LyXLayout const & style = textclasslist.Style(params.textclass,
2638 char family_type = 0; // family font flag
2639 bool is_bold = false; // series font flag
2640 char shape_type = 0; // shape font flag
2641 bool is_em = false; // emphasis (italic) font flag
2643 int stack_num = -1; // style stack position
2644 // Can this be rewritten to use a std::stack, please. (Lgb)
2645 char stack[5][3]; // style stack
2646 string::size_type char_line_count = 5; // Heuristic choice ;-)
2648 if (style.labeltype != LABEL_MANUAL)
2651 main_body = par->BeginningOfMainBody();
2653 // gets paragraph main font
2655 font1 = style.labelfont;
2660 // parsing main loop
2661 for (LyXParagraph::size_type i = 0;
2662 i < par->size(); ++i) {
2674 LyXFont const font2 = par->getFont(params, i);
2676 if (font1.family() != font2.family()) {
2677 switch (family_type) {
2679 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2680 push_tag(os, "tt", stack_num, stack);
2683 else if (font2.family() == LyXFont::SANS_FAMILY) {
2684 push_tag(os, "sf", stack_num, stack);
2689 pop_tag(os, "tt", stack_num, stack);
2690 if (font2.family() == LyXFont::SANS_FAMILY) {
2691 push_tag(os, "sf", stack_num, stack);
2698 pop_tag(os, "sf", stack_num, stack);
2699 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2700 push_tag(os, "tt", stack_num, stack);
2709 if (font1.series() != font2.series()) {
2710 if (font2.series() == LyXFont::BOLD_SERIES) {
2711 push_tag(os, "bf", stack_num, stack);
2713 } else if (is_bold) {
2714 pop_tag(os, "bf", stack_num, stack);
2719 // handle italic and slanted fonts
2720 if (font1.shape() != font2.shape()) {
2721 switch (shape_type) {
2723 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2724 push_tag(os, "it", stack_num, stack);
2726 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2727 push_tag(os, "sl", stack_num, stack);
2732 pop_tag(os, "it", stack_num, stack);
2733 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2734 push_tag(os, "sl", stack_num, stack);
2741 pop_tag(os, "sl", stack_num, stack);
2742 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2743 push_tag(os, "it", stack_num, stack);
2751 if (font1.emph() != font2.emph()) {
2752 if (font2.emph() == LyXFont::ON) {
2753 push_tag(os, "em", stack_num, stack);
2756 pop_tag(os, "em", stack_num, stack);
2761 c = par->GetChar(i);
2763 if (c == LyXParagraph::META_INSET) {
2764 inset = par->GetInset(i);
2765 inset->Linuxdoc(this, os);
2768 if (font2.latex() == LyXFont::ON) {
2769 // "TeX"-Mode on == > SGML-Mode on.
2771 os << c; // see LaTeX-Generation...
2775 if (par->linuxDocConvertChar(c, sgml_string)
2776 && !style.free_spacing) { // in freespacing
2778 // non-breaking characters
2782 linux_doc_line_break(os, char_line_count, 6);
2786 linux_doc_line_break(os, char_line_count, 1);
2791 char_line_count += sgml_string.length();
2797 // needed if there is an optional argument but no contents
2798 if (main_body > 0 && main_body == par->size()) {
2802 // pop all defined Styles
2803 for (j = stack_num; j >= 0; --j) {
2804 linux_doc_line_break(os,
2806 3 + strlen(stack[j]));
2807 os << "</" << stack[j] << ">";
2810 // resets description flag correctly
2813 // <tag> not closed...
2814 linux_doc_line_break(os, char_line_count, 6);
2818 // fprintf(file, "</p>");
2824 // Print an error message.
2825 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2826 string const & message)
2828 // insert an error marker in text
2829 InsetError * new_inset = new InsetError(message);
2830 par->InsertInset(pos, new_inset);
2833 // This constant defines the maximum number of
2834 // environment layouts that can be nesteded.
2835 // The same applies for command layouts.
2836 // These values should be more than enough.
2837 // José Matos (1999/07/22)
2839 enum { MAX_NEST_LEVEL = 25};
2841 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2843 LyXParagraph * par = paragraph;
2845 niceFile = nice; // this will be used by Insetincludes.
2847 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2848 // Please use a real stack.
2849 string environment_stack[MAX_NEST_LEVEL];
2850 string environment_inner[MAX_NEST_LEVEL];
2851 // Please use a real stack.
2852 string command_stack[MAX_NEST_LEVEL];
2853 bool command_flag= false;
2854 int command_depth= 0, command_base= 0, cmd_depth= 0;
2856 string item_name, command_name;
2857 string c_depth, c_params, tmps;
2859 int depth = 0; // paragraph depth
2860 LyXTextClass const & tclass =
2861 textclasslist.TextClass(params.textclass);
2863 LaTeXFeatures features(params, tclass.numLayouts());
2867 tex_code_break_column = lyxrc.ascii_linelen;
2869 //tex_code_break_column = 0;
2871 ofstream ofs(fname.c_str());
2873 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2880 string sgml_includedfiles=features.getIncludedFiles(fname);
2882 ofs << "<!doctype " << top_element
2883 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2885 if (params.preamble.empty() && sgml_includedfiles.empty())
2888 ofs << "\n [ " << params.preamble
2889 << sgml_includedfiles << " \n]>\n\n";
2892 if (params.options.empty())
2893 sgmlOpenTag(ofs, 0, top_element);
2895 string top = top_element;
2897 top += params.options;
2898 sgmlOpenTag(ofs, 0, top);
2901 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2902 << "\n See http://www.lyx.org/ for more information -->\n";
2905 int desc_on = 0; // description mode
2906 LyXLayout const & style =
2907 textclasslist.Style(params.textclass,
2910 // environment tag closing
2911 for (; depth > par->depth; --depth) {
2912 if (environment_inner[depth] != "!-- --") {
2913 item_name= "listitem";
2914 sgmlCloseTag(ofs, command_depth + depth,
2916 if (environment_inner[depth] == "varlistentry")
2917 sgmlCloseTag(ofs, depth+command_depth,
2918 environment_inner[depth]);
2920 sgmlCloseTag(ofs, depth + command_depth,
2921 environment_stack[depth]);
2922 environment_stack[depth].erase();
2923 environment_inner[depth].erase();
2926 if (depth == par->depth
2927 && environment_stack[depth] != style.latexname()
2928 && !environment_stack[depth].empty()) {
2929 if (environment_inner[depth] != "!-- --") {
2930 item_name= "listitem";
2931 sgmlCloseTag(ofs, command_depth+depth,
2933 if (environment_inner[depth] == "varlistentry")
2935 depth + command_depth,
2936 environment_inner[depth]);
2939 sgmlCloseTag(ofs, depth + command_depth,
2940 environment_stack[depth]);
2942 environment_stack[depth].erase();
2943 environment_inner[depth].erase();
2946 // Write opening SGML tags.
2947 switch (style.latextype) {
2948 case LATEX_PARAGRAPH:
2949 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2954 LinuxDocError(par, 0,
2955 _("Error : Wrong depth for "
2956 "LatexType Command.\n"));
2958 command_name = style.latexname();
2960 tmps = style.latexparam();
2961 c_params = split(tmps, c_depth,'|');
2963 cmd_depth= lyx::atoi(c_depth);
2966 if (cmd_depth<command_base) {
2967 for (int j = command_depth;
2968 j >= command_base; --j)
2969 if (!command_stack[j].empty())
2970 sgmlCloseTag(ofs, j, command_stack[j]);
2971 command_depth= command_base= cmd_depth;
2972 } else if (cmd_depth <= command_depth) {
2973 for (int j = command_depth;
2974 j >= cmd_depth; --j)
2976 if (!command_stack[j].empty())
2977 sgmlCloseTag(ofs, j, command_stack[j]);
2978 command_depth= cmd_depth;
2980 command_depth= cmd_depth;
2982 command_depth = command_base = cmd_depth;
2983 command_flag = true;
2985 command_stack[command_depth]= command_name;
2987 // treat label as a special case for
2988 // more WYSIWYM handling.
2989 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2990 Inset * inset = par->GetInset(0);
2991 Inset::Code lyx_code = inset->LyxCode();
2992 if (lyx_code == Inset::LABEL_CODE){
2993 command_name += " id=\"";
2994 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2995 command_name += "\"";
3000 sgmlOpenTag(ofs, depth + command_depth, command_name);
3001 item_name = "title";
3002 if (command_name != "!-- --")
3003 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3006 case LATEX_ENVIRONMENT:
3007 case LATEX_ITEM_ENVIRONMENT:
3008 if (depth < par->depth) {
3010 environment_stack[depth].erase();
3013 if (environment_stack[depth] != style.latexname()) {
3014 environment_stack[depth] = style.latexname();
3015 environment_inner[depth] = "!-- --";
3016 sgmlOpenTag(ofs, depth + command_depth,
3017 environment_stack[depth]);
3019 if (environment_inner[depth] != "!-- --") {
3020 item_name= "listitem";
3022 command_depth + depth,
3024 if (environment_inner[depth] == "varlistentry")
3026 depth + command_depth,
3027 environment_inner[depth]);
3031 if (style.latextype == LATEX_ENVIRONMENT) {
3032 if (!style.latexparam().empty())
3033 sgmlOpenTag(ofs, depth + command_depth,
3034 style.latexparam());
3038 desc_on = (style.labeltype == LABEL_MANUAL);
3041 environment_inner[depth]= "varlistentry";
3043 environment_inner[depth]= "listitem";
3045 sgmlOpenTag(ofs, depth + 1 + command_depth,
3046 environment_inner[depth]);
3050 sgmlOpenTag(ofs, depth + 1 + command_depth,
3054 sgmlOpenTag(ofs, depth + 1 + command_depth,
3059 sgmlOpenTag(ofs, depth + command_depth,
3068 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3069 depth + 1 + command_depth);
3072 DocBookHandleFootnote(ofs, par,
3073 depth + 1 + command_depth);
3075 while(par && par->IsDummy());
3078 // write closing SGML tags
3079 switch (style.latextype) {
3082 if (command_name != "!-- --")
3083 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3085 case LATEX_ENVIRONMENT:
3086 if (!style.latexparam().empty())
3087 sgmlCloseTag(ofs, depth + command_depth,
3088 style.latexparam());
3090 case LATEX_ITEM_ENVIRONMENT:
3091 if (desc_on == 1) break;
3093 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3095 case LATEX_PARAGRAPH:
3096 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3099 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3105 for (; depth >= 0; --depth) {
3106 if (!environment_stack[depth].empty()) {
3107 if (environment_inner[depth] != "!-- --") {
3108 item_name= "listitem";
3109 sgmlCloseTag(ofs, command_depth + depth,
3111 if (environment_inner[depth] == "varlistentry")
3112 sgmlCloseTag(ofs, depth + command_depth,
3113 environment_inner[depth]);
3116 sgmlCloseTag(ofs, depth + command_depth,
3117 environment_stack[depth]);
3121 for (int j = command_depth; j >= command_base; --j)
3122 if (!command_stack[j].empty())
3123 sgmlCloseTag(ofs, j, command_stack[j]);
3126 sgmlCloseTag(ofs, 0, top_element);
3129 // How to check for successful close
3133 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3134 LyXParagraph * par, int & desc_on,
3137 bool emph_flag = false;
3139 LyXLayout const & style = textclasslist.Style(params.textclass,
3142 LyXParagraph::size_type main_body;
3143 if (style.labeltype != LABEL_MANUAL)
3146 main_body = par->BeginningOfMainBody();
3148 // gets paragraph main font
3149 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3151 int char_line_count = depth;
3152 if (!style.free_spacing)
3153 for (int j = 0; j < depth; ++j)
3156 // parsing main loop
3157 for (LyXParagraph::size_type i = 0;
3158 i < par->size(); ++i) {
3159 LyXFont font2 = par->getFont(params, i);
3161 // handle <emphasis> tag
3162 if (font1.emph() != font2.emph() && i) {
3163 if (font2.emph() == LyXFont::ON) {
3167 os << "</emphasis>";
3172 char c = par->GetChar(i);
3174 if (c == LyXParagraph::META_INSET) {
3175 Inset * inset = par->GetInset(i);
3176 std::ostringstream ost;
3177 inset->DocBook(this, ost);
3178 string tmp_out = ost.str().c_str();
3181 // This code needs some explanation:
3182 // Two insets are treated specially
3183 // label if it is the first element in a command paragraph
3185 // graphics inside tables or figure floats can't go on
3186 // title (the equivalente in latex for this case is caption
3187 // and title should come first
3190 if (desc_on!= 3 || i!= 0) {
3191 if (!tmp_out.empty() && tmp_out[0] == '@') {
3193 extra += frontStrip(tmp_out, '@');
3195 os << frontStrip(tmp_out, '@');
3200 } else if (font2.latex() == LyXFont::ON) {
3201 // "TeX"-Mode on ==> SGML-Mode on.
3207 if (par->linuxDocConvertChar(c, sgml_string)
3208 && !style.free_spacing) { // in freespacing
3210 // non-breaking characters
3214 os << "\n</term><listitem><para>";
3226 // needed if there is an optional argument but no contents
3227 if (main_body > 0 && main_body == par->size()) {
3231 os << "</emphasis>";
3234 // resets description flag correctly
3237 // <term> not closed...
3245 // This should be enabled when the Chktex class is implemented. (Asger)
3246 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3247 // Other flags: -wall -v0 -x
3248 int Buffer::runChktex()
3250 if (!users->text) return 0;
3252 ProhibitInput(users);
3254 // get LaTeX-Filename
3255 string const name = getLatexName();
3256 string path = OnlyPath(filename);
3258 string const org_path = path;
3259 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3263 Path p(path); // path to LaTeX file
3264 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3266 // Remove all error insets
3267 bool const removedErrorInsets = users->removeAutoInsets();
3269 // Generate the LaTeX file if neccessary
3270 makeLaTeXFile(name, org_path, false);
3273 Chktex chktex(lyxrc.chktex_command, name, filepath);
3274 int res = chktex.run(terr); // run chktex
3277 WriteAlert(_("chktex did not work!"),
3278 _("Could not run with file:"), name);
3279 } else if (res > 0) {
3280 // Insert all errors as errors boxes
3281 users->insertErrors(terr);
3284 // if we removed error insets before we ran chktex or if we inserted
3285 // error insets after we ran chktex, this must be run:
3286 if (removedErrorInsets || res){
3288 users->fitCursor(users->text);
3296 void Buffer::validate(LaTeXFeatures & features) const
3298 LyXParagraph * par = paragraph;
3299 LyXTextClass const & tclass =
3300 textclasslist.TextClass(params.textclass);
3302 // AMS Style is at document level
3304 features.amsstyle = (params.use_amsmath ||
3305 tclass.provides(LyXTextClass::amsmath));
3308 // We don't use "lyxerr.debug" because of speed. (Asger)
3309 if (lyxerr.debugging(Debug::LATEX))
3310 lyxerr << "Paragraph: " << par << endl;
3312 // Now just follow the list of paragraphs and run
3313 // validate on each of them.
3314 par->validate(features);
3316 // and then the next paragraph
3320 // the bullet shapes are buffer level not paragraph level
3321 // so they are tested here
3322 for (int i = 0; i < 4; ++i) {
3323 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3324 int const font = params.user_defined_bullets[i].getFont();
3326 int const c = params
3327 .user_defined_bullets[i]
3334 features.latexsym = true;
3336 } else if (font == 1) {
3337 features.amssymb = true;
3338 } else if ((font >= 2 && font <= 5)) {
3339 features.pifont = true;
3344 if (lyxerr.debugging(Debug::LATEX)) {
3345 features.showStruct();
3350 void Buffer::setPaperStuff()
3352 params.papersize = BufferParams::PAPER_DEFAULT;
3353 char const c1 = params.paperpackage;
3354 if (c1 == BufferParams::PACKAGE_NONE) {
3355 char const c2 = params.papersize2;
3356 if (c2 == BufferParams::VM_PAPER_USLETTER)
3357 params.papersize = BufferParams::PAPER_USLETTER;
3358 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3359 params.papersize = BufferParams::PAPER_LEGALPAPER;
3360 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3361 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3362 else if (c2 == BufferParams::VM_PAPER_A3)
3363 params.papersize = BufferParams::PAPER_A3PAPER;
3364 else if (c2 == BufferParams::VM_PAPER_A4)
3365 params.papersize = BufferParams::PAPER_A4PAPER;
3366 else if (c2 == BufferParams::VM_PAPER_A5)
3367 params.papersize = BufferParams::PAPER_A5PAPER;
3368 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3369 (c2 == BufferParams::VM_PAPER_B5))
3370 params.papersize = BufferParams::PAPER_B5PAPER;
3371 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3372 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3373 params.papersize = BufferParams::PAPER_A4PAPER;
3377 // This function should be in Buffer because it's a buffer's property (ale)
3378 string const Buffer::getIncludeonlyList(char delim)
3381 for (inset_iterator it = inset_iterator_begin();
3382 it != inset_iterator_end(); ++it) {
3383 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3384 InsetInclude * insetinc =
3385 static_cast<InsetInclude *>(*it);
3386 if (insetinc->isInclude()
3387 && insetinc->isNoLoad()) {
3390 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3394 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3399 vector<string> const Buffer::getLabelList()
3401 /// if this is a child document and the parent is already loaded
3402 /// Use the parent's list instead [ale990407]
3403 if (!params.parentname.empty()
3404 && bufferlist.exists(params.parentname)) {
3405 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3407 return tmp->getLabelList();
3410 vector<string> label_list;
3411 for (inset_iterator it = inset_iterator_begin();
3412 it != inset_iterator_end(); ++it) {
3413 vector<string> const l = (*it)->getLabelList();
3414 label_list.insert(label_list.end(), l.begin(), l.end());
3420 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3425 vector<vector<TocItem> > l(4);
3426 LyXParagraph * par = paragraph;
3429 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3430 if (textclasslist.Style(params.textclass,
3431 par->GetLayout()).labeltype
3432 == LABEL_SENSITIVE) {
3436 tmp.str = par->String(this, false);
3437 switch (par->footnotekind) {
3438 case LyXParagraph::FIG:
3439 case LyXParagraph::WIDE_FIG:
3440 tmp.str = tostr(++figs) + ". "
3442 l[TOC_LOF].push_back(tmp);
3444 case LyXParagraph::TAB:
3445 case LyXParagraph::WIDE_TAB:
3446 tmp.str = tostr(++tables) + ". "
3448 l[TOC_LOT].push_back(tmp);
3450 case LyXParagraph::ALGORITHM:
3451 tmp.str = tostr(++algs) + ". "
3453 l[TOC_LOA].push_back(tmp);
3455 case LyXParagraph::FOOTNOTE:
3456 case LyXParagraph::MARGIN:
3460 } else if (!par->IsDummy()) {
3462 char const labeltype =
3463 textclasslist.Style(params.textclass,
3464 par->GetLayout()).labeltype;
3466 if (labeltype >= LABEL_COUNTER_CHAPTER
3467 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3468 // insert this into the table of contents
3473 textclasslist.TextClass(params.textclass).maxcounter());
3474 tmp.str = par->String(this, true);
3475 l[TOC_TOC].push_back(tmp);
3486 // This is also a buffer property (ale)
3487 vector<pair<string,string> > const Buffer::getBibkeyList()
3489 /// if this is a child document and the parent is already loaded
3490 /// Use the parent's list instead [ale990412]
3491 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3492 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3494 return tmp->getBibkeyList();
3497 vector<pair<string, string> > keys;
3498 LyXParagraph * par = paragraph;
3501 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3502 par->String(this, false)));
3506 // Might be either using bibtex or a child has bibliography
3508 for (inset_iterator it = inset_iterator_begin();
3509 it != inset_iterator_end(); ++it) {
3510 // Search for Bibtex or Include inset
3511 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3512 vector<pair<string,string> > tmp =
3513 static_cast<InsetBibtex*>(*it)->getKeys(this);
3514 keys.insert(keys.end(), tmp.begin(), tmp.end());
3515 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3516 vector<pair<string,string> > const tmp =
3517 static_cast<InsetInclude*>(*it)->getKeys();
3518 keys.insert(keys.end(), tmp.begin(), tmp.end());
3527 bool Buffer::isDepClean(string const & name) const
3529 DEPCLEAN * item = dep_clean;
3530 while (item && item->master != name)
3532 if (!item) return true;
3537 void Buffer::markDepClean(string const & name)
3540 dep_clean = new DEPCLEAN;
3541 dep_clean->clean = true;
3542 dep_clean->master = name;
3543 dep_clean->next = 0;
3545 DEPCLEAN * item = dep_clean;
3546 while (item && item->master != name)
3551 item = new DEPCLEAN;
3553 item->master = name;
3560 bool Buffer::Dispatch(string const & command)
3562 // Split command string into command and argument
3564 string line = frontStrip(command);
3565 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3567 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3571 bool Buffer::Dispatch(int action, string const & argument)
3573 bool dispatched = true;
3576 Exporter::Export(this, argument, false);
3586 void Buffer::resize()
3588 /// resize the BufferViews!
3594 void Buffer::resizeInsets(BufferView * bv)
3596 /// then remove all LyXText in text-insets
3597 LyXParagraph * par = paragraph;
3598 for (; par; par = par->next) {
3599 par->resizeInsetsLyXText(bv);
3603 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3606 LyXParagraph * par = paragraph;
3608 par->ChangeLanguage(params, from, to);
3614 bool Buffer::isMultiLingual()
3616 LyXParagraph * par = paragraph;
3618 if (par->isMultiLingual(params))
3626 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3627 LyXParagraph::size_type pos)
3630 it = par->InsetIterator(pos);
3631 if (it == par->inset_iterator_end()) {
3638 void Buffer::inset_iterator::SetParagraph()
3641 it = par->inset_iterator_begin();
3642 if (it != par->inset_iterator_end())
3647 // We maintain an invariant that whenever par = 0 then it = 0