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 * ======================================================
22 #include <sys/types.h>
32 #pragma implementation "buffer.h"
36 #include "bufferlist.h"
38 #include "lyx_gui_misc.h"
39 #include "LyXAction.h"
42 #include "tex-strings.h"
44 #include "bufferview_funcs.h"
45 #include "minibuffer.h"
48 #include "mathed/formulamacro.h"
49 #include "insets/lyxinset.h"
50 #include "insets/inseterror.h"
51 #include "insets/insetlabel.h"
52 #include "insets/insetref.h"
53 #include "insets/inseturl.h"
54 #include "insets/insetinfo.h"
55 #include "insets/insetquotes.h"
56 #include "insets/insetlatexaccent.h"
57 #include "insets/insetbib.h"
58 #include "insets/insetcite.h"
59 #include "insets/insetexternal.h"
60 #include "insets/insetindex.h"
61 #include "insets/insetinclude.h"
62 #include "insets/insettoc.h"
63 #include "insets/insetparent.h"
64 #include "insets/insetspecialchar.h"
65 #include "insets/figinset.h"
66 #include "insets/insettext.h"
67 #include "insets/insetert.h"
68 #include "insets/insetgraphics.h"
69 #include "insets/insetfoot.h"
70 #include "insets/insetmarginal.h"
71 #include "insets/insetminipage.h"
72 #include "insets/insetfloat.h"
73 #include "insets/insetlist.h"
74 #include "insets/insettabular.h"
75 #include "insets/insettheorem.h"
76 #include "insets/insetcaption.h"
77 #include "support/filetools.h"
78 #include "support/path.h"
83 #include "LaTeXFeatures.h"
84 #include "support/syscall.h"
85 #include "support/lyxlib.h"
86 #include "support/FileInfo.h"
90 #include "lyx_gui_misc.h" // WarnReadonly()
91 #include "frontends/Dialogs.h"
107 using std::istringstream;
109 // all these externs should eventually be removed.
110 extern BufferList bufferlist;
112 extern LyXAction lyxaction;
115 static const float LYX_FORMAT = 2.17;
117 extern int tex_code_break_column;
120 Buffer::Buffer(string const & file, bool ronly)
122 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
124 filepath = OnlyPath(file);
133 if (read_only || (lyxrc.use_tempdir)) {
134 tmppath = CreateBufferTmpDir();
135 } else tmppath.erase();
141 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142 // here the buffer should take care that it is
143 // saved properly, before it goes into the void.
145 // make sure that views using this buffer
150 if (!tmppath.empty()) {
151 DestroyBufferTmpDir(tmppath);
154 LyXParagraph * par = paragraph;
155 LyXParagraph * tmppar;
165 string const Buffer::getLatexName(bool no_path) const
168 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
171 return ChangeExtension(MakeLatexName(filename),
176 void Buffer::setReadonly(bool flag)
178 if (read_only != flag) {
181 users->owner()->getDialogs()->updateBufferDependent();
184 WarnReadonly(filename);
189 bool Buffer::saveParamsAsDefaults() // const
191 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
193 Buffer defaults = Buffer(fname);
195 // Use the current buffer's parameters as default
196 defaults.params = params;
198 // add an empty paragraph. Is this enough?
199 defaults.paragraph = new LyXParagraph;
201 return defaults.writeFile(defaults.filename, false);
205 /// Update window titles of all users
206 // Should work on a list
207 void Buffer::updateTitles() const
209 if (users) users->owner()->updateWindowTitle();
213 /// Reset autosave timer of all users
214 // Should work on a list
215 void Buffer::resetAutosaveTimers() const
217 if (users) users->owner()->resetAutosaveTimer();
221 void Buffer::fileName(string const & newfile)
223 filename = MakeAbsPath(newfile);
224 filepath = OnlyPath(filename);
225 setReadonly(IsFileWriteable(filename) == 0);
230 // candidate for move to BufferView
231 // (at least some parts in the beginning of the func)
234 // changed to be public and have one parameter
235 // if par = 0 normal behavior
236 // else insert behavior
237 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
238 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
241 char depth = 0; // signed or unsigned?
243 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
244 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
246 bool the_end_read = false;
248 LyXParagraph * return_par = 0;
249 LyXFont font(LyXFont::ALL_INHERIT, params.language_info);
250 if (format < 2.16 && params.language == "hebrew")
251 font.setLanguage(default_language);
253 // If we are inserting, we cheat and get a token in advance
254 bool has_token = false;
258 par = new LyXParagraph;
260 users->text->BreakParagraph(users);
261 return_par = users->text->FirstParagraph();
264 // We don't want to adopt the parameters from the
265 // document we insert, so we skip until the text begins:
268 pretoken = lex.GetString();
269 if (pretoken == "\\layout") {
281 pretoken = lex.GetString();
284 if (pretoken.empty()) continue;
287 parseSingleLyXformat2Token(lex, par, return_par,
288 pretoken, pos, depth,
300 paragraph = return_par;
306 // We'll remove this later. (Lgb)
307 static string last_inset_read;
311 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
312 LyXParagraph *& return_par,
313 string const & token, int & pos,
314 char & depth, LyXFont & font
316 , LyXParagraph::footnote_flag & footnoteflag,
317 LyXParagraph::footnote_kind & footnotekind
321 bool the_end_read = false;
323 if (token[0] != '\\') {
324 for (string::const_iterator cit = token.begin();
325 cit != token.end(); ++cit) {
326 par->InsertChar(pos, (*cit), font);
329 } else if (token == "\\i") {
330 Inset * inset = new InsetLatexAccent;
331 inset->Read(this, lex);
332 par->InsertInset(pos, inset, font);
334 } else if (token == "\\layout") {
339 par = new LyXParagraph(par);
343 string const layoutname = lex.GetString();
344 pair<bool, LyXTextClass::LayoutList::size_type> pp
345 = textclasslist.NumberOfLayout(params.textclass,
348 par->layout = pp.second;
349 } else { // layout not found
350 // use default layout "Standard" (0)
353 // Test whether the layout is obsolete.
354 LyXLayout const & layout =
355 textclasslist.Style(params.textclass,
357 if (!layout.obsoleted_by().empty())
359 textclasslist.NumberOfLayout(params.textclass,
360 layout.obsoleted_by()).second;
362 par->footnoteflag = footnoteflag;
363 par->footnotekind = footnotekind;
366 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
367 if (format < 2.16 && params.language == "hebrew")
368 font.setLanguage(default_language);
370 } else if (token == "\\end_float") {
375 par = new LyXParagraph(par);
377 footnotekind = LyXParagraph::FOOTNOTE;
378 footnoteflag = LyXParagraph::NO_FOOTNOTE;
381 par->layout = LYX_DUMMY_LAYOUT;
382 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
383 if (format < 2.16 && params.language == "hebrew")
384 font.setLanguage(default_language);
385 } else if (token == "\\begin_float") {
386 int tmpret = lex.FindToken(string_footnotekinds);
387 if (tmpret == -1) ++tmpret;
388 if (tmpret != LYX_LAYOUT_DEFAULT)
389 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
390 if (footnotekind == LyXParagraph::FOOTNOTE
391 || footnotekind == LyXParagraph::MARGIN)
392 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
394 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
396 } else if (token == "\\begin_float") {
397 // This is the compability reader, unfinished but tested.
400 string const tmptok = lex.GetString();
401 //lyxerr << "old float: " << tmptok << endl;
406 if (tmptok == "footnote") {
407 inset = new InsetFoot;
408 } else if (tmptok == "margin") {
409 inset = new InsetMarginal;
410 } else if (tmptok == "fig") {
411 inset = new InsetFloat("figure");
412 old_float += "placement htbp\n";
413 } else if (tmptok == "tab") {
414 inset = new InsetFloat("table");
415 old_float += "placement htbp\n";
416 } else if (tmptok == "alg") {
417 inset = new InsetFloat("algorithm");
418 old_float += "placement htbp\n";
419 } else if (tmptok == "wide-fig") {
420 InsetFloat * tmp = new InsetFloat("figure");
423 old_float += "placement htbp\n";
424 } else if (tmptok == "wide-tab") {
425 InsetFloat * tmp = new InsetFloat("table");
428 old_float += "placement htbp\n";
431 if (!inset) return false; // no end read yet
433 old_float += "collapsed true\n";
435 // Here we need to check for \end_deeper and handle that
436 // before we do the footnote parsing.
437 // This _is_ a hack! (Lgb)
440 string const tmp = lex.GetString();
441 if (tmp == "\\end_deeper") {
442 lyxerr << "\\end_deeper caught!" << endl;
444 lex.printError("\\end_deeper: "
445 "depth is already null");
456 old_float += lex.getLongString("\\end_float");
457 old_float += "\n\\end_inset\n";
458 //lyxerr << "float body: " << old_float << endl;
460 istringstream istr(old_float);
463 nylex.setStream(istr);
465 inset->Read(this, nylex);
466 par->InsertInset(pos, inset, font);
469 } else if (token == "\\begin_deeper") {
471 } else if (token == "\\end_deeper") {
473 lex.printError("\\end_deeper: "
474 "depth is already null");
478 } else if (token == "\\begin_preamble") {
479 params.readPreamble(lex);
480 } else if (token == "\\textclass") {
482 pair<bool, LyXTextClassList::size_type> pp =
483 textclasslist.NumberOfClass(lex.GetString());
485 params.textclass = pp.second;
487 lex.printError("Unknown textclass `$$Token'");
488 params.textclass = 0;
490 if (!textclasslist.Load(params.textclass)) {
491 // if the textclass wasn't loaded properly
492 // we need to either substitute another
493 // or stop loading the file.
494 // I can substitute but I don't see how I can
495 // stop loading... ideas?? ARRae980418
496 WriteAlert(_("Textclass Loading Error!"),
497 string(_("Can't load textclass ")) +
498 textclasslist.NameOfClass(params.textclass),
499 _("-- substituting default"));
500 params.textclass = 0;
502 } else if (token == "\\options") {
504 params.options = lex.GetString();
505 } else if (token == "\\language") {
506 params.readLanguage(lex);
507 } else if (token == "\\fontencoding") {
509 } else if (token == "\\inputencoding") {
511 params.inputenc = lex.GetString();
512 } else if (token == "\\graphics") {
513 params.readGraphicsDriver(lex);
514 } else if (token == "\\fontscheme") {
516 params.fonts = lex.GetString();
517 } else if (token == "\\noindent") {
518 par->noindent = true;
519 } else if (token == "\\fill_top") {
520 par->added_space_top = VSpace(VSpace::VFILL);
521 } else if (token == "\\fill_bottom") {
522 par->added_space_bottom = VSpace(VSpace::VFILL);
523 } else if (token == "\\line_top") {
524 par->line_top = true;
525 } else if (token == "\\line_bottom") {
526 par->line_bottom = true;
527 } else if (token == "\\pagebreak_top") {
528 par->pagebreak_top = true;
529 } else if (token == "\\pagebreak_bottom") {
530 par->pagebreak_bottom = true;
531 } else if (token == "\\start_of_appendix") {
532 par->start_of_appendix = true;
533 } else if (token == "\\paragraph_separation") {
534 int tmpret = lex.FindToken(string_paragraph_separation);
535 if (tmpret == -1) ++tmpret;
536 if (tmpret != LYX_LAYOUT_DEFAULT)
537 params.paragraph_separation =
538 static_cast<BufferParams::PARSEP>(tmpret);
539 } else if (token == "\\defskip") {
541 params.defskip = VSpace(lex.GetString());
542 } else if (token == "\\epsfig") { // obsolete
543 // Indeed it is obsolete, but we HAVE to be backwards
544 // compatible until 0.14, because otherwise all figures
545 // in existing documents are irretrivably lost. (Asger)
546 params.readGraphicsDriver(lex);
547 } else if (token == "\\quotes_language") {
548 int tmpret = lex.FindToken(string_quotes_language);
549 if (tmpret == -1) ++tmpret;
550 if (tmpret != LYX_LAYOUT_DEFAULT) {
551 InsetQuotes::quote_language tmpl =
552 InsetQuotes::EnglishQ;
555 tmpl = InsetQuotes::EnglishQ;
558 tmpl = InsetQuotes::SwedishQ;
561 tmpl = InsetQuotes::GermanQ;
564 tmpl = InsetQuotes::PolishQ;
567 tmpl = InsetQuotes::FrenchQ;
570 tmpl = InsetQuotes::DanishQ;
573 params.quotes_language = tmpl;
575 } else if (token == "\\quotes_times") {
577 switch(lex.GetInteger()) {
579 params.quotes_times = InsetQuotes::SingleQ;
582 params.quotes_times = InsetQuotes::DoubleQ;
585 } else if (token == "\\papersize") {
586 int tmpret = lex.FindToken(string_papersize);
590 params.papersize2 = tmpret;
591 } else if (token == "\\paperpackage") {
592 int tmpret = lex.FindToken(string_paperpackages);
595 params.paperpackage = BufferParams::PACKAGE_NONE;
597 params.paperpackage = tmpret;
598 } else if (token == "\\use_geometry") {
600 params.use_geometry = lex.GetInteger();
601 } else if (token == "\\use_amsmath") {
603 params.use_amsmath = lex.GetInteger();
604 } else if (token == "\\paperorientation") {
605 int tmpret = lex.FindToken(string_orientation);
606 if (tmpret == -1) ++tmpret;
607 if (tmpret != LYX_LAYOUT_DEFAULT)
608 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
609 } else if (token == "\\paperwidth") {
611 params.paperwidth = lex.GetString();
612 } else if (token == "\\paperheight") {
614 params.paperheight = lex.GetString();
615 } else if (token == "\\leftmargin") {
617 params.leftmargin = lex.GetString();
618 } else if (token == "\\topmargin") {
620 params.topmargin = lex.GetString();
621 } else if (token == "\\rightmargin") {
623 params.rightmargin = lex.GetString();
624 } else if (token == "\\bottommargin") {
626 params.bottommargin = lex.GetString();
627 } else if (token == "\\headheight") {
629 params.headheight = lex.GetString();
630 } else if (token == "\\headsep") {
632 params.headsep = lex.GetString();
633 } else if (token == "\\footskip") {
635 params.footskip = lex.GetString();
636 } else if (token == "\\paperfontsize") {
638 params.fontsize = strip(lex.GetString());
639 } else if (token == "\\papercolumns") {
641 params.columns = lex.GetInteger();
642 } else if (token == "\\papersides") {
644 switch(lex.GetInteger()) {
646 case 1: params.sides = LyXTextClass::OneSide; break;
647 case 2: params.sides = LyXTextClass::TwoSides; break;
649 } else if (token == "\\paperpagestyle") {
651 params.pagestyle = strip(lex.GetString());
652 } else if (token == "\\bullet") {
654 int const index = lex.GetInteger();
656 int temp_int = lex.GetInteger();
657 params.user_defined_bullets[index].setFont(temp_int);
658 params.temp_bullets[index].setFont(temp_int);
660 temp_int = lex.GetInteger();
661 params.user_defined_bullets[index].setCharacter(temp_int);
662 params.temp_bullets[index].setCharacter(temp_int);
664 temp_int = lex.GetInteger();
665 params.user_defined_bullets[index].setSize(temp_int);
666 params.temp_bullets[index].setSize(temp_int);
668 string const temp_str = lex.GetString();
669 if (temp_str != "\\end_bullet") {
670 // this element isn't really necessary for
671 // parsing but is easier for humans
672 // to understand bullets. Put it back and
673 // set a debug message?
674 lex.printError("\\end_bullet expected, got" + temp_str);
675 //how can I put it back?
677 } else if (token == "\\bulletLaTeX") {
679 int const index = lex.GetInteger();
681 string temp_str = lex.GetString();
683 while (temp_str != "\\end_bullet") {
684 // this loop structure is needed when user
685 // enters an empty string since the first
686 // thing returned will be the \\end_bullet
688 // if the LaTeX entry has spaces. Each element
689 // therefore needs to be read in turn
692 temp_str = lex.GetString();
694 params.user_defined_bullets[index].setText(sum_str);
695 params.temp_bullets[index].setText(sum_str);
696 } else if (token == "\\secnumdepth") {
698 params.secnumdepth = lex.GetInteger();
699 } else if (token == "\\tocdepth") {
701 params.tocdepth = lex.GetInteger();
702 } else if (token == "\\spacing") {
704 string const tmp = strip(lex.GetString());
705 Spacing::Space tmp_space = Spacing::Default;
707 if (tmp == "single") {
708 tmp_space = Spacing::Single;
709 } else if (tmp == "onehalf") {
710 tmp_space = Spacing::Onehalf;
711 } else if (tmp == "double") {
712 tmp_space = Spacing::Double;
713 } else if (tmp == "other") {
715 tmp_space = Spacing::Other;
716 tmp_val = lex.GetFloat();
718 lex.printError("Unknown spacing token: '$$Token'");
720 // Small hack so that files written with klyx will be
723 par->spacing.set(tmp_space, tmp_val);
725 params.spacing.set(tmp_space, tmp_val);
727 } else if (token == "\\paragraph_spacing") {
729 string const tmp = strip(lex.GetString());
730 if (tmp == "single") {
731 par->spacing.set(Spacing::Single);
732 } else if (tmp == "onehalf") {
733 par->spacing.set(Spacing::Onehalf);
734 } else if (tmp == "double") {
735 par->spacing.set(Spacing::Double);
736 } else if (tmp == "other") {
738 par->spacing.set(Spacing::Other,
741 lex.printError("Unknown spacing token: '$$Token'");
743 } else if (token == "\\float_placement") {
745 params.float_placement = lex.GetString();
746 } else if (token == "\\family") {
748 font.setLyXFamily(lex.GetString());
749 } else if (token == "\\series") {
751 font.setLyXSeries(lex.GetString());
752 } else if (token == "\\shape") {
754 font.setLyXShape(lex.GetString());
755 } else if (token == "\\size") {
757 font.setLyXSize(lex.GetString());
758 } else if (token == "\\latex") {
760 string const tok = lex.GetString();
761 // This is dirty, but gone with LyX3. (Asger)
762 if (tok == "no_latex")
763 font.setLatex(LyXFont::OFF);
764 else if (tok == "latex")
765 font.setLatex(LyXFont::ON);
766 else if (tok == "default")
767 font.setLatex(LyXFont::INHERIT);
769 lex.printError("Unknown LaTeX font flag "
771 } else if (token == "\\lang") {
773 string const tok = lex.GetString();
774 Languages::iterator lit = languages.find(tok);
775 if (lit != languages.end()) {
776 font.setLanguage(&(*lit).second);
778 font.setLanguage(params.language_info);
779 lex.printError("Unknown language `$$Token'");
781 } else if (token == "\\numeric") {
783 font.setNumber(font.setLyXMisc(lex.GetString()));
784 } else if (token == "\\emph") {
786 font.setEmph(font.setLyXMisc(lex.GetString()));
787 } else if (token == "\\bar") {
789 string const tok = lex.GetString();
790 // This is dirty, but gone with LyX3. (Asger)
792 font.setUnderbar(LyXFont::ON);
793 else if (tok == "no")
794 font.setUnderbar(LyXFont::OFF);
795 else if (tok == "default")
796 font.setUnderbar(LyXFont::INHERIT);
798 lex.printError("Unknown bar font flag "
800 } else if (token == "\\noun") {
802 font.setNoun(font.setLyXMisc(lex.GetString()));
803 } else if (token == "\\color") {
805 font.setLyXColor(lex.GetString());
806 } else if (token == "\\align") {
807 int tmpret = lex.FindToken(string_align);
808 if (tmpret == -1) ++tmpret;
809 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
811 for (; tmpret > 0; --tmpret)
812 tmpret2 = tmpret2 * 2;
813 par->align = LyXAlignment(tmpret2);
815 } else if (token == "\\added_space_top") {
817 par->added_space_top = VSpace(lex.GetString());
818 } else if (token == "\\added_space_bottom") {
820 par->added_space_bottom = VSpace(lex.GetString());
821 } else if (token == "\\pextra_type") {
823 par->pextra_type = lex.GetInteger();
824 } else if (token == "\\pextra_width") {
826 par->pextra_width = lex.GetString();
827 } else if (token == "\\pextra_widthp") {
829 par->pextra_widthp = lex.GetString();
830 } else if (token == "\\pextra_alignment") {
832 par->pextra_alignment = lex.GetInteger();
833 } else if (token == "\\pextra_hfill") {
835 par->pextra_hfill = lex.GetInteger();
836 } else if (token == "\\pextra_start_minipage") {
838 par->pextra_start_minipage = lex.GetInteger();
839 } else if (token == "\\labelwidthstring") {
841 par->labelwidthstring = lex.GetString();
842 // do not delete this token, it is still needed!
843 } else if (token == "\\end_inset") {
844 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
845 << "Last inset read was: " << last_inset_read
847 // Simply ignore this. The insets do not have
849 // But insets should read it, it is a part of
850 // the inset isn't it? Lgb.
851 } else if (token == "\\begin_inset") {
852 readInset(lex, par, pos, font);
853 } else if (token == "\\SpecialChar") {
854 LyXLayout const & layout =
855 textclasslist.Style(params.textclass,
858 // Insets don't make sense in a free-spacing context! ---Kayvan
859 if (layout.free_spacing) {
862 string next_token = lex.GetString();
863 if (next_token == "\\-") {
864 par->InsertChar(pos, '-', font);
865 } else if (next_token == "\\protected_separator"
866 || next_token == "~") {
867 par->InsertChar(pos, ' ', font);
869 lex.printError("Token `$$Token' "
871 "paragraph layout!");
876 Inset * inset = new InsetSpecialChar;
877 inset->Read(this, lex);
878 par->InsertInset(pos, inset, font);
881 } else if (token == "\\newline") {
882 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
884 } else if (token == "\\LyXTable") {
885 Inset * inset = new InsetTabular(this);
886 inset->Read(this, lex);
887 par->InsertInset(pos, inset, font);
889 } else if (token == "\\hfill") {
890 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
892 } else if (token == "\\protected_separator") { // obsolete
893 // This is a backward compability thingie. (Lgb)
894 // Remove it later some time...introduced with fileformat
896 LyXLayout const & layout =
897 textclasslist.Style(params.textclass,
900 if (layout.free_spacing) {
901 par->InsertChar(pos, ' ', font);
903 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
904 par->InsertInset(pos, inset, font);
907 } else if (token == "\\bibitem") { // ale970302
909 InsetCommandParams p( "bibitem" );
910 par->bibkey = new InsetBibKey(p);
912 par->bibkey->Read(this, lex);
913 } else if (token == "\\backslash") {
914 par->InsertChar(pos, '\\', font);
916 } else if (token == "\\the_end") {
919 // This should be insurance for the future: (Asger)
920 lex.printError("Unknown token `$$Token'. "
921 "Inserting as text.");
922 string::const_iterator cit = token.begin();
923 string::const_iterator end = token.end();
924 for(; cit != end; ++cit) {
925 par->InsertChar(pos, (*cit), font);
933 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
934 int & pos, LyXFont & font)
937 if (lex.GetString() != "\\begin_inset") {
938 lyxerr << "Buffer::readInset: Consistency check failed."
945 string const tmptok = lex.GetString();
946 last_inset_read = tmptok;
948 // test the different insets
949 if (tmptok == "LatexCommand") {
950 InsetCommandParams inscmd;
953 if (inscmd.getCmdName() == "cite") {
954 inset = new InsetCitation(inscmd);
955 } else if (inscmd.getCmdName() == "bibitem") {
956 lex.printError("Wrong place for bibitem");
957 inset = new InsetBibKey(inscmd);
958 } else if (inscmd.getCmdName() == "BibTeX") {
959 inset = new InsetBibtex(inscmd);
960 } else if (inscmd.getCmdName() == "index") {
961 inset = new InsetIndex(inscmd);
962 } else if (inscmd.getCmdName() == "include") {
963 inset = new InsetInclude(inscmd, this);
964 } else if (inscmd.getCmdName() == "label") {
965 inset = new InsetLabel(inscmd);
966 } else if (inscmd.getCmdName() == "url"
967 || inscmd.getCmdName() == "htmlurl") {
968 inset = new InsetUrl(inscmd);
969 } else if (inscmd.getCmdName() == "ref"
970 || inscmd.getCmdName() == "pageref"
971 || inscmd.getCmdName() == "vref"
972 || inscmd.getCmdName() == "vpageref"
973 || inscmd.getCmdName() == "prettyref") {
974 if (!inscmd.getOptions().empty()
975 || !inscmd.getContents().empty()) {
976 inset = new InsetRef(inscmd);
978 } else if (inscmd.getCmdName() == "tableofcontents"
979 || inscmd.getCmdName() == "listofalgorithms"
980 || inscmd.getCmdName() == "listoffigures"
981 || inscmd.getCmdName() == "listoftables") {
982 inset = new InsetTOC(inscmd);
983 } else if (inscmd.getCmdName() == "printindex") {
984 inset = new InsetPrintIndex(inscmd);
985 } else if (inscmd.getCmdName() == "lyxparent") {
986 inset = new InsetParent(inscmd, this);
989 if (tmptok == "Quotes") {
990 inset = new InsetQuotes;
991 } else if (tmptok == "External") {
992 inset = new InsetExternal;
993 } else if (tmptok == "FormulaMacro") {
994 inset = new InsetFormulaMacro;
995 } else if (tmptok == "Formula") {
996 inset = new InsetFormula;
997 } else if (tmptok == "Figure") {
998 inset = new InsetFig(100, 100, this);
999 } else if (tmptok == "Info") {
1000 inset = new InsetInfo;
1001 } else if (tmptok == "Include") {
1002 InsetCommandParams p( "Include" );
1003 inset = new InsetInclude(p, this);
1004 } else if (tmptok == "ERT") {
1005 inset = new InsetERT;
1006 } else if (tmptok == "Tabular") {
1007 inset = new InsetTabular(this);
1008 } else if (tmptok == "Text") {
1009 inset = new InsetText;
1010 } else if (tmptok == "Foot") {
1011 inset = new InsetFoot;
1012 } else if (tmptok == "Marginal") {
1013 inset = new InsetMarginal;
1014 } else if (tmptok == "Minipage") {
1015 inset = new InsetMinipage;
1016 } else if (tmptok == "Float") {
1018 string tmptok = lex.GetString();
1019 inset = new InsetFloat(tmptok);
1020 } else if (tmptok == "List") {
1021 inset = new InsetList;
1022 } else if (tmptok == "Theorem") {
1023 inset = new InsetList;
1024 } else if (tmptok == "Caption") {
1025 inset = new InsetCaption;
1026 } else if (tmptok == "GRAPHICS") {
1027 inset = new InsetGraphics;
1030 if (inset) inset->Read(this, lex);
1034 par->InsertInset(pos, inset, font);
1040 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1044 string const token(lex.GetString());
1045 if (token == "\\lyxformat") { // the first token _must_ be...
1047 format = lex.GetFloat();
1049 if (LYX_FORMAT - format > 0.05) {
1051 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1052 LYX_FORMAT, format);
1054 if (format - LYX_FORMAT > 0.05) {
1055 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1056 LYX_FORMAT, format);
1058 bool the_end = readLyXformat2(lex, par);
1059 // Formats >= 2.13 support "\the_end" marker
1066 WriteAlert(_("Warning!"),
1067 _("Reading of document is not complete"),
1068 _("Maybe the document is truncated"));
1069 // We simulate a safe reading anyways to allow
1070 // users to take the chance... (Asger)
1074 WriteAlert(_("ERROR!"),
1075 _("Old LyX file format found. "
1076 "Use LyX 0.10.x to read this!"));
1080 } else { // "\\lyxformat" not found
1081 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1084 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1090 // Should probably be moved to somewhere else: BufferView? LyXView?
1091 bool Buffer::save() const
1093 // We don't need autosaves in the immediate future. (Asger)
1094 resetAutosaveTimers();
1098 if (lyxrc.make_backup) {
1099 s = fileName() + '~';
1100 if (!lyxrc.backupdir_path.empty())
1101 s = AddName(lyxrc.backupdir_path,
1102 subst(CleanupPath(s),'/','!'));
1104 // Rename is the wrong way of making a backup,
1105 // this is the correct way.
1106 /* truss cp fil fil2:
1107 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1108 stat("LyXVC.lyx", 0xEFFFF688) = 0
1109 open("LyXVC.lyx", O_RDONLY) = 3
1110 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1111 fstat(4, 0xEFFFF508) = 0
1112 fstat(3, 0xEFFFF508) = 0
1113 read(3, " # T h i s f i l e w".., 8192) = 5579
1114 write(4, " # T h i s f i l e w".., 5579) = 5579
1115 read(3, 0xEFFFD4A0, 8192) = 0
1118 chmod("LyXVC3.lyx", 0100644) = 0
1119 lseek(0, 0, SEEK_CUR) = 46440
1123 // Should proabaly have some more error checking here.
1124 // Should be cleaned up in 0.13, at least a bit.
1125 // Doing it this way, also makes the inodes stay the same.
1126 // This is still not a very good solution, in particular we
1127 // might loose the owner of the backup.
1128 FileInfo finfo(fileName());
1129 if (finfo.exist()) {
1130 mode_t fmode = finfo.getMode();
1131 struct utimbuf times = {
1132 finfo.getAccessTime(),
1133 finfo.getModificationTime() };
1135 ifstream ifs(fileName().c_str());
1136 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1141 ::chmod(s.c_str(), fmode);
1143 if (::utime(s.c_str(), ×)) {
1144 lyxerr << "utime error." << endl;
1147 lyxerr << "LyX was not able to make "
1148 "backupcopy. Beware." << endl;
1153 if (writeFile(fileName(), false)) {
1155 removeAutosaveFile(fileName());
1157 // Saving failed, so backup is not backup
1158 if (lyxrc.make_backup) {
1159 lyx::rename(s, fileName());
1167 // Returns false if unsuccesful
1168 bool Buffer::writeFile(string const & fname, bool flag) const
1170 // if flag is false writeFile will not create any GUI
1171 // warnings, only cerr.
1172 // Needed for autosave in background or panic save (Matthias 120496)
1174 if (read_only && (fname == filename)) {
1175 // Here we should come with a question if we should
1176 // perform the write anyway.
1178 lyxerr << _("Error! Document is read-only: ")
1181 WriteAlert(_("Error! Document is read-only: "),
1186 FileInfo finfo(fname);
1187 if (finfo.exist() && !finfo.writable()) {
1188 // Here we should come with a question if we should
1189 // try to do the save anyway. (i.e. do a chmod first)
1191 lyxerr << _("Error! Cannot write file: ")
1194 WriteFSAlert(_("Error! Cannot write file: "),
1199 ofstream ofs(fname.c_str());
1202 lyxerr << _("Error! Cannot open file: ")
1205 WriteFSAlert(_("Error! Cannot open file: "),
1211 // Use the standard "C" locale for file output.
1212 ofs.imbue(std::locale::classic());
1215 // The top of the file should not be written by params.
1217 // write out a comment in the top of the file
1218 ofs << '#' << LYX_DOCVERSION
1219 << " created this file. For more info see http://www.lyx.org/\n";
1220 ofs.setf(ios::showpoint|ios::fixed);
1223 char dummy_format[512];
1224 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1225 ofs << "\\lyxformat " << dummy_format << "\n";
1227 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1229 // now write out the buffer paramters.
1230 params.writeFile(ofs);
1232 char footnoteflag = 0;
1235 // this will write out all the paragraphs
1236 // using recursive descent.
1237 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1239 // Write marker that shows file is complete
1240 ofs << "\n\\the_end" << endl;
1242 // how to check if close went ok?
1248 void Buffer::writeFileAscii(string const & fname, int linelen)
1252 char footnoteflag = 0;
1255 LyXParagraph::size_type i;
1258 int ltype_depth = 0;
1261 int currlinelen = 0;
1263 bool ref_printed = false;
1265 ofstream ofs(fname.c_str());
1267 WriteFSAlert(_("Error: Cannot write file:"), fname);
1271 string const fname1 = TmpFileName();
1272 LyXParagraph * par = paragraph;
1278 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1282 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1287 /* begins a footnote environment ? */
1288 if (footnoteflag != par->footnoteflag) {
1289 footnoteflag = par->footnoteflag;
1291 j = strlen(string_footnotekinds[par->footnotekind])+4;
1292 if (currlinelen + j > linelen)
1295 << string_footnotekinds[par->footnotekind] << "] ";
1301 /* begins or ends a deeper area ?*/
1302 if (depth != par->depth) {
1303 if (par->depth > depth) {
1304 while (par->depth > depth) {
1309 while (par->depth < depth) {
1315 /* First write the layout */
1316 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1317 if (tmp == "Itemize") {
1319 ltype_depth = depth+1;
1320 } else if (tmp == "Enumerate") {
1322 ltype_depth = depth+1;
1323 } else if (contains(tmp, "ection")) {
1325 ltype_depth = depth+1;
1326 } else if (contains(tmp, "aragraph")) {
1328 ltype_depth = depth+1;
1329 } else if (tmp == "Description") {
1331 ltype_depth = depth+1;
1332 } else if (tmp == "Abstract") {
1335 } else if (tmp == "Bibliography") {
1343 /* maybe some vertical spaces */
1345 /* the labelwidthstring used in lists */
1349 /* some pagebreaks? */
1353 /* what about the alignment */
1356 /* dummy layout, that means a footnote ended */
1357 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1361 lyxerr << "Should this ever happen?" << endl;
1366 LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1368 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1369 if (!i && !footnoteflag && !noparbreak){
1371 for(j = 0; j < depth; ++j)
1373 currlinelen = depth * 2;
1375 case 0: /* Standard */
1376 case 4: /* (Sub)Paragraph */
1377 case 5: /* Description */
1379 case 6: /* Abstract */
1380 ofs << "Abstract\n\n";
1382 case 7: /* Bibliography */
1384 ofs << "References\n\n";
1389 ofs << par->labelstring << " ";
1392 if (ltype_depth > depth) {
1393 for(j = ltype_depth - 1; j > depth; --j)
1395 currlinelen += (ltype_depth-depth)*2;
1398 LyXFont font2 = par->GetFontSettings(params, i);
1399 if (font1.latex() != font2.latex()) {
1400 if (font2.latex() == LyXFont::OFF)
1407 c = par->GetChar(i);
1411 case LyXParagraph::META_INSET:
1412 if ((inset = par->GetInset(i))) {
1414 inset->Ascii(this, ofs);
1415 currlinelen += (ofs.tellp() - fpos);
1416 actpos += (ofs.tellp() - fpos) - 1;
1419 case LyXParagraph::META_NEWLINE:
1421 for(j = 0; j < depth; ++j)
1423 currlinelen = depth * 2;
1424 if (ltype_depth > depth) {
1425 for(j = ltype_depth;
1428 currlinelen += (ltype_depth - depth) * 2;
1431 case LyXParagraph::META_HFILL:
1438 if (currlinelen > linelen - 10
1439 && c == ' ' && i + 2 < par->size()) {
1441 for(j = 0; j < depth; ++j)
1443 currlinelen = depth * 2;
1444 if (ltype_depth > depth) {
1445 for(j = ltype_depth;
1448 currlinelen += (ltype_depth-depth)*2;
1450 } else if (c != '\0')
1453 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1463 //----------------------------------------------------------------------------
1465 //----------------------------------------------------------------------------
1466 string const Buffer::asciiParagraph(LyXParagraph const * par,
1467 unsigned int linelen) const
1469 ostringstream buffer;
1472 Inset const * inset;
1474 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1477 int ltype_depth = 0;
1478 unsigned int currlinelen = 0;
1479 bool ref_printed = false;
1485 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1489 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1493 /* begins a footnote environment ? */
1494 if (footnoteflag != par->footnoteflag) {
1495 footnoteflag = par->footnoteflag;
1497 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1498 if ((linelen > 0) &&
1499 ((currlinelen + j) > linelen)) {
1504 << string_footnotekinds[par->footnotekind]
1510 /* begins or ends a deeper area ?*/
1511 if (depth != par->depth) {
1512 if (par->depth > depth) {
1513 while (par->depth > depth) {
1518 while (par->depth < depth) {
1524 /* First write the layout */
1525 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1526 if (tmp == "Itemize") {
1528 ltype_depth = depth+1;
1529 } else if (tmp == "Enumerate") {
1531 ltype_depth = depth+1;
1532 } else if (strstr(tmp.c_str(), "ection")) {
1534 ltype_depth = depth+1;
1535 } else if (strstr(tmp.c_str(), "aragraph")) {
1537 ltype_depth = depth+1;
1538 } else if (tmp == "Description") {
1540 ltype_depth = depth+1;
1541 } else if (tmp == "Abstract") {
1544 } else if (tmp == "Bibliography") {
1552 /* maybe some vertical spaces */
1554 /* the labelwidthstring used in lists */
1558 /* some pagebreaks? */
1562 /* what about the alignment */
1565 /* dummy layout, that means a footnote ended */
1566 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1570 lyxerr << "Should this ever happen?" << endl;
1574 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1575 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1576 if (!i && !footnoteflag && !noparbreak){
1579 for(char j = 0; j < depth; ++j)
1581 currlinelen = depth * 2;
1583 case 0: /* Standard */
1584 case 4: /* (Sub)Paragraph */
1585 case 5: /* Description */
1587 case 6: /* Abstract */
1589 buffer << "Abstract\n\n";
1591 buffer << "Abstract: ";
1593 case 7: /* Bibliography */
1596 buffer << "References\n\n";
1598 buffer << "References: ";
1603 buffer << par->labelstring << " ";
1606 if (ltype_depth > depth) {
1607 for(char j = ltype_depth - 1; j > depth; --j)
1609 currlinelen += (ltype_depth-depth)*2;
1612 font2 = par->GetFontSettings(params, i);
1613 if (font1.latex() != font2.latex()) {
1614 if (font2.latex() == LyXFont::OFF)
1621 c = par->GetChar(i);
1625 case LyXParagraph::META_INSET:
1626 if ((inset = par->GetInset(i))) {
1627 if (!inset->Ascii(this, buffer)) {
1629 string s = rsplit(buffer.str(),
1631 currlinelen += s.length();
1633 // to be sure it breaks paragraph
1634 currlinelen += linelen;
1638 case LyXParagraph::META_NEWLINE:
1641 for(char j = 0; j < depth; ++j)
1644 currlinelen = depth * 2;
1645 if (ltype_depth > depth) {
1646 for(char j = ltype_depth;
1649 currlinelen += (ltype_depth - depth) * 2;
1652 case LyXParagraph::META_HFILL:
1659 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1660 (c == ' ') && ((i + 2) < par->size()))
1663 for(char j = 0; j < depth; ++j)
1665 currlinelen = depth * 2;
1666 if (ltype_depth > depth) {
1667 for(char j = ltype_depth;
1670 currlinelen += (ltype_depth-depth)*2;
1672 } else if (c != '\0')
1675 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1680 return buffer.str();
1684 void Buffer::writeFileAscii(string const & fname, int linelen)
1686 ofstream ofs(fname.c_str());
1688 WriteFSAlert(_("Error: Cannot write file:"), fname);
1691 writeFileAscii(ofs, linelen);
1695 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1697 LyXParagraph * par = paragraph;
1699 ofs << asciiParagraph(par, linelen);
1706 void Buffer::makeLaTeXFile(string const & fname,
1707 string const & original_path,
1708 bool nice, bool only_body)
1710 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1712 niceFile = nice; // this will be used by Insetincludes.
1714 tex_code_break_column = lyxrc.ascii_linelen;
1716 LyXTextClass const & tclass =
1717 textclasslist.TextClass(params.textclass);
1719 ofstream ofs(fname.c_str());
1721 WriteFSAlert(_("Error: Cannot open file: "), fname);
1725 // validate the buffer.
1726 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1727 LaTeXFeatures features(params, tclass.numLayouts());
1729 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1732 // The starting paragraph of the coming rows is the
1733 // first paragraph of the document. (Asger)
1734 texrow.start(paragraph, 0);
1736 if (!only_body && nice) {
1737 ofs << "%% " LYX_DOCVERSION " created this file. "
1738 "For more info, see http://www.lyx.org/.\n"
1739 "%% Do not edit unless you really know what "
1744 lyxerr.debug() << "lyx header finished" << endl;
1745 // There are a few differences between nice LaTeX and usual files:
1746 // usual is \batchmode and has a
1747 // special input@path to allow the including of figures
1748 // with either \input or \includegraphics (what figinsets do).
1749 // batchmode is not set if there is a tex_code_break_column.
1750 // In this case somebody is interested in the generated LaTeX,
1751 // so this is OK. input@path is set when the actual parameter
1752 // original_path is set. This is done for usual tex-file, but not
1753 // for nice-latex-file. (Matthias 250696)
1756 // code for usual, NOT nice-latex-file
1757 ofs << "\\batchmode\n"; // changed
1758 // from \nonstopmode
1761 if (!original_path.empty()) {
1762 ofs << "\\makeatletter\n"
1763 << "\\def\\input@path{{"
1764 << original_path << "/}}\n"
1765 << "\\makeatother\n";
1771 ofs << "\\documentclass";
1773 string options; // the document class options.
1775 if (tokenPos(tclass.opt_fontsize(),
1776 '|', params.fontsize) >= 0) {
1777 // only write if existing in list (and not default)
1778 options += params.fontsize;
1783 if (!params.use_geometry &&
1784 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1785 switch (params.papersize) {
1786 case BufferParams::PAPER_A4PAPER:
1787 options += "a4paper,";
1789 case BufferParams::PAPER_USLETTER:
1790 options += "letterpaper,";
1792 case BufferParams::PAPER_A5PAPER:
1793 options += "a5paper,";
1795 case BufferParams::PAPER_B5PAPER:
1796 options += "b5paper,";
1798 case BufferParams::PAPER_EXECUTIVEPAPER:
1799 options += "executivepaper,";
1801 case BufferParams::PAPER_LEGALPAPER:
1802 options += "legalpaper,";
1808 if (params.sides != tclass.sides()) {
1809 switch (params.sides) {
1810 case LyXTextClass::OneSide:
1811 options += "oneside,";
1813 case LyXTextClass::TwoSides:
1814 options += "twoside,";
1821 if (params.columns != tclass.columns()) {
1822 if (params.columns == 2)
1823 options += "twocolumn,";
1825 options += "onecolumn,";
1828 if (!params.use_geometry
1829 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1830 options += "landscape,";
1832 // language should be a parameter to \documentclass
1833 bool use_babel = false;
1834 if (params.language_info->lang() == "hebrew") // This seems necessary
1835 features.UsedLanguages.insert(default_language);
1836 if (params.language != "default" ||
1837 !features.UsedLanguages.empty() ) {
1839 for (LaTeXFeatures::LanguageList::const_iterator cit =
1840 features.UsedLanguages.begin();
1841 cit != features.UsedLanguages.end(); ++cit)
1842 options += (*cit)->lang() + ",";
1843 options += params.language_info->lang() + ',';
1846 // the user-defined options
1847 if (!params.options.empty()) {
1848 options += params.options + ',';
1851 if (!options.empty()){
1852 options = strip(options, ',');
1853 ofs << '[' << options << ']';
1857 << textclasslist.LatexnameOfClass(params.textclass)
1860 // end of \documentclass defs
1862 // font selection must be done before loading fontenc.sty
1863 if (params.fonts != "default") {
1864 ofs << "\\usepackage{" << params.fonts << "}\n";
1867 // this one is not per buffer
1868 if (lyxrc.fontenc != "default") {
1869 ofs << "\\usepackage[" << lyxrc.fontenc
1874 if (params.inputenc == "auto") {
1875 string const doc_encoding =
1876 params.language_info->encoding()->LatexName();
1878 // Create a list with all the input encodings used
1880 set<string> encodings;
1881 for (LaTeXFeatures::LanguageList::const_iterator it =
1882 features.UsedLanguages.begin();
1883 it != features.UsedLanguages.end(); ++it)
1884 if ((*it)->encoding()->LatexName() != doc_encoding)
1885 encodings.insert((*it)->encoding()->LatexName());
1887 ofs << "\\usepackage[";
1888 for (set<string>::const_iterator it = encodings.begin();
1889 it != encodings.end(); ++it)
1891 ofs << doc_encoding << "]{inputenc}\n";
1893 } else if (params.inputenc != "default") {
1894 ofs << "\\usepackage[" << params.inputenc
1899 // At the very beginning the text parameters.
1900 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1901 switch (params.paperpackage) {
1902 case BufferParams::PACKAGE_A4:
1903 ofs << "\\usepackage{a4}\n";
1906 case BufferParams::PACKAGE_A4WIDE:
1907 ofs << "\\usepackage{a4wide}\n";
1910 case BufferParams::PACKAGE_WIDEMARGINSA4:
1911 ofs << "\\usepackage[widemargins]{a4}\n";
1916 if (params.use_geometry) {
1917 ofs << "\\usepackage{geometry}\n";
1919 ofs << "\\geometry{verbose";
1920 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1921 ofs << ",landscape";
1922 switch (params.papersize2) {
1923 case BufferParams::VM_PAPER_CUSTOM:
1924 if (!params.paperwidth.empty())
1925 ofs << ",paperwidth="
1926 << params.paperwidth;
1927 if (!params.paperheight.empty())
1928 ofs << ",paperheight="
1929 << params.paperheight;
1931 case BufferParams::VM_PAPER_USLETTER:
1932 ofs << ",letterpaper";
1934 case BufferParams::VM_PAPER_USLEGAL:
1935 ofs << ",legalpaper";
1937 case BufferParams::VM_PAPER_USEXECUTIVE:
1938 ofs << ",executivepaper";
1940 case BufferParams::VM_PAPER_A3:
1943 case BufferParams::VM_PAPER_A4:
1946 case BufferParams::VM_PAPER_A5:
1949 case BufferParams::VM_PAPER_B3:
1952 case BufferParams::VM_PAPER_B4:
1955 case BufferParams::VM_PAPER_B5:
1959 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1960 switch (lyxrc.default_papersize) {
1961 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1962 case BufferParams::PAPER_USLETTER:
1963 ofs << ",letterpaper";
1965 case BufferParams::PAPER_LEGALPAPER:
1966 ofs << ",legalpaper";
1968 case BufferParams::PAPER_EXECUTIVEPAPER:
1969 ofs << ",executivepaper";
1971 case BufferParams::PAPER_A3PAPER:
1974 case BufferParams::PAPER_A4PAPER:
1977 case BufferParams::PAPER_A5PAPER:
1980 case BufferParams::PAPER_B5PAPER:
1985 if (!params.topmargin.empty())
1986 ofs << ",tmargin=" << params.topmargin;
1987 if (!params.bottommargin.empty())
1988 ofs << ",bmargin=" << params.bottommargin;
1989 if (!params.leftmargin.empty())
1990 ofs << ",lmargin=" << params.leftmargin;
1991 if (!params.rightmargin.empty())
1992 ofs << ",rmargin=" << params.rightmargin;
1993 if (!params.headheight.empty())
1994 ofs << ",headheight=" << params.headheight;
1995 if (!params.headsep.empty())
1996 ofs << ",headsep=" << params.headsep;
1997 if (!params.footskip.empty())
1998 ofs << ",footskip=" << params.footskip;
2002 if (params.use_amsmath
2003 && !tclass.provides(LyXTextClass::amsmath)) {
2004 ofs << "\\usepackage{amsmath}\n";
2008 if (tokenPos(tclass.opt_pagestyle(),
2009 '|', params.pagestyle) >= 0) {
2010 if (params.pagestyle == "fancy") {
2011 ofs << "\\usepackage{fancyhdr}\n";
2014 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2018 // We try to load babel late, in case it interferes
2019 // with other packages.
2021 ofs << lyxrc.language_package << endl;
2025 if (params.secnumdepth != tclass.secnumdepth()) {
2026 ofs << "\\setcounter{secnumdepth}{"
2027 << params.secnumdepth
2031 if (params.tocdepth != tclass.tocdepth()) {
2032 ofs << "\\setcounter{tocdepth}{"
2038 if (params.paragraph_separation) {
2039 switch (params.defskip.kind()) {
2040 case VSpace::SMALLSKIP:
2041 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2043 case VSpace::MEDSKIP:
2044 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2046 case VSpace::BIGSKIP:
2047 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2049 case VSpace::LENGTH:
2050 ofs << "\\setlength\\parskip{"
2051 << params.defskip.length().asLatexString()
2054 default: // should never happen // Then delete it.
2055 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2060 ofs << "\\setlength\\parindent{0pt}\n";
2064 // Now insert the LyX specific LaTeX commands...
2066 // The optional packages;
2067 string preamble(features.getPackages());
2069 // this might be useful...
2070 preamble += "\n\\makeatletter\n";
2072 // Some macros LyX will need
2073 string tmppreamble(features.getMacros());
2075 if (!tmppreamble.empty()) {
2076 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2077 "LyX specific LaTeX commands.\n"
2078 + tmppreamble + '\n';
2081 // the text class specific preamble
2082 tmppreamble = features.getTClassPreamble();
2083 if (!tmppreamble.empty()) {
2084 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2085 "Textclass specific LaTeX commands.\n"
2086 + tmppreamble + '\n';
2089 /* the user-defined preamble */
2090 if (!params.preamble.empty()) {
2091 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2092 "User specified LaTeX commands.\n"
2093 + params.preamble + '\n';
2096 preamble += "\\makeatother\n";
2098 // Itemize bullet settings need to be last in case the user
2099 // defines their own bullets that use a package included
2100 // in the user-defined preamble -- ARRae
2101 // Actually it has to be done much later than that
2102 // since some packages like frenchb make modifications
2103 // at \begin{document} time -- JMarc
2105 for (int i = 0; i < 4; ++i) {
2106 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2107 if (bullets_def.empty())
2108 bullets_def="\\AtBeginDocument{\n";
2109 bullets_def += " \\renewcommand{\\labelitemi";
2111 // `i' is one less than the item to modify
2118 bullets_def += "ii";
2124 bullets_def += "}{" +
2125 params.user_defined_bullets[i].getText()
2130 if (!bullets_def.empty())
2131 preamble += bullets_def + "}\n\n";
2133 for (int j = countChar(preamble, '\n'); j-- ;) {
2140 ofs << "\\begin{document}\n";
2143 lyxerr.debug() << "preamble finished, now the body." << endl;
2144 if (!lyxrc.language_auto_begin && params.language != "default") {
2145 ofs << subst(lyxrc.language_command_begin, "$$lang",
2151 latexParagraphs(ofs, paragraph, 0, texrow);
2153 // add this just in case after all the paragraphs
2157 if (!lyxrc.language_auto_end && params.language != "default") {
2158 ofs << subst(lyxrc.language_command_end, "$$lang",
2165 ofs << "\\end{document}\n";
2168 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2170 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2174 // Just to be sure. (Asger)
2177 // tex_code_break_column's value is used to decide
2178 // if we are in batchmode or not (within mathed_write()
2179 // in math_write.C) so we must set it to a non-zero
2180 // value when we leave otherwise we save incorrect .lyx files.
2181 tex_code_break_column = lyxrc.ascii_linelen;
2185 lyxerr << "File was not closed properly." << endl;
2188 lyxerr.debug() << "Finished making latex file." << endl;
2193 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2195 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2196 LyXParagraph * endpar, TexRow & texrow) const
2198 bool was_title = false;
2199 bool already_title = false;
2200 std::ostringstream ftnote;
2205 while (par != endpar) {
2208 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2211 LyXLayout const & layout =
2212 textclasslist.Style(params.textclass,
2215 if (layout.intitle) {
2216 if (already_title) {
2217 lyxerr <<"Error in latexParagraphs: You"
2218 " should not mix title layouts"
2219 " with normal ones." << endl;
2222 } else if (was_title && !already_title) {
2223 ofs << "\\maketitle\n";
2225 already_title = true;
2228 // We are at depth 0 so we can just use
2229 // ordinary \footnote{} generation
2230 // flag this with ftcount
2232 if (layout.isEnvironment()
2233 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2234 par = par->TeXEnvironment(this, params, ofs, texrow
2236 ,ftnote, ft_texrow, ftcount
2240 par = par->TeXOnePar(this, params, ofs, texrow, false
2243 ftnote, ft_texrow, ftcount
2248 // Write out what we've generated...
2251 ofs << "\\addtocounter{footnote}{-"
2255 ofs << ftnote.str();
2256 texrow += ft_texrow;
2258 // The extra .c_str() is needed when we use
2259 // lyxstring instead of the STL string class.
2260 ftnote.str(string().c_str());
2265 // It might be that we only have a title in this document
2266 if (was_title && !already_title) {
2267 ofs << "\\maketitle\n";
2273 bool Buffer::isLatex() const
2275 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2279 bool Buffer::isLinuxDoc() const
2281 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2285 bool Buffer::isLiterate() const
2287 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2291 bool Buffer::isDocBook() const
2293 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2297 bool Buffer::isSGML() const
2299 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2300 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2304 void Buffer::sgmlOpenTag(ostream & os, int depth,
2305 string const & latexname) const
2307 os << string(depth, ' ') << "<" << latexname << ">\n";
2311 void Buffer::sgmlCloseTag(ostream & os, int depth,
2312 string const & latexname) const
2314 os << string(depth, ' ') << "</" << latexname << ">\n";
2318 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2320 LyXParagraph * par = paragraph;
2322 niceFile = nice; // this will be used by Insetincludes.
2324 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2325 string environment_stack[10];
2328 int depth = 0; // paragraph depth
2330 ofstream ofs(fname.c_str());
2333 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2337 LyXTextClass const & tclass =
2338 textclasslist.TextClass(params.textclass);
2340 LaTeXFeatures features(params, tclass.numLayouts());
2344 tex_code_break_column = lyxrc.ascii_linelen;
2346 //tex_code_break_column = 0;
2351 string sgml_includedfiles=features.getIncludedFiles();
2353 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2354 ofs << "<!doctype linuxdoc system>\n\n";
2356 ofs << "<!doctype linuxdoc system [ "
2357 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2360 if(params.options.empty())
2361 sgmlOpenTag(ofs, 0, top_element);
2363 string top = top_element;
2365 top += params.options;
2366 sgmlOpenTag(ofs, 0, top);
2370 ofs << "<!-- " << LYX_DOCVERSION
2371 << " created this file. For more info see http://www.lyx.org/"
2375 int desc_on = 0; // description mode
2376 LyXLayout const & style =
2377 textclasslist.Style(params.textclass,
2380 // treat <toc> as a special case for compatibility with old code
2381 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2382 Inset * inset = par->GetInset(0);
2383 Inset::Code lyx_code = inset->LyxCode();
2384 if (lyx_code == Inset::TOC_CODE){
2385 string const temp = "toc";
2386 sgmlOpenTag(ofs, depth, temp);
2390 linuxDocHandleFootnote(ofs, par, depth);
2396 // environment tag closing
2397 for (; depth > par->depth; --depth) {
2398 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2399 environment_stack[depth].erase();
2402 // write opening SGML tags
2403 switch (style.latextype) {
2404 case LATEX_PARAGRAPH:
2405 if(depth == par->depth
2406 && !environment_stack[depth].empty()) {
2407 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2408 environment_stack[depth].erase();
2414 sgmlOpenTag(ofs, depth, style.latexname());
2419 LinuxDocError(par, 0,
2420 _("Error : Wrong depth for"
2421 " LatexType Command.\n"));
2423 if (!environment_stack[depth].empty()){
2424 sgmlCloseTag(ofs, depth,
2425 environment_stack[depth]);
2429 environment_stack[depth].erase();
2430 sgmlOpenTag(ofs, depth, style.latexname());
2433 case LATEX_ENVIRONMENT:
2434 case LATEX_ITEM_ENVIRONMENT:
2435 if (depth == par->depth
2436 && environment_stack[depth] != style.latexname()
2437 && !environment_stack[depth].empty()) {
2439 sgmlCloseTag(ofs, depth,
2440 environment_stack[depth]);
2441 environment_stack[depth].erase();
2443 if (depth < par->depth) {
2445 environment_stack[depth].erase();
2447 if (environment_stack[depth] != style.latexname()) {
2449 string const temp = "p";
2450 sgmlOpenTag(ofs, depth, temp);
2452 environment_stack[depth] = style.latexname();
2453 sgmlOpenTag(ofs, depth,
2454 environment_stack[depth]);
2456 if(style.latextype == LATEX_ENVIRONMENT) break;
2458 desc_on = (style.labeltype == LABEL_MANUAL);
2465 sgmlOpenTag(ofs, depth + 1, item_name);
2468 sgmlOpenTag(ofs, depth, style.latexname());
2475 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2479 linuxDocHandleFootnote(ofs, par, depth);
2481 while(par && par->IsDummy());
2485 // write closing SGML tags
2486 switch(style.latextype) {
2488 case LATEX_ENVIRONMENT:
2489 case LATEX_ITEM_ENVIRONMENT:
2492 sgmlCloseTag(ofs, depth, style.latexname());
2498 for(; depth > 0; --depth)
2499 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2501 if(!environment_stack[depth].empty())
2502 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2506 sgmlCloseTag(ofs, 0, top_element);
2510 // How to check for successful close
2515 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2518 string const tag = "footnote";
2520 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2521 sgmlOpenTag(os, depth + 1, tag);
2522 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2523 sgmlCloseTag(os, depth + 1, tag);
2530 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2531 int depth, int desc_on,
2532 LyXParagraph * & par)
2534 LyXParagraph * tpar = par;
2537 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2539 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2543 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2544 "Caption").second) {
2545 sgmlOpenTag(os, depth + 1, inner_tag);
2547 SimpleDocBookOnePar(os, extra_par, tpar,
2548 desc_on, depth + 2);
2549 sgmlCloseTag(os, depth+1, inner_tag);
2550 if(!extra_par.empty())
2557 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2560 string tag, inner_tag;
2561 string tmp_par, extra_par;
2562 bool inner_span = false;
2565 // Someone should give this enum a proper name (Lgb)
2573 SOME_ENUM last = NO_ONE;
2574 SOME_ENUM present = FOOTNOTE_LIKE;
2576 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2577 if (last == present) {
2579 if (!tmp_par.empty()) {
2582 sgmlCloseTag(os, depth + 1, inner_tag);
2583 sgmlOpenTag(os, depth + 1, inner_tag);
2590 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2592 if (!extra_par.empty()) os << extra_par;
2593 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2596 switch (par->footnotekind) {
2597 case LyXParagraph::FOOTNOTE:
2598 case LyXParagraph::ALGORITHM:
2601 present = FOOTNOTE_LIKE;
2604 case LyXParagraph::MARGIN:
2607 present = MARGIN_LIKE;
2610 case LyXParagraph::FIG:
2611 case LyXParagraph::WIDE_FIG:
2613 inner_tag = "title";
2617 case LyXParagraph::TAB:
2618 case LyXParagraph::WIDE_TAB:
2620 inner_tag = "title";
2625 sgmlOpenTag(os, depth, tag);
2626 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2627 DocBookHandleCaption(os, inner_tag, depth,
2631 sgmlOpenTag(os, depth + 1, inner_tag);
2634 // ignore all caption here, we processed them above!!!
2635 if (par->layout != textclasslist
2636 .NumberOfLayout(params.textclass,
2637 "Caption").second) {
2638 std::ostringstream ost;
2639 SimpleDocBookOnePar(ost, extra_par, par,
2640 desc_on, depth + 2);
2641 tmp_par += ost.str().c_str();
2643 tmp_par = frontStrip(strip(tmp_par));
2649 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2650 if(!extra_par.empty()) os << extra_par;
2651 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2656 // push a tag in a style stack
2657 void Buffer::push_tag(ostream & os, string const & tag,
2658 int & pos, char stack[5][3])
2660 #warning Use a real stack! (Lgb)
2661 // pop all previous tags
2662 for (int j = pos; j >= 0; --j)
2663 os << "</" << stack[j] << ">";
2666 sprintf(stack[++pos], "%s", tag.c_str());
2669 for (int i = 0; i <= pos; ++i)
2670 os << "<" << stack[i] << ">";
2674 void Buffer::pop_tag(ostream & os, string const & tag,
2675 int & pos, char stack[5][3])
2677 #ifdef WITH_WARNINGS
2678 #warning Use a real stack! (Lgb)
2680 // Please, Lars, do not remove the global variable. I already
2681 // had to reintroduce it twice! (JMarc)
2684 // pop all tags till specified one
2685 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2686 os << "</" << stack[j] << ">";
2689 os << "</" << tag << ">";
2691 // push all tags, but the specified one
2692 for (j = j + 1; j <= pos; ++j) {
2693 os << "<" << stack[j] << ">";
2694 strcpy(stack[j-1], stack[j]);
2700 // Handle internal paragraph parsing -- layout already processed.
2702 // checks, if newcol chars should be put into this line
2703 // writes newline, if necessary.
2705 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2706 string::size_type newcol)
2709 if (colcount > lyxrc.ascii_linelen) {
2711 colcount = newcol; // assume write after this call
2716 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2717 int desc_on, int /*depth*/)
2722 LyXParagraph::size_type main_body;
2724 LyXLayout const & style = textclasslist.Style(params.textclass,
2727 char family_type = 0; // family font flag
2728 bool is_bold = false; // series font flag
2729 char shape_type = 0; // shape font flag
2730 bool is_em = false; // emphasis (italic) font flag
2732 int stack_num = -1; // style stack position
2733 // Can this be rewritten to use a std::stack, please. (Lgb)
2734 char stack[5][3]; // style stack
2735 string::size_type char_line_count = 5; // Heuristic choice ;-)
2737 if (style.labeltype != LABEL_MANUAL)
2740 main_body = par->BeginningOfMainBody();
2742 // gets paragraph main font
2744 font1 = style.labelfont;
2749 // parsing main loop
2750 for (LyXParagraph::size_type i = 0;
2751 i < par->size(); ++i) {
2763 LyXFont const font2 = par->getFont(params, i);
2765 if (font1.family() != font2.family()) {
2766 switch(family_type) {
2768 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2769 push_tag(os, "tt", stack_num, stack);
2772 else if (font2.family() == LyXFont::SANS_FAMILY) {
2773 push_tag(os, "sf", stack_num, stack);
2778 pop_tag(os, "tt", stack_num, stack);
2779 if (font2.family() == LyXFont::SANS_FAMILY) {
2780 push_tag(os, "sf", stack_num, stack);
2787 pop_tag(os, "sf", stack_num, stack);
2788 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2789 push_tag(os, "tt", stack_num, stack);
2798 if (font1.series() != font2.series()) {
2799 if (font2.series() == LyXFont::BOLD_SERIES) {
2800 push_tag(os, "bf", stack_num, stack);
2802 } else if (is_bold) {
2803 pop_tag(os, "bf", stack_num, stack);
2808 // handle italic and slanted fonts
2809 if (font1.shape() != font2.shape()) {
2810 switch(shape_type) {
2812 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2813 push_tag(os, "it", stack_num, stack);
2815 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2816 push_tag(os, "sl", stack_num, stack);
2821 pop_tag(os, "it", stack_num, stack);
2822 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2823 push_tag(os, "sl", stack_num, stack);
2830 pop_tag(os, "sl", stack_num, stack);
2831 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2832 push_tag(os, "it", stack_num, stack);
2840 if (font1.emph() != font2.emph()) {
2841 if (font2.emph() == LyXFont::ON) {
2842 push_tag(os, "em", stack_num, stack);
2845 pop_tag(os, "em", stack_num, stack);
2850 c = par->GetChar(i);
2852 if (c == LyXParagraph::META_INSET) {
2853 inset = par->GetInset(i);
2854 inset->Linuxdoc(this, os);
2857 if (font2.latex() == LyXFont::ON) {
2858 // "TeX"-Mode on == > SGML-Mode on.
2860 os << c; // see LaTeX-Generation...
2864 if (par->linuxDocConvertChar(c, sgml_string)
2865 && !style.free_spacing) { // in freespacing
2867 // non-breaking characters
2871 linux_doc_line_break(os, char_line_count, 6);
2875 linux_doc_line_break(os, char_line_count, 1);
2880 char_line_count += sgml_string.length();
2886 // needed if there is an optional argument but no contents
2887 if (main_body > 0 && main_body == par->size()) {
2891 // pop all defined Styles
2892 for (j = stack_num; j >= 0; --j) {
2893 linux_doc_line_break(os,
2895 3 + strlen(stack[j]));
2896 os << "</" << stack[j] << ">";
2899 // resets description flag correctly
2902 // <tag> not closed...
2903 linux_doc_line_break(os, char_line_count, 6);
2907 // fprintf(file, "</p>");
2913 // Print an error message.
2914 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2915 string const & message)
2917 // insert an error marker in text
2918 InsetError * new_inset = new InsetError(message);
2919 par->InsertInset(pos, new_inset);
2922 // This constant defines the maximum number of
2923 // environment layouts that can be nesteded.
2924 // The same applies for command layouts.
2925 // These values should be more than enough.
2926 // José Matos (1999/07/22)
2928 enum { MAX_NEST_LEVEL = 25};
2930 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2932 LyXParagraph * par = paragraph;
2934 niceFile = nice; // this will be used by Insetincludes.
2936 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2937 // Please use a real stack.
2938 string environment_stack[MAX_NEST_LEVEL];
2939 string environment_inner[MAX_NEST_LEVEL];
2940 // Please use a real stack.
2941 string command_stack[MAX_NEST_LEVEL];
2942 bool command_flag= false;
2943 int command_depth= 0, command_base= 0, cmd_depth= 0;
2945 string item_name, command_name;
2946 string c_depth, c_params, tmps;
2948 int depth = 0; // paragraph depth
2949 LyXTextClass const & tclass =
2950 textclasslist.TextClass(params.textclass);
2952 LaTeXFeatures features(params, tclass.numLayouts());
2956 tex_code_break_column = lyxrc.ascii_linelen;
2958 //tex_code_break_column = 0;
2960 ofstream ofs(fname.c_str());
2962 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2969 string sgml_includedfiles=features.getIncludedFiles();
2971 ofs << "<!doctype " << top_element
2972 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2974 if (params.preamble.empty() && sgml_includedfiles.empty())
2977 ofs << "\n [ " << params.preamble
2978 << sgml_includedfiles << " \n]>\n\n";
2980 if(params.options.empty())
2981 sgmlOpenTag(ofs, 0, top_element);
2983 string top = top_element;
2985 top += params.options;
2986 sgmlOpenTag(ofs, 0, top);
2990 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2991 << "\n See http://www.lyx.org/ for more information -->\n";
2994 int desc_on = 0; // description mode
2995 LyXLayout const & style =
2996 textclasslist.Style(params.textclass,
2999 // environment tag closing
3000 for( ; depth > par->depth; --depth) {
3001 if(environment_inner[depth] != "!-- --") {
3002 item_name= "listitem";
3003 sgmlCloseTag(ofs, command_depth + depth,
3005 if( environment_inner[depth] == "varlistentry")
3006 sgmlCloseTag(ofs, depth+command_depth,
3007 environment_inner[depth]);
3009 sgmlCloseTag(ofs, depth + command_depth,
3010 environment_stack[depth]);
3011 environment_stack[depth].erase();
3012 environment_inner[depth].erase();
3015 if(depth == par->depth
3016 && environment_stack[depth] != style.latexname()
3017 && !environment_stack[depth].empty()) {
3018 if(environment_inner[depth] != "!-- --") {
3019 item_name= "listitem";
3020 sgmlCloseTag(ofs, command_depth+depth,
3022 if( environment_inner[depth] == "varlistentry")
3024 depth + command_depth,
3025 environment_inner[depth]);
3028 sgmlCloseTag(ofs, depth + command_depth,
3029 environment_stack[depth]);
3031 environment_stack[depth].erase();
3032 environment_inner[depth].erase();
3035 // Write opening SGML tags.
3036 switch(style.latextype) {
3037 case LATEX_PARAGRAPH:
3038 if(style.latexname() != "dummy")
3039 sgmlOpenTag(ofs, depth+command_depth,
3045 LinuxDocError(par, 0,
3046 _("Error : Wrong depth for "
3047 "LatexType Command.\n"));
3049 command_name = style.latexname();
3051 tmps = style.latexparam();
3052 c_params = split(tmps, c_depth,'|');
3054 cmd_depth= lyx::atoi(c_depth);
3057 if(cmd_depth<command_base) {
3058 for(int j = command_depth;
3059 j >= command_base; --j)
3060 if(!command_stack[j].empty())
3061 sgmlCloseTag(ofs, j, command_stack[j]);
3062 command_depth= command_base= cmd_depth;
3063 } else if(cmd_depth <= command_depth) {
3064 for(int j = command_depth;
3065 j >= cmd_depth; --j)
3067 if(!command_stack[j].empty())
3068 sgmlCloseTag(ofs, j, command_stack[j]);
3069 command_depth= cmd_depth;
3071 command_depth= cmd_depth;
3073 command_depth = command_base = cmd_depth;
3074 command_flag = true;
3076 command_stack[command_depth]= command_name;
3078 // treat label as a special case for
3079 // more WYSIWYM handling.
3080 if (par->GetChar(0) == LyXParagraph::META_INSET) {
3081 Inset * inset = par->GetInset(0);
3082 Inset::Code lyx_code = inset->LyxCode();
3083 if (lyx_code == Inset::LABEL_CODE){
3084 command_name += " id=\"";
3085 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3086 command_name += "\"";
3091 sgmlOpenTag(ofs, depth + command_depth, command_name);
3092 item_name = "title";
3093 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3096 case LATEX_ENVIRONMENT:
3097 case LATEX_ITEM_ENVIRONMENT:
3098 if (depth < par->depth) {
3100 environment_stack[depth].erase();
3103 if (environment_stack[depth] != style.latexname()) {
3104 environment_stack[depth] = style.latexname();
3105 environment_inner[depth] = "!-- --";
3106 sgmlOpenTag(ofs, depth + command_depth,
3107 environment_stack[depth]);
3109 if(environment_inner[depth] != "!-- --") {
3110 item_name= "listitem";
3112 command_depth + depth,
3114 if (environment_inner[depth] == "varlistentry")
3116 depth + command_depth,
3117 environment_inner[depth]);
3121 if(style.latextype == LATEX_ENVIRONMENT) {
3122 if(!style.latexparam().empty())
3123 sgmlOpenTag(ofs, depth + command_depth,
3124 style.latexparam());
3128 desc_on = (style.labeltype == LABEL_MANUAL);
3131 environment_inner[depth]= "varlistentry";
3133 environment_inner[depth]= "listitem";
3135 sgmlOpenTag(ofs, depth + 1 + command_depth,
3136 environment_inner[depth]);
3140 sgmlOpenTag(ofs, depth + 1 + command_depth,
3144 sgmlOpenTag(ofs, depth + 1 + command_depth,
3149 sgmlOpenTag(ofs, depth + command_depth,
3158 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3159 depth + 1 + command_depth);
3162 DocBookHandleFootnote(ofs, par,
3163 depth + 1 + command_depth);
3165 while(par && par->IsDummy());
3168 // write closing SGML tags
3169 switch(style.latextype) {
3172 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3174 case LATEX_ENVIRONMENT:
3175 if(!style.latexparam().empty())
3176 sgmlCloseTag(ofs, depth + command_depth,
3177 style.latexparam());
3179 case LATEX_ITEM_ENVIRONMENT:
3180 if(desc_on == 1) break;
3182 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3184 case LATEX_PARAGRAPH:
3185 if(style.latexname() != "dummy")
3186 sgmlCloseTag(ofs, depth + command_depth,
3190 sgmlCloseTag(ofs, depth + command_depth,
3197 for(; depth >= 0; --depth) {
3198 if(!environment_stack[depth].empty()) {
3199 if(environment_inner[depth] != "!-- --") {
3200 item_name= "listitem";
3201 sgmlCloseTag(ofs, command_depth + depth,
3203 if( environment_inner[depth] == "varlistentry")
3204 sgmlCloseTag(ofs, depth + command_depth,
3205 environment_inner[depth]);
3208 sgmlCloseTag(ofs, depth + command_depth,
3209 environment_stack[depth]);
3213 for(int j = command_depth; j >= command_base; --j)
3214 if(!command_stack[j].empty())
3215 sgmlCloseTag(ofs, j, command_stack[j]);
3219 sgmlCloseTag(ofs, 0, top_element);
3223 // How to check for successful close
3227 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3228 LyXParagraph * par, int & desc_on,
3231 bool emph_flag = false;
3233 LyXLayout const & style = textclasslist.Style(params.textclass,
3236 LyXParagraph::size_type main_body;
3237 if (style.labeltype != LABEL_MANUAL)
3240 main_body = par->BeginningOfMainBody();
3242 // gets paragraph main font
3243 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3245 int char_line_count = depth;
3246 if(!style.free_spacing)
3247 for (int j = 0; j < depth; ++j)
3250 // parsing main loop
3251 for (LyXParagraph::size_type i = 0;
3252 i < par->size(); ++i) {
3253 LyXFont font2 = par->getFont(params, i);
3255 // handle <emphasis> tag
3256 if (font1.emph() != font2.emph() && i) {
3257 if (font2.emph() == LyXFont::ON) {
3261 os << "</emphasis>";
3266 char c = par->GetChar(i);
3268 if (c == LyXParagraph::META_INSET) {
3269 Inset * inset = par->GetInset(i);
3270 std::ostringstream ost;
3271 inset->DocBook(this, ost);
3272 string tmp_out = ost.str().c_str();
3275 // This code needs some explanation:
3276 // Two insets are treated specially
3277 // label if it is the first element in a command paragraph
3279 // graphics inside tables or figure floats can't go on
3280 // title (the equivalente in latex for this case is caption
3281 // and title should come first
3284 if(desc_on!= 3 || i!= 0) {
3285 if(!tmp_out.empty() && tmp_out[0] == '@') {
3287 extra += frontStrip(tmp_out, '@');
3289 os << frontStrip(tmp_out, '@');
3294 } else if (font2.latex() == LyXFont::ON) {
3295 // "TeX"-Mode on ==> SGML-Mode on.
3301 if (par->linuxDocConvertChar(c, sgml_string)
3302 && !style.free_spacing) { // in freespacing
3304 // non-breaking characters
3308 os << "\n</term><listitem><para>";
3320 // needed if there is an optional argument but no contents
3321 if (main_body > 0 && main_body == par->size()) {
3325 os << "</emphasis>";
3328 // resets description flag correctly
3331 // <term> not closed...
3339 // This should be enabled when the Chktex class is implemented. (Asger)
3340 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3341 // Other flags: -wall -v0 -x
3342 int Buffer::runChktex()
3344 if (!users->text) return 0;
3346 ProhibitInput(users);
3348 // get LaTeX-Filename
3349 string const name = getLatexName();
3350 string path = OnlyPath(filename);
3352 string const org_path = path;
3353 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3357 Path p(path); // path to LaTeX file
3358 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3360 // Remove all error insets
3361 bool const removedErrorInsets = users->removeAutoInsets();
3363 // Generate the LaTeX file if neccessary
3364 makeLaTeXFile(name, org_path, false);
3367 Chktex chktex(lyxrc.chktex_command, name, filepath);
3368 int res = chktex.run(terr); // run chktex
3371 WriteAlert(_("chktex did not work!"),
3372 _("Could not run with file:"), name);
3373 } else if (res > 0) {
3374 // Insert all errors as errors boxes
3375 users->insertErrors(terr);
3378 // if we removed error insets before we ran chktex or if we inserted
3379 // error insets after we ran chktex, this must be run:
3380 if (removedErrorInsets || res){
3382 users->fitCursor(users->text);
3390 void Buffer::validate(LaTeXFeatures & features) const
3392 LyXParagraph * par = paragraph;
3393 LyXTextClass const & tclass =
3394 textclasslist.TextClass(params.textclass);
3396 // AMS Style is at document level
3398 features.amsstyle = (params.use_amsmath ||
3399 tclass.provides(LyXTextClass::amsmath));
3402 // We don't use "lyxerr.debug" because of speed. (Asger)
3403 if (lyxerr.debugging(Debug::LATEX))
3404 lyxerr << "Paragraph: " << par << endl;
3406 // Now just follow the list of paragraphs and run
3407 // validate on each of them.
3408 par->validate(features);
3410 // and then the next paragraph
3414 // the bullet shapes are buffer level not paragraph level
3415 // so they are tested here
3416 for (int i = 0; i < 4; ++i) {
3417 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3418 int const font = params.user_defined_bullets[i].getFont();
3420 int const c = params
3421 .user_defined_bullets[i]
3428 features.latexsym = true;
3430 } else if (font == 1) {
3431 features.amssymb = true;
3432 } else if ((font >= 2 && font <= 5)) {
3433 features.pifont = true;
3438 if (lyxerr.debugging(Debug::LATEX)) {
3439 features.showStruct();
3444 void Buffer::setPaperStuff()
3446 params.papersize = BufferParams::PAPER_DEFAULT;
3447 char const c1 = params.paperpackage;
3448 if (c1 == BufferParams::PACKAGE_NONE) {
3449 char const c2 = params.papersize2;
3450 if (c2 == BufferParams::VM_PAPER_USLETTER)
3451 params.papersize = BufferParams::PAPER_USLETTER;
3452 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3453 params.papersize = BufferParams::PAPER_LEGALPAPER;
3454 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3455 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3456 else if (c2 == BufferParams::VM_PAPER_A3)
3457 params.papersize = BufferParams::PAPER_A3PAPER;
3458 else if (c2 == BufferParams::VM_PAPER_A4)
3459 params.papersize = BufferParams::PAPER_A4PAPER;
3460 else if (c2 == BufferParams::VM_PAPER_A5)
3461 params.papersize = BufferParams::PAPER_A5PAPER;
3462 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3463 (c2 == BufferParams::VM_PAPER_B5))
3464 params.papersize = BufferParams::PAPER_B5PAPER;
3465 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3466 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3467 params.papersize = BufferParams::PAPER_A4PAPER;
3471 // This function should be in Buffer because it's a buffer's property (ale)
3472 string const Buffer::getIncludeonlyList(char delim)
3475 for (inset_iterator it = inset_iterator_begin();
3476 it != inset_iterator_end(); ++it) {
3477 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3478 InsetInclude * insetinc =
3479 static_cast<InsetInclude *>(*it);
3480 if (insetinc->isInclude()
3481 && insetinc->isNoLoad()) {
3484 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3488 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3493 vector<string> const Buffer::getLabelList()
3495 /// if this is a child document and the parent is already loaded
3496 /// Use the parent's list instead [ale990407]
3497 if (!params.parentname.empty()
3498 && bufferlist.exists(params.parentname)) {
3499 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3501 return tmp->getLabelList();
3504 vector<string> label_list;
3505 for (inset_iterator it = inset_iterator_begin();
3506 it != inset_iterator_end(); ++it) {
3507 vector<string> const l = (*it)->getLabelList();
3508 label_list.insert(label_list.end(), l.begin(), l.end());
3514 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3516 vector<vector<TocItem> > l(4);
3517 LyXParagraph * par = paragraph;
3520 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3521 if (textclasslist.Style(params.textclass,
3522 par->GetLayout()).labeltype
3523 == LABEL_SENSITIVE) {
3527 tmp.str = par->String(this, false);
3528 switch (par->footnotekind) {
3529 case LyXParagraph::FIG:
3530 case LyXParagraph::WIDE_FIG:
3531 l[TOC_LOF].push_back(tmp);
3533 case LyXParagraph::TAB:
3534 case LyXParagraph::WIDE_TAB:
3535 l[TOC_LOT].push_back(tmp);
3537 case LyXParagraph::ALGORITHM:
3538 l[TOC_LOA].push_back(tmp);
3540 case LyXParagraph::FOOTNOTE:
3541 case LyXParagraph::MARGIN:
3545 } else if (!par->IsDummy()) {
3547 char const labeltype =
3548 textclasslist.Style(params.textclass,
3549 par->GetLayout()).labeltype;
3551 if (labeltype >= LABEL_COUNTER_CHAPTER
3552 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3553 // insert this into the table of contents
3558 textclasslist.TextClass(params.textclass).maxcounter());
3559 tmp.str = par->String(this, true);
3560 l[TOC_TOC].push_back(tmp);
3571 // This is also a buffer property (ale)
3572 vector<pair<string,string> > const Buffer::getBibkeyList()
3574 /// if this is a child document and the parent is already loaded
3575 /// Use the parent's list instead [ale990412]
3576 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3577 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3579 return tmp->getBibkeyList();
3582 vector<pair<string, string> > keys;
3583 LyXParagraph * par = paragraph;
3586 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3587 par->String(this, false)));
3591 // Might be either using bibtex or a child has bibliography
3593 for (inset_iterator it = inset_iterator_begin();
3594 it != inset_iterator_end(); ++it) {
3595 // Search for Bibtex or Include inset
3596 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3597 vector<pair<string,string> > tmp =
3598 static_cast<InsetBibtex*>(*it)->getKeys(this);
3599 keys.insert(keys.end(), tmp.begin(), tmp.end());
3600 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3601 vector<pair<string,string> > const tmp =
3602 static_cast<InsetInclude*>(*it)->getKeys();
3603 keys.insert(keys.end(), tmp.begin(), tmp.end());
3612 bool Buffer::isDepClean(string const & name) const
3614 DEPCLEAN * item = dep_clean;
3615 while (item && item->master != name)
3617 if (!item) return true;
3622 void Buffer::markDepClean(string const & name)
3625 dep_clean = new DEPCLEAN;
3626 dep_clean->clean = true;
3627 dep_clean->master = name;
3628 dep_clean->next = 0;
3630 DEPCLEAN * item = dep_clean;
3631 while (item && item->master != name)
3636 item = new DEPCLEAN;
3638 item->master = name;
3645 bool Buffer::Dispatch(string const & command)
3647 // Split command string into command and argument
3649 string line = frontStrip(command);
3650 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3652 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3656 bool Buffer::Dispatch(int action, string const & argument)
3658 bool dispatched = true;
3661 Exporter::Export(this, argument, false);
3671 void Buffer::resize()
3673 /// resize the BufferViews!
3679 void Buffer::resizeInsets(BufferView * bv)
3681 /// then remove all LyXText in text-insets
3682 LyXParagraph * par = paragraph;
3683 for(; par; par = par->next) {
3684 par->resizeInsetsLyXText(bv);
3688 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3691 LyXParagraph * par = paragraph;
3693 par->ChangeLanguage(params, from, to);
3699 bool Buffer::isMultiLingual()
3701 LyXParagraph * par = paragraph;
3703 if (par->isMultiLingual(params))
3711 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3712 LyXParagraph::size_type pos)
3715 it = par->InsetIterator(pos);
3716 if (it == par->inset_iterator_end()) {
3723 void Buffer::inset_iterator::SetParagraph()
3726 it = par->inset_iterator_begin();
3727 if (it != par->inset_iterator_end())
3732 // We maintain an invariant that whenever par = 0 then it = 0