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"
87 #include "support/lyxmanip.h"
91 #include "lyx_gui_misc.h" // WarnReadonly()
92 #include "frontends/Dialogs.h"
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(false);
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::setFileName(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);
250 if (format < 2.16 && params.language->lang() == "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);
367 if (format < 2.16 && params.language->lang() == "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);
383 if (format < 2.16 && params.language->lang() == "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 Language const * lang = languages.getLanguage(tok);
776 font.setLanguage(lang);
778 font.setLanguage(params.language);
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, *this);
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) {
1050 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1051 LYX_FORMAT, format) << endl;
1053 if (format - LYX_FORMAT > 0.05) {
1054 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1055 LYX_FORMAT, format) << endl;
1057 bool the_end = readLyXformat2(lex, par);
1058 // Formats >= 2.13 support "\the_end" marker
1065 WriteAlert(_("Warning!"),
1066 _("Reading of document is not complete"),
1067 _("Maybe the document is truncated"));
1068 // We simulate a safe reading anyways to allow
1069 // users to take the chance... (Asger)
1073 WriteAlert(_("ERROR!"),
1074 _("Old LyX file format found. "
1075 "Use LyX 0.10.x to read this!"));
1079 } else { // "\\lyxformat" not found
1080 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1083 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1089 // Should probably be moved to somewhere else: BufferView? LyXView?
1090 bool Buffer::save() const
1092 // We don't need autosaves in the immediate future. (Asger)
1093 resetAutosaveTimers();
1097 if (lyxrc.make_backup) {
1098 s = fileName() + '~';
1099 if (!lyxrc.backupdir_path.empty())
1100 s = AddName(lyxrc.backupdir_path,
1101 subst(CleanupPath(s),'/','!'));
1103 // Rename is the wrong way of making a backup,
1104 // this is the correct way.
1105 /* truss cp fil fil2:
1106 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1107 stat("LyXVC.lyx", 0xEFFFF688) = 0
1108 open("LyXVC.lyx", O_RDONLY) = 3
1109 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1110 fstat(4, 0xEFFFF508) = 0
1111 fstat(3, 0xEFFFF508) = 0
1112 read(3, " # T h i s f i l e w".., 8192) = 5579
1113 write(4, " # T h i s f i l e w".., 5579) = 5579
1114 read(3, 0xEFFFD4A0, 8192) = 0
1117 chmod("LyXVC3.lyx", 0100644) = 0
1118 lseek(0, 0, SEEK_CUR) = 46440
1122 // Should proabaly have some more error checking here.
1123 // Should be cleaned up in 0.13, at least a bit.
1124 // Doing it this way, also makes the inodes stay the same.
1125 // This is still not a very good solution, in particular we
1126 // might loose the owner of the backup.
1127 FileInfo finfo(fileName());
1128 if (finfo.exist()) {
1129 mode_t fmode = finfo.getMode();
1130 struct utimbuf times = {
1131 finfo.getAccessTime(),
1132 finfo.getModificationTime() };
1134 ifstream ifs(fileName().c_str());
1135 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1140 ::chmod(s.c_str(), fmode);
1142 if (::utime(s.c_str(), ×)) {
1143 lyxerr << "utime error." << endl;
1146 lyxerr << "LyX was not able to make "
1147 "backupcopy. Beware." << endl;
1152 if (writeFile(fileName(), false)) {
1154 removeAutosaveFile(fileName());
1156 // Saving failed, so backup is not backup
1157 if (lyxrc.make_backup) {
1158 lyx::rename(s, fileName());
1166 // Returns false if unsuccesful
1167 bool Buffer::writeFile(string const & fname, bool flag) const
1169 // if flag is false writeFile will not create any GUI
1170 // warnings, only cerr.
1171 // Needed for autosave in background or panic save (Matthias 120496)
1173 if (read_only && (fname == filename)) {
1174 // Here we should come with a question if we should
1175 // perform the write anyway.
1177 lyxerr << _("Error! Document is read-only: ")
1180 WriteAlert(_("Error! Document is read-only: "),
1185 FileInfo finfo(fname);
1186 if (finfo.exist() && !finfo.writable()) {
1187 // Here we should come with a question if we should
1188 // try to do the save anyway. (i.e. do a chmod first)
1190 lyxerr << _("Error! Cannot write file: ")
1193 WriteFSAlert(_("Error! Cannot write file: "),
1198 ofstream ofs(fname.c_str());
1201 lyxerr << _("Error! Cannot open file: ")
1204 WriteFSAlert(_("Error! Cannot open file: "),
1210 // Use the standard "C" locale for file output.
1211 ofs.imbue(std::locale::classic());
1214 // The top of the file should not be written by params.
1216 // write out a comment in the top of the file
1217 ofs << '#' << LYX_DOCVERSION
1218 << " created this file. For more info see http://www.lyx.org/\n";
1219 ofs.setf(ios::showpoint|ios::fixed);
1222 char dummy_format[512];
1223 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1224 ofs << "\\lyxformat " << dummy_format << "\n";
1226 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1228 // now write out the buffer paramters.
1229 params.writeFile(ofs);
1231 char footnoteflag = 0;
1234 // this will write out all the paragraphs
1235 // using recursive descent.
1236 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1238 // Write marker that shows file is complete
1239 ofs << "\n\\the_end" << endl;
1243 // how to check if close went ok?
1244 // Following is an attempt... (BE 20001011)
1246 // good() returns false if any error occured, including some
1247 // formatting error.
1248 // bad() returns true if something bad happened in the buffer,
1249 // which should include file system full errors.
1256 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1258 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1269 void Buffer::writeFileAscii(string const & fname, int linelen)
1273 char footnoteflag = 0;
1276 LyXParagraph::size_type i;
1279 int ltype_depth = 0;
1282 int currlinelen = 0;
1284 bool ref_printed = false;
1286 ofstream ofs(fname.c_str());
1288 WriteFSAlert(_("Error: Cannot write file:"), fname);
1292 string const fname1 = TmpFileName();
1293 LyXParagraph * par = paragraph;
1299 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1303 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1308 /* begins a footnote environment ? */
1309 if (footnoteflag != par->footnoteflag) {
1310 footnoteflag = par->footnoteflag;
1312 j = strlen(string_footnotekinds[par->footnotekind])+4;
1313 if (currlinelen + j > linelen)
1316 << string_footnotekinds[par->footnotekind] << "] ";
1322 /* begins or ends a deeper area ?*/
1323 if (depth != par->depth) {
1324 if (par->depth > depth) {
1325 while (par->depth > depth) {
1330 while (par->depth < depth) {
1336 /* First write the layout */
1337 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1338 if (tmp == "Itemize") {
1340 ltype_depth = depth+1;
1341 } else if (tmp == "Enumerate") {
1343 ltype_depth = depth+1;
1344 } else if (contains(tmp, "ection")) {
1346 ltype_depth = depth+1;
1347 } else if (contains(tmp, "aragraph")) {
1349 ltype_depth = depth+1;
1350 } else if (tmp == "Description") {
1352 ltype_depth = depth+1;
1353 } else if (tmp == "Abstract") {
1356 } else if (tmp == "Bibliography") {
1364 /* maybe some vertical spaces */
1366 /* the labelwidthstring used in lists */
1370 /* some pagebreaks? */
1374 /* what about the alignment */
1377 /* dummy layout, that means a footnote ended */
1378 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1382 lyxerr << "Should this ever happen?" << endl;
1387 LyXFont(LyXFont::ALL_INHERIT, params.language);
1389 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1390 if (!i && !footnoteflag && !noparbreak){
1392 for(j = 0; j < depth; ++j)
1394 currlinelen = depth * 2;
1396 case 0: /* Standard */
1397 case 4: /* (Sub)Paragraph */
1398 case 5: /* Description */
1400 case 6: /* Abstract */
1401 ofs << "Abstract\n\n";
1403 case 7: /* Bibliography */
1405 ofs << "References\n\n";
1410 ofs << par->labelstring << " ";
1413 if (ltype_depth > depth) {
1414 for(j = ltype_depth - 1; j > depth; --j)
1416 currlinelen += (ltype_depth-depth)*2;
1419 LyXFont font2 = par->GetFontSettings(params, i);
1420 if (font1.latex() != font2.latex()) {
1421 if (font2.latex() == LyXFont::OFF)
1428 c = par->GetChar(i);
1432 case LyXParagraph::META_INSET:
1433 if ((inset = par->GetInset(i))) {
1435 inset->Ascii(this, ofs);
1436 currlinelen += (ofs.tellp() - fpos);
1437 actpos += (ofs.tellp() - fpos) - 1;
1440 case LyXParagraph::META_NEWLINE:
1442 for(j = 0; j < depth; ++j)
1444 currlinelen = depth * 2;
1445 if (ltype_depth > depth) {
1446 for(j = ltype_depth;
1449 currlinelen += (ltype_depth - depth) * 2;
1452 case LyXParagraph::META_HFILL:
1459 if (currlinelen > linelen - 10
1460 && c == ' ' && i + 2 < par->size()) {
1462 for(j = 0; j < depth; ++j)
1464 currlinelen = depth * 2;
1465 if (ltype_depth > depth) {
1466 for(j = ltype_depth;
1469 currlinelen += (ltype_depth-depth)*2;
1471 } else if (c != '\0')
1474 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1484 //----------------------------------------------------------------------------
1486 //----------------------------------------------------------------------------
1487 string const Buffer::asciiParagraph(LyXParagraph const * par,
1488 unsigned int linelen) const
1490 ostringstream buffer;
1493 Inset const * inset;
1495 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1498 int ltype_depth = 0;
1499 unsigned int currlinelen = 0;
1500 bool ref_printed = false;
1506 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1510 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1514 /* begins a footnote environment ? */
1515 if (footnoteflag != par->footnoteflag) {
1516 footnoteflag = par->footnoteflag;
1518 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1519 if ((linelen > 0) &&
1520 ((currlinelen + j) > linelen)) {
1525 << string_footnotekinds[par->footnotekind]
1531 /* begins or ends a deeper area ?*/
1532 if (depth != par->depth) {
1533 if (par->depth > depth) {
1534 while (par->depth > depth) {
1539 while (par->depth < depth) {
1545 /* First write the layout */
1546 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1547 if (tmp == "Itemize") {
1549 ltype_depth = depth+1;
1550 } else if (tmp == "Enumerate") {
1552 ltype_depth = depth+1;
1553 } else if (strstr(tmp.c_str(), "ection")) {
1555 ltype_depth = depth+1;
1556 } else if (strstr(tmp.c_str(), "aragraph")) {
1558 ltype_depth = depth+1;
1559 } else if (tmp == "Description") {
1561 ltype_depth = depth+1;
1562 } else if (tmp == "Abstract") {
1565 } else if (tmp == "Bibliography") {
1573 /* maybe some vertical spaces */
1575 /* the labelwidthstring used in lists */
1579 /* some pagebreaks? */
1583 /* what about the alignment */
1586 /* dummy layout, that means a footnote ended */
1587 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1591 lyxerr << "Should this ever happen?" << endl;
1595 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1596 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1597 if (!i && !footnoteflag && !noparbreak){
1600 for(char j = 0; j < depth; ++j)
1602 currlinelen = depth * 2;
1604 case 0: /* Standard */
1605 case 4: /* (Sub)Paragraph */
1606 case 5: /* Description */
1608 case 6: /* Abstract */
1610 buffer << "Abstract\n\n";
1612 buffer << "Abstract: ";
1614 case 7: /* Bibliography */
1617 buffer << "References\n\n";
1619 buffer << "References: ";
1624 buffer << par->labelstring << " ";
1627 if (ltype_depth > depth) {
1628 for(char j = ltype_depth - 1; j > depth; --j)
1630 currlinelen += (ltype_depth-depth)*2;
1633 font2 = par->GetFontSettings(params, i);
1634 if (font1.latex() != font2.latex()) {
1635 if (font2.latex() == LyXFont::OFF)
1642 c = par->GetChar(i);
1646 case LyXParagraph::META_INSET:
1647 if ((inset = par->GetInset(i))) {
1648 if (!inset->Ascii(this, buffer)) {
1650 string s = rsplit(buffer.str(),
1652 currlinelen += s.length();
1654 // to be sure it breaks paragraph
1655 currlinelen += linelen;
1659 case LyXParagraph::META_NEWLINE:
1662 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;
1673 case LyXParagraph::META_HFILL:
1680 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1681 (c == ' ') && ((i + 2) < par->size()))
1684 for(char j = 0; j < depth; ++j)
1686 currlinelen = depth * 2;
1687 if (ltype_depth > depth) {
1688 for(char j = ltype_depth;
1691 currlinelen += (ltype_depth-depth)*2;
1693 } else if (c != '\0')
1696 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1701 return buffer.str();
1705 void Buffer::writeFileAscii(string const & fname, int linelen)
1707 ofstream ofs(fname.c_str());
1709 WriteFSAlert(_("Error: Cannot write file:"), fname);
1712 writeFileAscii(ofs, linelen);
1716 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1718 LyXParagraph * par = paragraph;
1720 ofs << asciiParagraph(par, linelen);
1727 void Buffer::makeLaTeXFile(string const & fname,
1728 string const & original_path,
1729 bool nice, bool only_body)
1731 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1733 niceFile = nice; // this will be used by Insetincludes.
1735 tex_code_break_column = lyxrc.ascii_linelen;
1737 LyXTextClass const & tclass =
1738 textclasslist.TextClass(params.textclass);
1740 ofstream ofs(fname.c_str());
1742 WriteFSAlert(_("Error: Cannot open file: "), fname);
1746 // validate the buffer.
1747 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1748 LaTeXFeatures features(params, tclass.numLayouts());
1750 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1753 // The starting paragraph of the coming rows is the
1754 // first paragraph of the document. (Asger)
1755 texrow.start(paragraph, 0);
1757 if (!only_body && nice) {
1758 ofs << "%% " LYX_DOCVERSION " created this file. "
1759 "For more info, see http://www.lyx.org/.\n"
1760 "%% Do not edit unless you really know what "
1765 lyxerr.debug() << "lyx header finished" << endl;
1766 // There are a few differences between nice LaTeX and usual files:
1767 // usual is \batchmode and has a
1768 // special input@path to allow the including of figures
1769 // with either \input or \includegraphics (what figinsets do).
1770 // batchmode is not set if there is a tex_code_break_column.
1771 // In this case somebody is interested in the generated LaTeX,
1772 // so this is OK. input@path is set when the actual parameter
1773 // original_path is set. This is done for usual tex-file, but not
1774 // for nice-latex-file. (Matthias 250696)
1777 // code for usual, NOT nice-latex-file
1778 ofs << "\\batchmode\n"; // changed
1779 // from \nonstopmode
1782 if (!original_path.empty()) {
1783 ofs << "\\makeatletter\n"
1784 << "\\def\\input@path{{"
1785 << original_path << "/}}\n"
1786 << "\\makeatother\n";
1792 ofs << "\\documentclass";
1794 string options; // the document class options.
1796 if (tokenPos(tclass.opt_fontsize(),
1797 '|', params.fontsize) >= 0) {
1798 // only write if existing in list (and not default)
1799 options += params.fontsize;
1804 if (!params.use_geometry &&
1805 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1806 switch (params.papersize) {
1807 case BufferParams::PAPER_A4PAPER:
1808 options += "a4paper,";
1810 case BufferParams::PAPER_USLETTER:
1811 options += "letterpaper,";
1813 case BufferParams::PAPER_A5PAPER:
1814 options += "a5paper,";
1816 case BufferParams::PAPER_B5PAPER:
1817 options += "b5paper,";
1819 case BufferParams::PAPER_EXECUTIVEPAPER:
1820 options += "executivepaper,";
1822 case BufferParams::PAPER_LEGALPAPER:
1823 options += "legalpaper,";
1829 if (params.sides != tclass.sides()) {
1830 switch (params.sides) {
1831 case LyXTextClass::OneSide:
1832 options += "oneside,";
1834 case LyXTextClass::TwoSides:
1835 options += "twoside,";
1842 if (params.columns != tclass.columns()) {
1843 if (params.columns == 2)
1844 options += "twocolumn,";
1846 options += "onecolumn,";
1849 if (!params.use_geometry
1850 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1851 options += "landscape,";
1853 // language should be a parameter to \documentclass
1854 bool use_babel = false;
1855 if (params.language->babel() == "hebrew") // This seems necessary
1856 features.UsedLanguages.insert(default_language);
1857 #ifdef DO_USE_DEFAULT_LANGUAGE
1858 if (params.language->lang() != "default" ||
1859 !features.UsedLanguages.empty() ) {
1862 for (LaTeXFeatures::LanguageList::const_iterator cit =
1863 features.UsedLanguages.begin();
1864 cit != features.UsedLanguages.end(); ++cit)
1865 options += (*cit)->babel() + ",";
1866 options += params.language->babel() + ',';
1867 #ifdef DO_USE_DEFAULT_LANGUAGE
1871 // the user-defined options
1872 if (!params.options.empty()) {
1873 options += params.options + ',';
1876 if (!options.empty()){
1877 options = strip(options, ',');
1878 ofs << '[' << options << ']';
1882 << textclasslist.LatexnameOfClass(params.textclass)
1885 // end of \documentclass defs
1887 // font selection must be done before loading fontenc.sty
1888 if (params.fonts != "default") {
1889 ofs << "\\usepackage{" << params.fonts << "}\n";
1892 // this one is not per buffer
1893 if (lyxrc.fontenc != "default") {
1894 ofs << "\\usepackage[" << lyxrc.fontenc
1899 if (params.inputenc == "auto") {
1900 string const doc_encoding =
1901 params.language->encoding()->LatexName();
1903 // Create a list with all the input encodings used
1905 set<string> encodings;
1906 for (LaTeXFeatures::LanguageList::const_iterator it =
1907 features.UsedLanguages.begin();
1908 it != features.UsedLanguages.end(); ++it)
1909 if ((*it)->encoding()->LatexName() != doc_encoding)
1910 encodings.insert((*it)->encoding()->LatexName());
1912 ofs << "\\usepackage[";
1913 std::copy(encodings.begin(), encodings.end(),
1914 std::ostream_iterator<string>(ofs, ","));
1915 ofs << doc_encoding << "]{inputenc}\n";
1917 } else if (params.inputenc != "default") {
1918 ofs << "\\usepackage[" << params.inputenc
1923 // At the very beginning the text parameters.
1924 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1925 switch (params.paperpackage) {
1926 case BufferParams::PACKAGE_A4:
1927 ofs << "\\usepackage{a4}\n";
1930 case BufferParams::PACKAGE_A4WIDE:
1931 ofs << "\\usepackage{a4wide}\n";
1934 case BufferParams::PACKAGE_WIDEMARGINSA4:
1935 ofs << "\\usepackage[widemargins]{a4}\n";
1940 if (params.use_geometry) {
1941 ofs << "\\usepackage{geometry}\n";
1943 ofs << "\\geometry{verbose";
1944 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1945 ofs << ",landscape";
1946 switch (params.papersize2) {
1947 case BufferParams::VM_PAPER_CUSTOM:
1948 if (!params.paperwidth.empty())
1949 ofs << ",paperwidth="
1950 << params.paperwidth;
1951 if (!params.paperheight.empty())
1952 ofs << ",paperheight="
1953 << params.paperheight;
1955 case BufferParams::VM_PAPER_USLETTER:
1956 ofs << ",letterpaper";
1958 case BufferParams::VM_PAPER_USLEGAL:
1959 ofs << ",legalpaper";
1961 case BufferParams::VM_PAPER_USEXECUTIVE:
1962 ofs << ",executivepaper";
1964 case BufferParams::VM_PAPER_A3:
1967 case BufferParams::VM_PAPER_A4:
1970 case BufferParams::VM_PAPER_A5:
1973 case BufferParams::VM_PAPER_B3:
1976 case BufferParams::VM_PAPER_B4:
1979 case BufferParams::VM_PAPER_B5:
1983 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1984 switch (lyxrc.default_papersize) {
1985 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1986 case BufferParams::PAPER_USLETTER:
1987 ofs << ",letterpaper";
1989 case BufferParams::PAPER_LEGALPAPER:
1990 ofs << ",legalpaper";
1992 case BufferParams::PAPER_EXECUTIVEPAPER:
1993 ofs << ",executivepaper";
1995 case BufferParams::PAPER_A3PAPER:
1998 case BufferParams::PAPER_A4PAPER:
2001 case BufferParams::PAPER_A5PAPER:
2004 case BufferParams::PAPER_B5PAPER:
2009 if (!params.topmargin.empty())
2010 ofs << ",tmargin=" << params.topmargin;
2011 if (!params.bottommargin.empty())
2012 ofs << ",bmargin=" << params.bottommargin;
2013 if (!params.leftmargin.empty())
2014 ofs << ",lmargin=" << params.leftmargin;
2015 if (!params.rightmargin.empty())
2016 ofs << ",rmargin=" << params.rightmargin;
2017 if (!params.headheight.empty())
2018 ofs << ",headheight=" << params.headheight;
2019 if (!params.headsep.empty())
2020 ofs << ",headsep=" << params.headsep;
2021 if (!params.footskip.empty())
2022 ofs << ",footskip=" << params.footskip;
2026 if (params.use_amsmath
2027 && !tclass.provides(LyXTextClass::amsmath)) {
2028 ofs << "\\usepackage{amsmath}\n";
2032 if (tokenPos(tclass.opt_pagestyle(),
2033 '|', params.pagestyle) >= 0) {
2034 if (params.pagestyle == "fancy") {
2035 ofs << "\\usepackage{fancyhdr}\n";
2038 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2042 // We try to load babel late, in case it interferes
2043 // with other packages.
2045 ofs << lyxrc.language_package << endl;
2049 if (params.secnumdepth != tclass.secnumdepth()) {
2050 ofs << "\\setcounter{secnumdepth}{"
2051 << params.secnumdepth
2055 if (params.tocdepth != tclass.tocdepth()) {
2056 ofs << "\\setcounter{tocdepth}{"
2062 if (params.paragraph_separation) {
2063 switch (params.defskip.kind()) {
2064 case VSpace::SMALLSKIP:
2065 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2067 case VSpace::MEDSKIP:
2068 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2070 case VSpace::BIGSKIP:
2071 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2073 case VSpace::LENGTH:
2074 ofs << "\\setlength\\parskip{"
2075 << params.defskip.length().asLatexString()
2078 default: // should never happen // Then delete it.
2079 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2084 ofs << "\\setlength\\parindent{0pt}\n";
2088 // Now insert the LyX specific LaTeX commands...
2090 // The optional packages;
2091 string preamble(features.getPackages());
2093 // this might be useful...
2094 preamble += "\n\\makeatletter\n";
2096 // Some macros LyX will need
2097 string tmppreamble(features.getMacros());
2099 if (!tmppreamble.empty()) {
2100 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2101 "LyX specific LaTeX commands.\n"
2102 + tmppreamble + '\n';
2105 // the text class specific preamble
2106 tmppreamble = features.getTClassPreamble();
2107 if (!tmppreamble.empty()) {
2108 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2109 "Textclass specific LaTeX commands.\n"
2110 + tmppreamble + '\n';
2113 /* the user-defined preamble */
2114 if (!params.preamble.empty()) {
2115 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2116 "User specified LaTeX commands.\n"
2117 + params.preamble + '\n';
2120 preamble += "\\makeatother\n";
2122 // Itemize bullet settings need to be last in case the user
2123 // defines their own bullets that use a package included
2124 // in the user-defined preamble -- ARRae
2125 // Actually it has to be done much later than that
2126 // since some packages like frenchb make modifications
2127 // at \begin{document} time -- JMarc
2129 for (int i = 0; i < 4; ++i) {
2130 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2131 if (bullets_def.empty())
2132 bullets_def="\\AtBeginDocument{\n";
2133 bullets_def += " \\renewcommand{\\labelitemi";
2135 // `i' is one less than the item to modify
2142 bullets_def += "ii";
2148 bullets_def += "}{" +
2149 params.user_defined_bullets[i].getText()
2154 if (!bullets_def.empty())
2155 preamble += bullets_def + "}\n\n";
2157 for (int j = countChar(preamble, '\n'); j-- ;) {
2164 ofs << "\\begin{document}\n";
2167 lyxerr.debug() << "preamble finished, now the body." << endl;
2168 #ifdef DO_USE_DEFAULT_LANGUAGE
2169 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2171 if (!lyxrc.language_auto_begin) {
2173 ofs << subst(lyxrc.language_command_begin, "$$lang",
2174 params.language->babel())
2179 latexParagraphs(ofs, paragraph, 0, texrow);
2181 // add this just in case after all the paragraphs
2185 #ifdef DO_USE_DEFAULT_LANGUAGE
2186 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2188 if (!lyxrc.language_auto_end) {
2190 ofs << subst(lyxrc.language_command_end, "$$lang",
2191 params.language->babel())
2197 ofs << "\\end{document}\n";
2200 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2202 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2206 // Just to be sure. (Asger)
2209 // tex_code_break_column's value is used to decide
2210 // if we are in batchmode or not (within mathed_write()
2211 // in math_write.C) so we must set it to a non-zero
2212 // value when we leave otherwise we save incorrect .lyx files.
2213 tex_code_break_column = lyxrc.ascii_linelen;
2217 lyxerr << "File was not closed properly." << endl;
2220 lyxerr.debug() << "Finished making latex file." << endl;
2225 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2227 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2228 LyXParagraph * endpar, TexRow & texrow) const
2230 bool was_title = false;
2231 bool already_title = false;
2232 std::ostringstream ftnote;
2237 while (par != endpar) {
2240 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2243 LyXLayout const & layout =
2244 textclasslist.Style(params.textclass,
2247 if (layout.intitle) {
2248 if (already_title) {
2249 lyxerr <<"Error in latexParagraphs: You"
2250 " should not mix title layouts"
2251 " with normal ones." << endl;
2254 } else if (was_title && !already_title) {
2255 ofs << "\\maketitle\n";
2257 already_title = true;
2260 // We are at depth 0 so we can just use
2261 // ordinary \footnote{} generation
2262 // flag this with ftcount
2264 if (layout.isEnvironment()
2265 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2266 par = par->TeXEnvironment(this, params, ofs, texrow
2268 ,ftnote, ft_texrow, ftcount
2272 par = par->TeXOnePar(this, params, ofs, texrow, false
2275 ftnote, ft_texrow, ftcount
2280 // Write out what we've generated...
2283 ofs << "\\addtocounter{footnote}{-"
2287 ofs << ftnote.str();
2288 texrow += ft_texrow;
2290 // The extra .c_str() is needed when we use
2291 // lyxstring instead of the STL string class.
2292 ftnote.str(string().c_str());
2297 // It might be that we only have a title in this document
2298 if (was_title && !already_title) {
2299 ofs << "\\maketitle\n";
2305 bool Buffer::isLatex() const
2307 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2311 bool Buffer::isLinuxDoc() const
2313 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2317 bool Buffer::isLiterate() const
2319 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2323 bool Buffer::isDocBook() const
2325 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2329 bool Buffer::isSGML() const
2331 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2332 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2336 void Buffer::sgmlOpenTag(ostream & os, int depth,
2337 string const & latexname) const
2339 os << string(depth, ' ') << "<" << latexname << ">\n";
2343 void Buffer::sgmlCloseTag(ostream & os, int depth,
2344 string const & latexname) const
2346 os << string(depth, ' ') << "</" << latexname << ">\n";
2350 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2352 LyXParagraph * par = paragraph;
2354 niceFile = nice; // this will be used by Insetincludes.
2356 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2357 string environment_stack[10];
2360 int depth = 0; // paragraph depth
2362 ofstream ofs(fname.c_str());
2365 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2369 LyXTextClass const & tclass =
2370 textclasslist.TextClass(params.textclass);
2372 LaTeXFeatures features(params, tclass.numLayouts());
2376 tex_code_break_column = lyxrc.ascii_linelen;
2378 //tex_code_break_column = 0;
2383 string sgml_includedfiles=features.getIncludedFiles();
2385 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2386 ofs << "<!doctype linuxdoc system>\n\n";
2388 ofs << "<!doctype linuxdoc system [ "
2389 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2392 if(params.options.empty())
2393 sgmlOpenTag(ofs, 0, top_element);
2395 string top = top_element;
2397 top += params.options;
2398 sgmlOpenTag(ofs, 0, top);
2402 ofs << "<!-- " << LYX_DOCVERSION
2403 << " created this file. For more info see http://www.lyx.org/"
2407 int desc_on = 0; // description mode
2408 LyXLayout const & style =
2409 textclasslist.Style(params.textclass,
2412 // treat <toc> as a special case for compatibility with old code
2413 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2414 Inset * inset = par->GetInset(0);
2415 Inset::Code lyx_code = inset->LyxCode();
2416 if (lyx_code == Inset::TOC_CODE){
2417 string const temp = "toc";
2418 sgmlOpenTag(ofs, depth, temp);
2422 linuxDocHandleFootnote(ofs, par, depth);
2428 // environment tag closing
2429 for (; depth > par->depth; --depth) {
2430 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2431 environment_stack[depth].erase();
2434 // write opening SGML tags
2435 switch (style.latextype) {
2436 case LATEX_PARAGRAPH:
2437 if(depth == par->depth
2438 && !environment_stack[depth].empty()) {
2439 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2440 environment_stack[depth].erase();
2446 sgmlOpenTag(ofs, depth, style.latexname());
2451 LinuxDocError(par, 0,
2452 _("Error : Wrong depth for"
2453 " LatexType Command.\n"));
2455 if (!environment_stack[depth].empty()){
2456 sgmlCloseTag(ofs, depth,
2457 environment_stack[depth]);
2461 environment_stack[depth].erase();
2462 sgmlOpenTag(ofs, depth, style.latexname());
2465 case LATEX_ENVIRONMENT:
2466 case LATEX_ITEM_ENVIRONMENT:
2467 if (depth == par->depth
2468 && environment_stack[depth] != style.latexname()
2469 && !environment_stack[depth].empty()) {
2471 sgmlCloseTag(ofs, depth,
2472 environment_stack[depth]);
2473 environment_stack[depth].erase();
2475 if (depth < par->depth) {
2477 environment_stack[depth].erase();
2479 if (environment_stack[depth] != style.latexname()) {
2481 string const temp = "p";
2482 sgmlOpenTag(ofs, depth, temp);
2484 environment_stack[depth] = style.latexname();
2485 sgmlOpenTag(ofs, depth,
2486 environment_stack[depth]);
2488 if(style.latextype == LATEX_ENVIRONMENT) break;
2490 desc_on = (style.labeltype == LABEL_MANUAL);
2497 sgmlOpenTag(ofs, depth + 1, item_name);
2500 sgmlOpenTag(ofs, depth, style.latexname());
2507 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2511 linuxDocHandleFootnote(ofs, par, depth);
2513 while(par && par->IsDummy());
2517 // write closing SGML tags
2518 switch(style.latextype) {
2520 case LATEX_ENVIRONMENT:
2521 case LATEX_ITEM_ENVIRONMENT:
2524 sgmlCloseTag(ofs, depth, style.latexname());
2530 for(; depth > 0; --depth)
2531 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2533 if(!environment_stack[depth].empty())
2534 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2538 sgmlCloseTag(ofs, 0, top_element);
2542 // How to check for successful close
2547 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2550 string const tag = "footnote";
2552 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2553 sgmlOpenTag(os, depth + 1, tag);
2554 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2555 sgmlCloseTag(os, depth + 1, tag);
2562 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2563 int depth, int desc_on,
2564 LyXParagraph * & par)
2566 LyXParagraph * tpar = par;
2569 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2571 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2575 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2576 "Caption").second) {
2577 sgmlOpenTag(os, depth + 1, inner_tag);
2579 SimpleDocBookOnePar(os, extra_par, tpar,
2580 desc_on, depth + 2);
2581 sgmlCloseTag(os, depth+1, inner_tag);
2582 if(!extra_par.empty())
2589 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2592 string tag, inner_tag;
2593 string tmp_par, extra_par;
2594 bool inner_span = false;
2597 // Someone should give this enum a proper name (Lgb)
2605 SOME_ENUM last = NO_ONE;
2606 SOME_ENUM present = FOOTNOTE_LIKE;
2608 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2609 if (last == present) {
2611 if (!tmp_par.empty()) {
2614 sgmlCloseTag(os, depth + 1, inner_tag);
2615 sgmlOpenTag(os, depth + 1, inner_tag);
2622 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2624 if (!extra_par.empty()) os << extra_par;
2625 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2628 switch (par->footnotekind) {
2629 case LyXParagraph::FOOTNOTE:
2630 case LyXParagraph::ALGORITHM:
2633 present = FOOTNOTE_LIKE;
2636 case LyXParagraph::MARGIN:
2639 present = MARGIN_LIKE;
2642 case LyXParagraph::FIG:
2643 case LyXParagraph::WIDE_FIG:
2645 inner_tag = "title";
2649 case LyXParagraph::TAB:
2650 case LyXParagraph::WIDE_TAB:
2652 inner_tag = "title";
2657 sgmlOpenTag(os, depth, tag);
2658 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2659 DocBookHandleCaption(os, inner_tag, depth,
2663 sgmlOpenTag(os, depth + 1, inner_tag);
2666 // ignore all caption here, we processed them above!!!
2667 if (par->layout != textclasslist
2668 .NumberOfLayout(params.textclass,
2669 "Caption").second) {
2670 std::ostringstream ost;
2671 SimpleDocBookOnePar(ost, extra_par, par,
2672 desc_on, depth + 2);
2673 tmp_par += ost.str().c_str();
2675 tmp_par = frontStrip(strip(tmp_par));
2681 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2682 if(!extra_par.empty()) os << extra_par;
2683 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2688 // push a tag in a style stack
2689 void Buffer::push_tag(ostream & os, string const & tag,
2690 int & pos, char stack[5][3])
2692 #ifdef WITH_WARNINGS
2693 #warning Use a real stack! (Lgb)
2695 // pop all previous tags
2696 for (int j = pos; j >= 0; --j)
2697 os << "</" << stack[j] << ">";
2700 sprintf(stack[++pos], "%s", tag.c_str());
2703 for (int i = 0; i <= pos; ++i)
2704 os << "<" << stack[i] << ">";
2708 void Buffer::pop_tag(ostream & os, string const & tag,
2709 int & pos, char stack[5][3])
2711 #ifdef WITH_WARNINGS
2712 #warning Use a real stack! (Lgb)
2714 // Please, Lars, do not remove the global variable. I already
2715 // had to reintroduce it twice! (JMarc)
2718 // pop all tags till specified one
2719 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2720 os << "</" << stack[j] << ">";
2723 os << "</" << tag << ">";
2725 // push all tags, but the specified one
2726 for (j = j + 1; j <= pos; ++j) {
2727 os << "<" << stack[j] << ">";
2728 strcpy(stack[j-1], stack[j]);
2734 // Handle internal paragraph parsing -- layout already processed.
2736 // checks, if newcol chars should be put into this line
2737 // writes newline, if necessary.
2739 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2740 string::size_type newcol)
2743 if (colcount > lyxrc.ascii_linelen) {
2745 colcount = newcol; // assume write after this call
2750 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2751 int desc_on, int /*depth*/)
2756 LyXParagraph::size_type main_body;
2758 LyXLayout const & style = textclasslist.Style(params.textclass,
2761 char family_type = 0; // family font flag
2762 bool is_bold = false; // series font flag
2763 char shape_type = 0; // shape font flag
2764 bool is_em = false; // emphasis (italic) font flag
2766 int stack_num = -1; // style stack position
2767 // Can this be rewritten to use a std::stack, please. (Lgb)
2768 char stack[5][3]; // style stack
2769 string::size_type char_line_count = 5; // Heuristic choice ;-)
2771 if (style.labeltype != LABEL_MANUAL)
2774 main_body = par->BeginningOfMainBody();
2776 // gets paragraph main font
2778 font1 = style.labelfont;
2783 // parsing main loop
2784 for (LyXParagraph::size_type i = 0;
2785 i < par->size(); ++i) {
2797 LyXFont const font2 = par->getFont(params, i);
2799 if (font1.family() != font2.family()) {
2800 switch(family_type) {
2802 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2803 push_tag(os, "tt", stack_num, stack);
2806 else if (font2.family() == LyXFont::SANS_FAMILY) {
2807 push_tag(os, "sf", stack_num, stack);
2812 pop_tag(os, "tt", stack_num, stack);
2813 if (font2.family() == LyXFont::SANS_FAMILY) {
2814 push_tag(os, "sf", stack_num, stack);
2821 pop_tag(os, "sf", stack_num, stack);
2822 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2823 push_tag(os, "tt", stack_num, stack);
2832 if (font1.series() != font2.series()) {
2833 if (font2.series() == LyXFont::BOLD_SERIES) {
2834 push_tag(os, "bf", stack_num, stack);
2836 } else if (is_bold) {
2837 pop_tag(os, "bf", stack_num, stack);
2842 // handle italic and slanted fonts
2843 if (font1.shape() != font2.shape()) {
2844 switch(shape_type) {
2846 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2847 push_tag(os, "it", stack_num, stack);
2849 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2850 push_tag(os, "sl", stack_num, stack);
2855 pop_tag(os, "it", stack_num, stack);
2856 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2857 push_tag(os, "sl", stack_num, stack);
2864 pop_tag(os, "sl", stack_num, stack);
2865 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2866 push_tag(os, "it", stack_num, stack);
2874 if (font1.emph() != font2.emph()) {
2875 if (font2.emph() == LyXFont::ON) {
2876 push_tag(os, "em", stack_num, stack);
2879 pop_tag(os, "em", stack_num, stack);
2884 c = par->GetChar(i);
2886 if (c == LyXParagraph::META_INSET) {
2887 inset = par->GetInset(i);
2888 inset->Linuxdoc(this, os);
2891 if (font2.latex() == LyXFont::ON) {
2892 // "TeX"-Mode on == > SGML-Mode on.
2894 os << c; // see LaTeX-Generation...
2898 if (par->linuxDocConvertChar(c, sgml_string)
2899 && !style.free_spacing) { // in freespacing
2901 // non-breaking characters
2905 linux_doc_line_break(os, char_line_count, 6);
2909 linux_doc_line_break(os, char_line_count, 1);
2914 char_line_count += sgml_string.length();
2920 // needed if there is an optional argument but no contents
2921 if (main_body > 0 && main_body == par->size()) {
2925 // pop all defined Styles
2926 for (j = stack_num; j >= 0; --j) {
2927 linux_doc_line_break(os,
2929 3 + strlen(stack[j]));
2930 os << "</" << stack[j] << ">";
2933 // resets description flag correctly
2936 // <tag> not closed...
2937 linux_doc_line_break(os, char_line_count, 6);
2941 // fprintf(file, "</p>");
2947 // Print an error message.
2948 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2949 string const & message)
2951 // insert an error marker in text
2952 InsetError * new_inset = new InsetError(message);
2953 par->InsertInset(pos, new_inset);
2956 // This constant defines the maximum number of
2957 // environment layouts that can be nesteded.
2958 // The same applies for command layouts.
2959 // These values should be more than enough.
2960 // José Matos (1999/07/22)
2962 enum { MAX_NEST_LEVEL = 25};
2964 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2966 LyXParagraph * par = paragraph;
2968 niceFile = nice; // this will be used by Insetincludes.
2970 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2971 // Please use a real stack.
2972 string environment_stack[MAX_NEST_LEVEL];
2973 string environment_inner[MAX_NEST_LEVEL];
2974 // Please use a real stack.
2975 string command_stack[MAX_NEST_LEVEL];
2976 bool command_flag= false;
2977 int command_depth= 0, command_base= 0, cmd_depth= 0;
2979 string item_name, command_name;
2980 string c_depth, c_params, tmps;
2982 int depth = 0; // paragraph depth
2983 LyXTextClass const & tclass =
2984 textclasslist.TextClass(params.textclass);
2986 LaTeXFeatures features(params, tclass.numLayouts());
2990 tex_code_break_column = lyxrc.ascii_linelen;
2992 //tex_code_break_column = 0;
2994 ofstream ofs(fname.c_str());
2996 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3003 string sgml_includedfiles=features.getIncludedFiles();
3005 ofs << "<!doctype " << top_element
3006 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3008 if (params.preamble.empty() && sgml_includedfiles.empty())
3011 ofs << "\n [ " << params.preamble
3012 << sgml_includedfiles << " \n]>\n\n";
3014 if(params.options.empty())
3015 sgmlOpenTag(ofs, 0, top_element);
3017 string top = top_element;
3019 top += params.options;
3020 sgmlOpenTag(ofs, 0, top);
3024 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3025 << "\n See http://www.lyx.org/ for more information -->\n";
3028 int desc_on = 0; // description mode
3029 LyXLayout const & style =
3030 textclasslist.Style(params.textclass,
3033 // environment tag closing
3034 for( ; depth > par->depth; --depth) {
3035 if(environment_inner[depth] != "!-- --") {
3036 item_name= "listitem";
3037 sgmlCloseTag(ofs, command_depth + depth,
3039 if( environment_inner[depth] == "varlistentry")
3040 sgmlCloseTag(ofs, depth+command_depth,
3041 environment_inner[depth]);
3043 sgmlCloseTag(ofs, depth + command_depth,
3044 environment_stack[depth]);
3045 environment_stack[depth].erase();
3046 environment_inner[depth].erase();
3049 if(depth == par->depth
3050 && environment_stack[depth] != style.latexname()
3051 && !environment_stack[depth].empty()) {
3052 if(environment_inner[depth] != "!-- --") {
3053 item_name= "listitem";
3054 sgmlCloseTag(ofs, command_depth+depth,
3056 if( environment_inner[depth] == "varlistentry")
3058 depth + command_depth,
3059 environment_inner[depth]);
3062 sgmlCloseTag(ofs, depth + command_depth,
3063 environment_stack[depth]);
3065 environment_stack[depth].erase();
3066 environment_inner[depth].erase();
3069 // Write opening SGML tags.
3070 switch(style.latextype) {
3071 case LATEX_PARAGRAPH:
3072 if(style.latexname() != "dummy")
3073 sgmlOpenTag(ofs, depth+command_depth,
3079 LinuxDocError(par, 0,
3080 _("Error : Wrong depth for "
3081 "LatexType Command.\n"));
3083 command_name = style.latexname();
3085 tmps = style.latexparam();
3086 c_params = split(tmps, c_depth,'|');
3088 cmd_depth= lyx::atoi(c_depth);
3091 if(cmd_depth<command_base) {
3092 for(int j = command_depth;
3093 j >= command_base; --j)
3094 if(!command_stack[j].empty())
3095 sgmlCloseTag(ofs, j, command_stack[j]);
3096 command_depth= command_base= cmd_depth;
3097 } else if(cmd_depth <= command_depth) {
3098 for(int j = command_depth;
3099 j >= cmd_depth; --j)
3101 if(!command_stack[j].empty())
3102 sgmlCloseTag(ofs, j, command_stack[j]);
3103 command_depth= cmd_depth;
3105 command_depth= cmd_depth;
3107 command_depth = command_base = cmd_depth;
3108 command_flag = true;
3110 command_stack[command_depth]= command_name;
3112 // treat label as a special case for
3113 // more WYSIWYM handling.
3114 if (par->GetChar(0) == LyXParagraph::META_INSET) {
3115 Inset * inset = par->GetInset(0);
3116 Inset::Code lyx_code = inset->LyxCode();
3117 if (lyx_code == Inset::LABEL_CODE){
3118 command_name += " id=\"";
3119 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3120 command_name += "\"";
3125 sgmlOpenTag(ofs, depth + command_depth, command_name);
3126 item_name = "title";
3127 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3130 case LATEX_ENVIRONMENT:
3131 case LATEX_ITEM_ENVIRONMENT:
3132 if (depth < par->depth) {
3134 environment_stack[depth].erase();
3137 if (environment_stack[depth] != style.latexname()) {
3138 environment_stack[depth] = style.latexname();
3139 environment_inner[depth] = "!-- --";
3140 sgmlOpenTag(ofs, depth + command_depth,
3141 environment_stack[depth]);
3143 if(environment_inner[depth] != "!-- --") {
3144 item_name= "listitem";
3146 command_depth + depth,
3148 if (environment_inner[depth] == "varlistentry")
3150 depth + command_depth,
3151 environment_inner[depth]);
3155 if(style.latextype == LATEX_ENVIRONMENT) {
3156 if(!style.latexparam().empty())
3157 sgmlOpenTag(ofs, depth + command_depth,
3158 style.latexparam());
3162 desc_on = (style.labeltype == LABEL_MANUAL);
3165 environment_inner[depth]= "varlistentry";
3167 environment_inner[depth]= "listitem";
3169 sgmlOpenTag(ofs, depth + 1 + command_depth,
3170 environment_inner[depth]);
3174 sgmlOpenTag(ofs, depth + 1 + command_depth,
3178 sgmlOpenTag(ofs, depth + 1 + command_depth,
3183 sgmlOpenTag(ofs, depth + command_depth,
3192 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3193 depth + 1 + command_depth);
3196 DocBookHandleFootnote(ofs, par,
3197 depth + 1 + command_depth);
3199 while(par && par->IsDummy());
3202 // write closing SGML tags
3203 switch(style.latextype) {
3206 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3208 case LATEX_ENVIRONMENT:
3209 if(!style.latexparam().empty())
3210 sgmlCloseTag(ofs, depth + command_depth,
3211 style.latexparam());
3213 case LATEX_ITEM_ENVIRONMENT:
3214 if(desc_on == 1) break;
3216 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3218 case LATEX_PARAGRAPH:
3219 if(style.latexname() != "dummy")
3220 sgmlCloseTag(ofs, depth + command_depth,
3224 sgmlCloseTag(ofs, depth + command_depth,
3231 for(; depth >= 0; --depth) {
3232 if(!environment_stack[depth].empty()) {
3233 if(environment_inner[depth] != "!-- --") {
3234 item_name= "listitem";
3235 sgmlCloseTag(ofs, command_depth + depth,
3237 if( environment_inner[depth] == "varlistentry")
3238 sgmlCloseTag(ofs, depth + command_depth,
3239 environment_inner[depth]);
3242 sgmlCloseTag(ofs, depth + command_depth,
3243 environment_stack[depth]);
3247 for(int j = command_depth; j >= command_base; --j)
3248 if(!command_stack[j].empty())
3249 sgmlCloseTag(ofs, j, command_stack[j]);
3253 sgmlCloseTag(ofs, 0, top_element);
3257 // How to check for successful close
3261 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3262 LyXParagraph * par, int & desc_on,
3265 bool emph_flag = false;
3267 LyXLayout const & style = textclasslist.Style(params.textclass,
3270 LyXParagraph::size_type main_body;
3271 if (style.labeltype != LABEL_MANUAL)
3274 main_body = par->BeginningOfMainBody();
3276 // gets paragraph main font
3277 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3279 int char_line_count = depth;
3280 if(!style.free_spacing)
3281 for (int j = 0; j < depth; ++j)
3284 // parsing main loop
3285 for (LyXParagraph::size_type i = 0;
3286 i < par->size(); ++i) {
3287 LyXFont font2 = par->getFont(params, i);
3289 // handle <emphasis> tag
3290 if (font1.emph() != font2.emph() && i) {
3291 if (font2.emph() == LyXFont::ON) {
3295 os << "</emphasis>";
3300 char c = par->GetChar(i);
3302 if (c == LyXParagraph::META_INSET) {
3303 Inset * inset = par->GetInset(i);
3304 std::ostringstream ost;
3305 inset->DocBook(this, ost);
3306 string tmp_out = ost.str().c_str();
3309 // This code needs some explanation:
3310 // Two insets are treated specially
3311 // label if it is the first element in a command paragraph
3313 // graphics inside tables or figure floats can't go on
3314 // title (the equivalente in latex for this case is caption
3315 // and title should come first
3318 if(desc_on!= 3 || i!= 0) {
3319 if(!tmp_out.empty() && tmp_out[0] == '@') {
3321 extra += frontStrip(tmp_out, '@');
3323 os << frontStrip(tmp_out, '@');
3328 } else if (font2.latex() == LyXFont::ON) {
3329 // "TeX"-Mode on ==> SGML-Mode on.
3335 if (par->linuxDocConvertChar(c, sgml_string)
3336 && !style.free_spacing) { // in freespacing
3338 // non-breaking characters
3342 os << "\n</term><listitem><para>";
3354 // needed if there is an optional argument but no contents
3355 if (main_body > 0 && main_body == par->size()) {
3359 os << "</emphasis>";
3362 // resets description flag correctly
3365 // <term> not closed...
3373 // This should be enabled when the Chktex class is implemented. (Asger)
3374 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3375 // Other flags: -wall -v0 -x
3376 int Buffer::runChktex()
3378 if (!users->text) return 0;
3380 ProhibitInput(users);
3382 // get LaTeX-Filename
3383 string const name = getLatexName();
3384 string path = OnlyPath(filename);
3386 string const org_path = path;
3387 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3391 Path p(path); // path to LaTeX file
3392 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3394 // Remove all error insets
3395 bool const removedErrorInsets = users->removeAutoInsets();
3397 // Generate the LaTeX file if neccessary
3398 makeLaTeXFile(name, org_path, false);
3401 Chktex chktex(lyxrc.chktex_command, name, filepath);
3402 int res = chktex.run(terr); // run chktex
3405 WriteAlert(_("chktex did not work!"),
3406 _("Could not run with file:"), name);
3407 } else if (res > 0) {
3408 // Insert all errors as errors boxes
3409 users->insertErrors(terr);
3412 // if we removed error insets before we ran chktex or if we inserted
3413 // error insets after we ran chktex, this must be run:
3414 if (removedErrorInsets || res){
3416 users->fitCursor(users->text);
3424 void Buffer::validate(LaTeXFeatures & features) const
3426 LyXParagraph * par = paragraph;
3427 LyXTextClass const & tclass =
3428 textclasslist.TextClass(params.textclass);
3430 // AMS Style is at document level
3432 features.amsstyle = (params.use_amsmath ||
3433 tclass.provides(LyXTextClass::amsmath));
3436 // We don't use "lyxerr.debug" because of speed. (Asger)
3437 if (lyxerr.debugging(Debug::LATEX))
3438 lyxerr << "Paragraph: " << par << endl;
3440 // Now just follow the list of paragraphs and run
3441 // validate on each of them.
3442 par->validate(features);
3444 // and then the next paragraph
3448 // the bullet shapes are buffer level not paragraph level
3449 // so they are tested here
3450 for (int i = 0; i < 4; ++i) {
3451 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3452 int const font = params.user_defined_bullets[i].getFont();
3454 int const c = params
3455 .user_defined_bullets[i]
3462 features.latexsym = true;
3464 } else if (font == 1) {
3465 features.amssymb = true;
3466 } else if ((font >= 2 && font <= 5)) {
3467 features.pifont = true;
3472 if (lyxerr.debugging(Debug::LATEX)) {
3473 features.showStruct();
3478 void Buffer::setPaperStuff()
3480 params.papersize = BufferParams::PAPER_DEFAULT;
3481 char const c1 = params.paperpackage;
3482 if (c1 == BufferParams::PACKAGE_NONE) {
3483 char const c2 = params.papersize2;
3484 if (c2 == BufferParams::VM_PAPER_USLETTER)
3485 params.papersize = BufferParams::PAPER_USLETTER;
3486 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3487 params.papersize = BufferParams::PAPER_LEGALPAPER;
3488 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3489 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3490 else if (c2 == BufferParams::VM_PAPER_A3)
3491 params.papersize = BufferParams::PAPER_A3PAPER;
3492 else if (c2 == BufferParams::VM_PAPER_A4)
3493 params.papersize = BufferParams::PAPER_A4PAPER;
3494 else if (c2 == BufferParams::VM_PAPER_A5)
3495 params.papersize = BufferParams::PAPER_A5PAPER;
3496 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3497 (c2 == BufferParams::VM_PAPER_B5))
3498 params.papersize = BufferParams::PAPER_B5PAPER;
3499 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3500 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3501 params.papersize = BufferParams::PAPER_A4PAPER;
3505 // This function should be in Buffer because it's a buffer's property (ale)
3506 string const Buffer::getIncludeonlyList(char delim)
3509 for (inset_iterator it = inset_iterator_begin();
3510 it != inset_iterator_end(); ++it) {
3511 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3512 InsetInclude * insetinc =
3513 static_cast<InsetInclude *>(*it);
3514 if (insetinc->isInclude()
3515 && insetinc->isNoLoad()) {
3518 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3522 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3527 vector<string> const Buffer::getLabelList()
3529 /// if this is a child document and the parent is already loaded
3530 /// Use the parent's list instead [ale990407]
3531 if (!params.parentname.empty()
3532 && bufferlist.exists(params.parentname)) {
3533 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3535 return tmp->getLabelList();
3538 vector<string> label_list;
3539 for (inset_iterator it = inset_iterator_begin();
3540 it != inset_iterator_end(); ++it) {
3541 vector<string> const l = (*it)->getLabelList();
3542 label_list.insert(label_list.end(), l.begin(), l.end());
3548 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3550 vector<vector<TocItem> > l(4);
3551 LyXParagraph * par = paragraph;
3554 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3555 if (textclasslist.Style(params.textclass,
3556 par->GetLayout()).labeltype
3557 == LABEL_SENSITIVE) {
3561 tmp.str = par->String(this, false);
3562 switch (par->footnotekind) {
3563 case LyXParagraph::FIG:
3564 case LyXParagraph::WIDE_FIG:
3565 l[TOC_LOF].push_back(tmp);
3567 case LyXParagraph::TAB:
3568 case LyXParagraph::WIDE_TAB:
3569 l[TOC_LOT].push_back(tmp);
3571 case LyXParagraph::ALGORITHM:
3572 l[TOC_LOA].push_back(tmp);
3574 case LyXParagraph::FOOTNOTE:
3575 case LyXParagraph::MARGIN:
3579 } else if (!par->IsDummy()) {
3581 char const labeltype =
3582 textclasslist.Style(params.textclass,
3583 par->GetLayout()).labeltype;
3585 if (labeltype >= LABEL_COUNTER_CHAPTER
3586 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3587 // insert this into the table of contents
3592 textclasslist.TextClass(params.textclass).maxcounter());
3593 tmp.str = par->String(this, true);
3594 l[TOC_TOC].push_back(tmp);
3605 // This is also a buffer property (ale)
3606 vector<pair<string,string> > const Buffer::getBibkeyList()
3608 /// if this is a child document and the parent is already loaded
3609 /// Use the parent's list instead [ale990412]
3610 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3611 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3613 return tmp->getBibkeyList();
3616 vector<pair<string, string> > keys;
3617 LyXParagraph * par = paragraph;
3620 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3621 par->String(this, false)));
3625 // Might be either using bibtex or a child has bibliography
3627 for (inset_iterator it = inset_iterator_begin();
3628 it != inset_iterator_end(); ++it) {
3629 // Search for Bibtex or Include inset
3630 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3631 vector<pair<string,string> > tmp =
3632 static_cast<InsetBibtex*>(*it)->getKeys(this);
3633 keys.insert(keys.end(), tmp.begin(), tmp.end());
3634 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3635 vector<pair<string,string> > const tmp =
3636 static_cast<InsetInclude*>(*it)->getKeys();
3637 keys.insert(keys.end(), tmp.begin(), tmp.end());
3646 bool Buffer::isDepClean(string const & name) const
3648 DEPCLEAN * item = dep_clean;
3649 while (item && item->master != name)
3651 if (!item) return true;
3656 void Buffer::markDepClean(string const & name)
3659 dep_clean = new DEPCLEAN;
3660 dep_clean->clean = true;
3661 dep_clean->master = name;
3662 dep_clean->next = 0;
3664 DEPCLEAN * item = dep_clean;
3665 while (item && item->master != name)
3670 item = new DEPCLEAN;
3672 item->master = name;
3679 bool Buffer::Dispatch(string const & command)
3681 // Split command string into command and argument
3683 string line = frontStrip(command);
3684 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3686 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3690 bool Buffer::Dispatch(int action, string const & argument)
3692 bool dispatched = true;
3695 Exporter::Export(this, argument, false);
3705 void Buffer::resize()
3707 /// resize the BufferViews!
3713 void Buffer::resizeInsets(BufferView * bv)
3715 /// then remove all LyXText in text-insets
3716 LyXParagraph * par = paragraph;
3717 for(; par; par = par->next) {
3718 par->resizeInsetsLyXText(bv);
3722 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3725 LyXParagraph * par = paragraph;
3727 par->ChangeLanguage(params, from, to);
3733 bool Buffer::isMultiLingual()
3735 LyXParagraph * par = paragraph;
3737 if (par->isMultiLingual(params))
3745 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3746 LyXParagraph::size_type pos)
3749 it = par->InsetIterator(pos);
3750 if (it == par->inset_iterator_end()) {
3757 void Buffer::inset_iterator::SetParagraph()
3760 it = par->inset_iterator_begin();
3761 if (it != par->inset_iterator_end())
3766 // We maintain an invariant that whenever par = 0 then it = 0