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"
108 using std::istringstream;
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
113 extern LyXAction lyxaction;
116 static const float LYX_FORMAT = 2.17;
118 extern int tex_code_break_column;
121 Buffer::Buffer(string const & file, bool ronly)
123 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
125 filepath = OnlyPath(file);
134 if (read_only || (lyxrc.use_tempdir)) {
135 tmppath = CreateBufferTmpDir();
136 } else tmppath.erase();
142 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
143 // here the buffer should take care that it is
144 // saved properly, before it goes into the void.
146 // make sure that views using this buffer
151 if (!tmppath.empty()) {
152 DestroyBufferTmpDir(tmppath);
155 LyXParagraph * par = paragraph;
156 LyXParagraph * tmppar;
166 string const Buffer::getLatexName(bool no_path) const
169 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
172 return ChangeExtension(MakeLatexName(filename),
177 void Buffer::setReadonly(bool flag)
179 if (read_only != flag) {
182 users->owner()->getDialogs()->updateBufferDependent(false);
185 WarnReadonly(filename);
190 bool Buffer::saveParamsAsDefaults() // const
192 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
194 Buffer defaults = Buffer(fname);
196 // Use the current buffer's parameters as default
197 defaults.params = params;
199 // add an empty paragraph. Is this enough?
200 defaults.paragraph = new LyXParagraph;
202 return defaults.writeFile(defaults.filename, false);
206 /// Update window titles of all users
207 // Should work on a list
208 void Buffer::updateTitles() const
210 if (users) users->owner()->updateWindowTitle();
214 /// Reset autosave timer of all users
215 // Should work on a list
216 void Buffer::resetAutosaveTimers() const
218 if (users) users->owner()->resetAutosaveTimer();
222 void Buffer::setFileName(string const & newfile)
224 filename = MakeAbsPath(newfile);
225 filepath = OnlyPath(filename);
226 setReadonly(IsFileWriteable(filename) == 0);
231 // candidate for move to BufferView
232 // (at least some parts in the beginning of the func)
235 // changed to be public and have one parameter
236 // if par = 0 normal behavior
237 // else insert behavior
238 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
239 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
242 char depth = 0; // signed or unsigned?
244 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
245 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
247 bool the_end_read = false;
249 LyXParagraph * return_par = 0;
250 LyXFont font(LyXFont::ALL_INHERIT, params.language);
251 if (format < 2.16 && params.language->lang() == "hebrew")
252 font.setLanguage(default_language);
254 // If we are inserting, we cheat and get a token in advance
255 bool has_token = false;
259 par = new LyXParagraph;
261 users->text->BreakParagraph(users);
262 return_par = users->text->FirstParagraph();
265 // We don't want to adopt the parameters from the
266 // document we insert, so we skip until the text begins:
269 pretoken = lex.GetString();
270 if (pretoken == "\\layout") {
282 pretoken = lex.GetString();
285 if (pretoken.empty()) continue;
288 parseSingleLyXformat2Token(lex, par, return_par,
289 pretoken, pos, depth,
301 paragraph = return_par;
307 // We'll remove this later. (Lgb)
308 static string last_inset_read;
312 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
313 LyXParagraph *& return_par,
314 string const & token, int & pos,
315 char & depth, LyXFont & font
317 , LyXParagraph::footnote_flag & footnoteflag,
318 LyXParagraph::footnote_kind & footnotekind
322 bool the_end_read = false;
324 if (token[0] != '\\') {
325 for (string::const_iterator cit = token.begin();
326 cit != token.end(); ++cit) {
327 par->InsertChar(pos, (*cit), font);
330 } else if (token == "\\i") {
331 Inset * inset = new InsetLatexAccent;
332 inset->Read(this, lex);
333 par->InsertInset(pos, inset, font);
335 } else if (token == "\\layout") {
340 par = new LyXParagraph(par);
344 string const layoutname = lex.GetString();
345 pair<bool, LyXTextClass::LayoutList::size_type> pp
346 = textclasslist.NumberOfLayout(params.textclass,
349 par->layout = pp.second;
350 } else { // layout not found
351 // use default layout "Standard" (0)
354 // Test whether the layout is obsolete.
355 LyXLayout const & layout =
356 textclasslist.Style(params.textclass,
358 if (!layout.obsoleted_by().empty())
360 textclasslist.NumberOfLayout(params.textclass,
361 layout.obsoleted_by()).second;
363 par->footnoteflag = footnoteflag;
364 par->footnotekind = footnotekind;
367 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
368 if (format < 2.16 && params.language->lang() == "hebrew")
369 font.setLanguage(default_language);
371 } else if (token == "\\end_float") {
376 par = new LyXParagraph(par);
378 footnotekind = LyXParagraph::FOOTNOTE;
379 footnoteflag = LyXParagraph::NO_FOOTNOTE;
382 par->layout = LYX_DUMMY_LAYOUT;
383 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
384 if (format < 2.16 && params.language->lang() == "hebrew")
385 font.setLanguage(default_language);
386 } else if (token == "\\begin_float") {
387 int tmpret = lex.FindToken(string_footnotekinds);
388 if (tmpret == -1) ++tmpret;
389 if (tmpret != LYX_LAYOUT_DEFAULT)
390 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
391 if (footnotekind == LyXParagraph::FOOTNOTE
392 || footnotekind == LyXParagraph::MARGIN)
393 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
395 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
397 } else if (token == "\\begin_float") {
398 // This is the compability reader, unfinished but tested.
401 string const tmptok = lex.GetString();
402 //lyxerr << "old float: " << tmptok << endl;
407 if (tmptok == "footnote") {
408 inset = new InsetFoot;
409 } else if (tmptok == "margin") {
410 inset = new InsetMarginal;
411 } else if (tmptok == "fig") {
412 inset = new InsetFloat("figure");
413 old_float += "placement htbp\n";
414 } else if (tmptok == "tab") {
415 inset = new InsetFloat("table");
416 old_float += "placement htbp\n";
417 } else if (tmptok == "alg") {
418 inset = new InsetFloat("algorithm");
419 old_float += "placement htbp\n";
420 } else if (tmptok == "wide-fig") {
421 InsetFloat * tmp = new InsetFloat("figure");
424 old_float += "placement htbp\n";
425 } else if (tmptok == "wide-tab") {
426 InsetFloat * tmp = new InsetFloat("table");
429 old_float += "placement htbp\n";
432 if (!inset) return false; // no end read yet
434 old_float += "collapsed true\n";
436 // Here we need to check for \end_deeper and handle that
437 // before we do the footnote parsing.
438 // This _is_ a hack! (Lgb)
441 string const tmp = lex.GetString();
442 if (tmp == "\\end_deeper") {
443 lyxerr << "\\end_deeper caught!" << endl;
445 lex.printError("\\end_deeper: "
446 "depth is already null");
457 old_float += lex.getLongString("\\end_float");
458 old_float += "\n\\end_inset\n";
459 //lyxerr << "float body: " << old_float << endl;
461 istringstream istr(old_float);
464 nylex.setStream(istr);
466 inset->Read(this, nylex);
467 par->InsertInset(pos, inset, font);
470 } else if (token == "\\begin_deeper") {
472 } else if (token == "\\end_deeper") {
474 lex.printError("\\end_deeper: "
475 "depth is already null");
479 } else if (token == "\\begin_preamble") {
480 params.readPreamble(lex);
481 } else if (token == "\\textclass") {
483 pair<bool, LyXTextClassList::size_type> pp =
484 textclasslist.NumberOfClass(lex.GetString());
486 params.textclass = pp.second;
488 lex.printError("Unknown textclass `$$Token'");
489 params.textclass = 0;
491 if (!textclasslist.Load(params.textclass)) {
492 // if the textclass wasn't loaded properly
493 // we need to either substitute another
494 // or stop loading the file.
495 // I can substitute but I don't see how I can
496 // stop loading... ideas?? ARRae980418
497 WriteAlert(_("Textclass Loading Error!"),
498 string(_("Can't load textclass ")) +
499 textclasslist.NameOfClass(params.textclass),
500 _("-- substituting default"));
501 params.textclass = 0;
503 } else if (token == "\\options") {
505 params.options = lex.GetString();
506 } else if (token == "\\language") {
507 params.readLanguage(lex);
508 } else if (token == "\\fontencoding") {
510 } else if (token == "\\inputencoding") {
512 params.inputenc = lex.GetString();
513 } else if (token == "\\graphics") {
514 params.readGraphicsDriver(lex);
515 } else if (token == "\\fontscheme") {
517 params.fonts = lex.GetString();
518 } else if (token == "\\noindent") {
519 par->noindent = true;
520 } else if (token == "\\fill_top") {
521 par->added_space_top = VSpace(VSpace::VFILL);
522 } else if (token == "\\fill_bottom") {
523 par->added_space_bottom = VSpace(VSpace::VFILL);
524 } else if (token == "\\line_top") {
525 par->line_top = true;
526 } else if (token == "\\line_bottom") {
527 par->line_bottom = true;
528 } else if (token == "\\pagebreak_top") {
529 par->pagebreak_top = true;
530 } else if (token == "\\pagebreak_bottom") {
531 par->pagebreak_bottom = true;
532 } else if (token == "\\start_of_appendix") {
533 par->start_of_appendix = true;
534 } else if (token == "\\paragraph_separation") {
535 int tmpret = lex.FindToken(string_paragraph_separation);
536 if (tmpret == -1) ++tmpret;
537 if (tmpret != LYX_LAYOUT_DEFAULT)
538 params.paragraph_separation =
539 static_cast<BufferParams::PARSEP>(tmpret);
540 } else if (token == "\\defskip") {
542 params.defskip = VSpace(lex.GetString());
543 } else if (token == "\\epsfig") { // obsolete
544 // Indeed it is obsolete, but we HAVE to be backwards
545 // compatible until 0.14, because otherwise all figures
546 // in existing documents are irretrivably lost. (Asger)
547 params.readGraphicsDriver(lex);
548 } else if (token == "\\quotes_language") {
549 int tmpret = lex.FindToken(string_quotes_language);
550 if (tmpret == -1) ++tmpret;
551 if (tmpret != LYX_LAYOUT_DEFAULT) {
552 InsetQuotes::quote_language tmpl =
553 InsetQuotes::EnglishQ;
556 tmpl = InsetQuotes::EnglishQ;
559 tmpl = InsetQuotes::SwedishQ;
562 tmpl = InsetQuotes::GermanQ;
565 tmpl = InsetQuotes::PolishQ;
568 tmpl = InsetQuotes::FrenchQ;
571 tmpl = InsetQuotes::DanishQ;
574 params.quotes_language = tmpl;
576 } else if (token == "\\quotes_times") {
578 switch(lex.GetInteger()) {
580 params.quotes_times = InsetQuotes::SingleQ;
583 params.quotes_times = InsetQuotes::DoubleQ;
586 } else if (token == "\\papersize") {
587 int tmpret = lex.FindToken(string_papersize);
591 params.papersize2 = tmpret;
592 } else if (token == "\\paperpackage") {
593 int tmpret = lex.FindToken(string_paperpackages);
596 params.paperpackage = BufferParams::PACKAGE_NONE;
598 params.paperpackage = tmpret;
599 } else if (token == "\\use_geometry") {
601 params.use_geometry = lex.GetInteger();
602 } else if (token == "\\use_amsmath") {
604 params.use_amsmath = lex.GetInteger();
605 } else if (token == "\\paperorientation") {
606 int tmpret = lex.FindToken(string_orientation);
607 if (tmpret == -1) ++tmpret;
608 if (tmpret != LYX_LAYOUT_DEFAULT)
609 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
610 } else if (token == "\\paperwidth") {
612 params.paperwidth = lex.GetString();
613 } else if (token == "\\paperheight") {
615 params.paperheight = lex.GetString();
616 } else if (token == "\\leftmargin") {
618 params.leftmargin = lex.GetString();
619 } else if (token == "\\topmargin") {
621 params.topmargin = lex.GetString();
622 } else if (token == "\\rightmargin") {
624 params.rightmargin = lex.GetString();
625 } else if (token == "\\bottommargin") {
627 params.bottommargin = lex.GetString();
628 } else if (token == "\\headheight") {
630 params.headheight = lex.GetString();
631 } else if (token == "\\headsep") {
633 params.headsep = lex.GetString();
634 } else if (token == "\\footskip") {
636 params.footskip = lex.GetString();
637 } else if (token == "\\paperfontsize") {
639 params.fontsize = strip(lex.GetString());
640 } else if (token == "\\papercolumns") {
642 params.columns = lex.GetInteger();
643 } else if (token == "\\papersides") {
645 switch(lex.GetInteger()) {
647 case 1: params.sides = LyXTextClass::OneSide; break;
648 case 2: params.sides = LyXTextClass::TwoSides; break;
650 } else if (token == "\\paperpagestyle") {
652 params.pagestyle = strip(lex.GetString());
653 } else if (token == "\\bullet") {
655 int const index = lex.GetInteger();
657 int temp_int = lex.GetInteger();
658 params.user_defined_bullets[index].setFont(temp_int);
659 params.temp_bullets[index].setFont(temp_int);
661 temp_int = lex.GetInteger();
662 params.user_defined_bullets[index].setCharacter(temp_int);
663 params.temp_bullets[index].setCharacter(temp_int);
665 temp_int = lex.GetInteger();
666 params.user_defined_bullets[index].setSize(temp_int);
667 params.temp_bullets[index].setSize(temp_int);
669 string const temp_str = lex.GetString();
670 if (temp_str != "\\end_bullet") {
671 // this element isn't really necessary for
672 // parsing but is easier for humans
673 // to understand bullets. Put it back and
674 // set a debug message?
675 lex.printError("\\end_bullet expected, got" + temp_str);
676 //how can I put it back?
678 } else if (token == "\\bulletLaTeX") {
680 int const index = lex.GetInteger();
682 string temp_str = lex.GetString();
684 while (temp_str != "\\end_bullet") {
685 // this loop structure is needed when user
686 // enters an empty string since the first
687 // thing returned will be the \\end_bullet
689 // if the LaTeX entry has spaces. Each element
690 // therefore needs to be read in turn
693 temp_str = lex.GetString();
695 params.user_defined_bullets[index].setText(sum_str);
696 params.temp_bullets[index].setText(sum_str);
697 } else if (token == "\\secnumdepth") {
699 params.secnumdepth = lex.GetInteger();
700 } else if (token == "\\tocdepth") {
702 params.tocdepth = lex.GetInteger();
703 } else if (token == "\\spacing") {
705 string const tmp = strip(lex.GetString());
706 Spacing::Space tmp_space = Spacing::Default;
708 if (tmp == "single") {
709 tmp_space = Spacing::Single;
710 } else if (tmp == "onehalf") {
711 tmp_space = Spacing::Onehalf;
712 } else if (tmp == "double") {
713 tmp_space = Spacing::Double;
714 } else if (tmp == "other") {
716 tmp_space = Spacing::Other;
717 tmp_val = lex.GetFloat();
719 lex.printError("Unknown spacing token: '$$Token'");
721 // Small hack so that files written with klyx will be
724 par->spacing.set(tmp_space, tmp_val);
726 params.spacing.set(tmp_space, tmp_val);
728 } else if (token == "\\paragraph_spacing") {
730 string const tmp = strip(lex.GetString());
731 if (tmp == "single") {
732 par->spacing.set(Spacing::Single);
733 } else if (tmp == "onehalf") {
734 par->spacing.set(Spacing::Onehalf);
735 } else if (tmp == "double") {
736 par->spacing.set(Spacing::Double);
737 } else if (tmp == "other") {
739 par->spacing.set(Spacing::Other,
742 lex.printError("Unknown spacing token: '$$Token'");
744 } else if (token == "\\float_placement") {
746 params.float_placement = lex.GetString();
747 } else if (token == "\\family") {
749 font.setLyXFamily(lex.GetString());
750 } else if (token == "\\series") {
752 font.setLyXSeries(lex.GetString());
753 } else if (token == "\\shape") {
755 font.setLyXShape(lex.GetString());
756 } else if (token == "\\size") {
758 font.setLyXSize(lex.GetString());
759 } else if (token == "\\latex") {
761 string const tok = lex.GetString();
762 // This is dirty, but gone with LyX3. (Asger)
763 if (tok == "no_latex")
764 font.setLatex(LyXFont::OFF);
765 else if (tok == "latex")
766 font.setLatex(LyXFont::ON);
767 else if (tok == "default")
768 font.setLatex(LyXFont::INHERIT);
770 lex.printError("Unknown LaTeX font flag "
772 } else if (token == "\\lang") {
774 string const tok = lex.GetString();
775 Language const * lang = languages.getLanguage(tok);
777 font.setLanguage(lang);
779 font.setLanguage(params.language);
780 lex.printError("Unknown language `$$Token'");
782 } else if (token == "\\numeric") {
784 font.setNumber(font.setLyXMisc(lex.GetString()));
785 } else if (token == "\\emph") {
787 font.setEmph(font.setLyXMisc(lex.GetString()));
788 } else if (token == "\\bar") {
790 string const tok = lex.GetString();
791 // This is dirty, but gone with LyX3. (Asger)
793 font.setUnderbar(LyXFont::ON);
794 else if (tok == "no")
795 font.setUnderbar(LyXFont::OFF);
796 else if (tok == "default")
797 font.setUnderbar(LyXFont::INHERIT);
799 lex.printError("Unknown bar font flag "
801 } else if (token == "\\noun") {
803 font.setNoun(font.setLyXMisc(lex.GetString()));
804 } else if (token == "\\color") {
806 font.setLyXColor(lex.GetString());
807 } else if (token == "\\align") {
808 int tmpret = lex.FindToken(string_align);
809 if (tmpret == -1) ++tmpret;
810 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
812 for (; tmpret > 0; --tmpret)
813 tmpret2 = tmpret2 * 2;
814 par->align = LyXAlignment(tmpret2);
816 } else if (token == "\\added_space_top") {
818 par->added_space_top = VSpace(lex.GetString());
819 } else if (token == "\\added_space_bottom") {
821 par->added_space_bottom = VSpace(lex.GetString());
822 } else if (token == "\\pextra_type") {
824 par->pextra_type = lex.GetInteger();
825 } else if (token == "\\pextra_width") {
827 par->pextra_width = lex.GetString();
828 } else if (token == "\\pextra_widthp") {
830 par->pextra_widthp = lex.GetString();
831 } else if (token == "\\pextra_alignment") {
833 par->pextra_alignment = lex.GetInteger();
834 } else if (token == "\\pextra_hfill") {
836 par->pextra_hfill = lex.GetInteger();
837 } else if (token == "\\pextra_start_minipage") {
839 par->pextra_start_minipage = lex.GetInteger();
840 } else if (token == "\\labelwidthstring") {
842 par->labelwidthstring = lex.GetString();
843 // do not delete this token, it is still needed!
844 } else if (token == "\\end_inset") {
845 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
846 << "Last inset read was: " << last_inset_read
848 // Simply ignore this. The insets do not have
850 // But insets should read it, it is a part of
851 // the inset isn't it? Lgb.
852 } else if (token == "\\begin_inset") {
853 readInset(lex, par, pos, font);
854 } else if (token == "\\SpecialChar") {
855 LyXLayout const & layout =
856 textclasslist.Style(params.textclass,
859 // Insets don't make sense in a free-spacing context! ---Kayvan
860 if (layout.free_spacing) {
863 string next_token = lex.GetString();
864 if (next_token == "\\-") {
865 par->InsertChar(pos, '-', font);
866 } else if (next_token == "\\protected_separator"
867 || next_token == "~") {
868 par->InsertChar(pos, ' ', font);
870 lex.printError("Token `$$Token' "
872 "paragraph layout!");
877 Inset * inset = new InsetSpecialChar;
878 inset->Read(this, lex);
879 par->InsertInset(pos, inset, font);
882 } else if (token == "\\newline") {
883 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
885 } else if (token == "\\LyXTable") {
886 Inset * inset = new InsetTabular(*this);
887 inset->Read(this, lex);
888 par->InsertInset(pos, inset, font);
890 } else if (token == "\\hfill") {
891 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
893 } else if (token == "\\protected_separator") { // obsolete
894 // This is a backward compability thingie. (Lgb)
895 // Remove it later some time...introduced with fileformat
897 LyXLayout const & layout =
898 textclasslist.Style(params.textclass,
901 if (layout.free_spacing) {
902 par->InsertChar(pos, ' ', font);
904 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
905 par->InsertInset(pos, inset, font);
908 } else if (token == "\\bibitem") { // ale970302
910 InsetCommandParams p( "bibitem" );
911 par->bibkey = new InsetBibKey(p);
913 par->bibkey->Read(this, lex);
914 } else if (token == "\\backslash") {
915 par->InsertChar(pos, '\\', font);
917 } else if (token == "\\the_end") {
920 // This should be insurance for the future: (Asger)
921 lex.printError("Unknown token `$$Token'. "
922 "Inserting as text.");
923 string::const_iterator cit = token.begin();
924 string::const_iterator end = token.end();
925 for(; cit != end; ++cit) {
926 par->InsertChar(pos, (*cit), font);
934 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
935 int & pos, LyXFont & font)
938 if (lex.GetString() != "\\begin_inset") {
939 lyxerr << "Buffer::readInset: Consistency check failed."
946 string const tmptok = lex.GetString();
947 last_inset_read = tmptok;
949 // test the different insets
950 if (tmptok == "LatexCommand") {
951 InsetCommandParams inscmd;
954 if (inscmd.getCmdName() == "cite") {
955 inset = new InsetCitation(inscmd);
956 } else if (inscmd.getCmdName() == "bibitem") {
957 lex.printError("Wrong place for bibitem");
958 inset = new InsetBibKey(inscmd);
959 } else if (inscmd.getCmdName() == "BibTeX") {
960 inset = new InsetBibtex(inscmd);
961 } else if (inscmd.getCmdName() == "index") {
962 inset = new InsetIndex(inscmd);
963 } else if (inscmd.getCmdName() == "include") {
964 inset = new InsetInclude(inscmd, *this);
965 } else if (inscmd.getCmdName() == "label") {
966 inset = new InsetLabel(inscmd);
967 } else if (inscmd.getCmdName() == "url"
968 || inscmd.getCmdName() == "htmlurl") {
969 inset = new InsetUrl(inscmd);
970 } else if (inscmd.getCmdName() == "ref"
971 || inscmd.getCmdName() == "pageref"
972 || inscmd.getCmdName() == "vref"
973 || inscmd.getCmdName() == "vpageref"
974 || inscmd.getCmdName() == "prettyref") {
975 if (!inscmd.getOptions().empty()
976 || !inscmd.getContents().empty()) {
977 inset = new InsetRef(inscmd, *this);
979 } else if (inscmd.getCmdName() == "tableofcontents"
980 || inscmd.getCmdName() == "listofalgorithms"
981 || inscmd.getCmdName() == "listoffigures"
982 || inscmd.getCmdName() == "listoftables") {
983 inset = new InsetTOC(inscmd);
984 } else if (inscmd.getCmdName() == "printindex") {
985 inset = new InsetPrintIndex(inscmd);
986 } else if (inscmd.getCmdName() == "lyxparent") {
987 inset = new InsetParent(inscmd, *this);
990 if (tmptok == "Quotes") {
991 inset = new InsetQuotes;
992 } else if (tmptok == "External") {
993 inset = new InsetExternal;
994 } else if (tmptok == "FormulaMacro") {
995 inset = new InsetFormulaMacro;
996 } else if (tmptok == "Formula") {
997 inset = new InsetFormula;
998 } else if (tmptok == "Figure") {
999 inset = new InsetFig(100, 100, *this);
1000 } else if (tmptok == "Info") {
1001 inset = new InsetInfo;
1002 } else if (tmptok == "Include") {
1003 InsetCommandParams p( "Include" );
1004 inset = new InsetInclude(p, *this);
1005 } else if (tmptok == "ERT") {
1006 inset = new InsetERT;
1007 } else if (tmptok == "Tabular") {
1008 inset = new InsetTabular(*this);
1009 } else if (tmptok == "Text") {
1010 inset = new InsetText;
1011 } else if (tmptok == "Foot") {
1012 inset = new InsetFoot;
1013 } else if (tmptok == "Marginal") {
1014 inset = new InsetMarginal;
1015 } else if (tmptok == "Minipage") {
1016 inset = new InsetMinipage;
1017 } else if (tmptok == "Float") {
1019 string tmptok = lex.GetString();
1020 inset = new InsetFloat(tmptok);
1021 } else if (tmptok == "List") {
1022 inset = new InsetList;
1023 } else if (tmptok == "Theorem") {
1024 inset = new InsetList;
1025 } else if (tmptok == "Caption") {
1026 inset = new InsetCaption;
1027 } else if (tmptok == "GRAPHICS") {
1028 inset = new InsetGraphics;
1031 if (inset) inset->Read(this, lex);
1035 par->InsertInset(pos, inset, font);
1041 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1045 string const token(lex.GetString());
1046 if (token == "\\lyxformat") { // the first token _must_ be...
1048 format = lex.GetFloat();
1050 if (LYX_FORMAT - format > 0.05) {
1051 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1052 LYX_FORMAT, format) << endl;
1054 if (format - LYX_FORMAT > 0.05) {
1055 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1056 LYX_FORMAT, format) << endl;
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;
1244 // how to check if close went ok?
1245 // Following is an attempt... (BE 20001011)
1247 // good() returns false if any error occured, including some
1248 // formatting error.
1249 // bad() returns true if something bad happened in the buffer,
1250 // which should include file system full errors.
1257 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1259 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1270 void Buffer::writeFileAscii(string const & fname, int linelen)
1274 char footnoteflag = 0;
1277 LyXParagraph::size_type i;
1280 int ltype_depth = 0;
1283 int currlinelen = 0;
1285 bool ref_printed = false;
1287 ofstream ofs(fname.c_str());
1289 WriteFSAlert(_("Error: Cannot write file:"), fname);
1293 string const fname1 = TmpFileName();
1294 LyXParagraph * par = paragraph;
1300 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1304 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1309 /* begins a footnote environment ? */
1310 if (footnoteflag != par->footnoteflag) {
1311 footnoteflag = par->footnoteflag;
1313 j = strlen(string_footnotekinds[par->footnotekind])+4;
1314 if (currlinelen + j > linelen)
1317 << string_footnotekinds[par->footnotekind] << "] ";
1323 /* begins or ends a deeper area ?*/
1324 if (depth != par->depth) {
1325 if (par->depth > depth) {
1326 while (par->depth > depth) {
1331 while (par->depth < depth) {
1337 /* First write the layout */
1338 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1339 if (tmp == "Itemize") {
1341 ltype_depth = depth+1;
1342 } else if (tmp == "Enumerate") {
1344 ltype_depth = depth+1;
1345 } else if (contains(tmp, "ection")) {
1347 ltype_depth = depth+1;
1348 } else if (contains(tmp, "aragraph")) {
1350 ltype_depth = depth+1;
1351 } else if (tmp == "Description") {
1353 ltype_depth = depth+1;
1354 } else if (tmp == "Abstract") {
1357 } else if (tmp == "Bibliography") {
1365 /* maybe some vertical spaces */
1367 /* the labelwidthstring used in lists */
1371 /* some pagebreaks? */
1375 /* what about the alignment */
1378 /* dummy layout, that means a footnote ended */
1379 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1383 lyxerr << "Should this ever happen?" << endl;
1388 LyXFont(LyXFont::ALL_INHERIT, params.language);
1390 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1391 if (!i && !footnoteflag && !noparbreak){
1393 for(j = 0; j < depth; ++j)
1395 currlinelen = depth * 2;
1397 case 0: /* Standard */
1398 case 4: /* (Sub)Paragraph */
1399 case 5: /* Description */
1401 case 6: /* Abstract */
1402 ofs << "Abstract\n\n";
1404 case 7: /* Bibliography */
1406 ofs << "References\n\n";
1411 ofs << par->labelstring << " ";
1414 if (ltype_depth > depth) {
1415 for(j = ltype_depth - 1; j > depth; --j)
1417 currlinelen += (ltype_depth-depth)*2;
1420 LyXFont font2 = par->GetFontSettings(params, i);
1421 if (font1.latex() != font2.latex()) {
1422 if (font2.latex() == LyXFont::OFF)
1429 c = par->GetChar(i);
1433 case LyXParagraph::META_INSET:
1434 if ((inset = par->GetInset(i))) {
1436 inset->Ascii(this, ofs);
1437 currlinelen += (ofs.tellp() - fpos);
1438 actpos += (ofs.tellp() - fpos) - 1;
1441 case LyXParagraph::META_NEWLINE:
1443 for(j = 0; j < depth; ++j)
1445 currlinelen = depth * 2;
1446 if (ltype_depth > depth) {
1447 for(j = ltype_depth;
1450 currlinelen += (ltype_depth - depth) * 2;
1453 case LyXParagraph::META_HFILL:
1460 if (currlinelen > linelen - 10
1461 && c == ' ' && i + 2 < par->size()) {
1463 for(j = 0; j < depth; ++j)
1465 currlinelen = depth * 2;
1466 if (ltype_depth > depth) {
1467 for(j = ltype_depth;
1470 currlinelen += (ltype_depth-depth)*2;
1472 } else if (c != '\0')
1475 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1485 //----------------------------------------------------------------------------
1487 //----------------------------------------------------------------------------
1488 string const Buffer::asciiParagraph(LyXParagraph const * par,
1489 unsigned int linelen) const
1491 ostringstream buffer;
1494 Inset const * inset;
1496 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1499 int ltype_depth = 0;
1500 unsigned int currlinelen = 0;
1501 bool ref_printed = false;
1507 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1511 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1515 /* begins a footnote environment ? */
1516 if (footnoteflag != par->footnoteflag) {
1517 footnoteflag = par->footnoteflag;
1519 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1520 if ((linelen > 0) &&
1521 ((currlinelen + j) > linelen)) {
1526 << string_footnotekinds[par->footnotekind]
1532 /* begins or ends a deeper area ?*/
1533 if (depth != par->depth) {
1534 if (par->depth > depth) {
1535 while (par->depth > depth) {
1540 while (par->depth < depth) {
1546 /* First write the layout */
1547 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1548 if (tmp == "Itemize") {
1550 ltype_depth = depth+1;
1551 } else if (tmp == "Enumerate") {
1553 ltype_depth = depth+1;
1554 } else if (strstr(tmp.c_str(), "ection")) {
1556 ltype_depth = depth+1;
1557 } else if (strstr(tmp.c_str(), "aragraph")) {
1559 ltype_depth = depth+1;
1560 } else if (tmp == "Description") {
1562 ltype_depth = depth+1;
1563 } else if (tmp == "Abstract") {
1566 } else if (tmp == "Bibliography") {
1574 /* maybe some vertical spaces */
1576 /* the labelwidthstring used in lists */
1580 /* some pagebreaks? */
1584 /* what about the alignment */
1587 /* dummy layout, that means a footnote ended */
1588 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1592 lyxerr << "Should this ever happen?" << endl;
1596 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1597 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1598 if (!i && !footnoteflag && !noparbreak){
1601 for(char j = 0; j < depth; ++j)
1603 currlinelen = depth * 2;
1605 case 0: /* Standard */
1606 case 4: /* (Sub)Paragraph */
1607 case 5: /* Description */
1609 case 6: /* Abstract */
1611 buffer << "Abstract\n\n";
1613 buffer << "Abstract: ";
1615 case 7: /* Bibliography */
1618 buffer << "References\n\n";
1620 buffer << "References: ";
1625 buffer << par->labelstring << " ";
1628 if (ltype_depth > depth) {
1629 for(char j = ltype_depth - 1; j > depth; --j)
1631 currlinelen += (ltype_depth-depth)*2;
1634 font2 = par->GetFontSettings(params, i);
1635 if (font1.latex() != font2.latex()) {
1636 if (font2.latex() == LyXFont::OFF)
1643 c = par->GetChar(i);
1647 case LyXParagraph::META_INSET:
1648 if ((inset = par->GetInset(i))) {
1649 if (!inset->Ascii(this, buffer)) {
1651 string s = rsplit(buffer.str(),
1653 currlinelen += s.length();
1655 // to be sure it breaks paragraph
1656 currlinelen += linelen;
1660 case LyXParagraph::META_NEWLINE:
1663 for(char j = 0; j < depth; ++j)
1666 currlinelen = depth * 2;
1667 if (ltype_depth > depth) {
1668 for(char j = ltype_depth;
1671 currlinelen += (ltype_depth - depth) * 2;
1674 case LyXParagraph::META_HFILL:
1681 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1682 (c == ' ') && ((i + 2) < par->size()))
1685 for(char j = 0; j < depth; ++j)
1687 currlinelen = depth * 2;
1688 if (ltype_depth > depth) {
1689 for(char j = ltype_depth;
1692 currlinelen += (ltype_depth-depth)*2;
1694 } else if (c != '\0')
1697 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1702 return buffer.str();
1706 void Buffer::writeFileAscii(string const & fname, int linelen)
1708 ofstream ofs(fname.c_str());
1710 WriteFSAlert(_("Error: Cannot write file:"), fname);
1713 writeFileAscii(ofs, linelen);
1717 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1719 LyXParagraph * par = paragraph;
1721 ofs << asciiParagraph(par, linelen);
1728 void Buffer::makeLaTeXFile(string const & fname,
1729 string const & original_path,
1730 bool nice, bool only_body)
1732 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1734 niceFile = nice; // this will be used by Insetincludes.
1736 tex_code_break_column = lyxrc.ascii_linelen;
1738 LyXTextClass const & tclass =
1739 textclasslist.TextClass(params.textclass);
1741 ofstream ofs(fname.c_str());
1743 WriteFSAlert(_("Error: Cannot open file: "), fname);
1747 // validate the buffer.
1748 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1749 LaTeXFeatures features(params, tclass.numLayouts());
1751 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1754 // The starting paragraph of the coming rows is the
1755 // first paragraph of the document. (Asger)
1756 texrow.start(paragraph, 0);
1758 if (!only_body && nice) {
1759 ofs << "%% " LYX_DOCVERSION " created this file. "
1760 "For more info, see http://www.lyx.org/.\n"
1761 "%% Do not edit unless you really know what "
1766 lyxerr.debug() << "lyx header finished" << endl;
1767 // There are a few differences between nice LaTeX and usual files:
1768 // usual is \batchmode and has a
1769 // special input@path to allow the including of figures
1770 // with either \input or \includegraphics (what figinsets do).
1771 // batchmode is not set if there is a tex_code_break_column.
1772 // In this case somebody is interested in the generated LaTeX,
1773 // so this is OK. input@path is set when the actual parameter
1774 // original_path is set. This is done for usual tex-file, but not
1775 // for nice-latex-file. (Matthias 250696)
1778 // code for usual, NOT nice-latex-file
1779 ofs << "\\batchmode\n"; // changed
1780 // from \nonstopmode
1783 if (!original_path.empty()) {
1784 ofs << "\\makeatletter\n"
1785 << "\\def\\input@path{{"
1786 << original_path << "/}}\n"
1787 << "\\makeatother\n";
1793 ofs << "\\documentclass";
1795 string options; // the document class options.
1797 if (tokenPos(tclass.opt_fontsize(),
1798 '|', params.fontsize) >= 0) {
1799 // only write if existing in list (and not default)
1800 options += params.fontsize;
1805 if (!params.use_geometry &&
1806 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1807 switch (params.papersize) {
1808 case BufferParams::PAPER_A4PAPER:
1809 options += "a4paper,";
1811 case BufferParams::PAPER_USLETTER:
1812 options += "letterpaper,";
1814 case BufferParams::PAPER_A5PAPER:
1815 options += "a5paper,";
1817 case BufferParams::PAPER_B5PAPER:
1818 options += "b5paper,";
1820 case BufferParams::PAPER_EXECUTIVEPAPER:
1821 options += "executivepaper,";
1823 case BufferParams::PAPER_LEGALPAPER:
1824 options += "legalpaper,";
1830 if (params.sides != tclass.sides()) {
1831 switch (params.sides) {
1832 case LyXTextClass::OneSide:
1833 options += "oneside,";
1835 case LyXTextClass::TwoSides:
1836 options += "twoside,";
1843 if (params.columns != tclass.columns()) {
1844 if (params.columns == 2)
1845 options += "twocolumn,";
1847 options += "onecolumn,";
1850 if (!params.use_geometry
1851 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1852 options += "landscape,";
1854 // language should be a parameter to \documentclass
1855 bool use_babel = false;
1856 if (params.language->babel() == "hebrew") // This seems necessary
1857 features.UsedLanguages.insert(default_language);
1858 #ifdef DO_USE_DEFAULT_LANGUAGE
1859 if (params.language->lang() != "default" ||
1860 !features.UsedLanguages.empty() ) {
1863 for (LaTeXFeatures::LanguageList::const_iterator cit =
1864 features.UsedLanguages.begin();
1865 cit != features.UsedLanguages.end(); ++cit)
1866 options += (*cit)->babel() + ",";
1867 options += params.language->babel() + ',';
1868 #ifdef DO_USE_DEFAULT_LANGUAGE
1872 // the user-defined options
1873 if (!params.options.empty()) {
1874 options += params.options + ',';
1877 if (!options.empty()){
1878 options = strip(options, ',');
1879 ofs << '[' << options << ']';
1883 << textclasslist.LatexnameOfClass(params.textclass)
1886 // end of \documentclass defs
1888 // font selection must be done before loading fontenc.sty
1889 if (params.fonts != "default") {
1890 ofs << "\\usepackage{" << params.fonts << "}\n";
1893 // this one is not per buffer
1894 if (lyxrc.fontenc != "default") {
1895 ofs << "\\usepackage[" << lyxrc.fontenc
1900 if (params.inputenc == "auto") {
1901 string const doc_encoding =
1902 params.language->encoding()->LatexName();
1904 // Create a list with all the input encodings used
1906 set<string> encodings;
1907 for (LaTeXFeatures::LanguageList::const_iterator it =
1908 features.UsedLanguages.begin();
1909 it != features.UsedLanguages.end(); ++it)
1910 if ((*it)->encoding()->LatexName() != doc_encoding)
1911 encodings.insert((*it)->encoding()->LatexName());
1913 ofs << "\\usepackage[";
1914 std::copy(encodings.begin(), encodings.end(),
1915 std::ostream_iterator<string>(ofs, ","));
1916 ofs << doc_encoding << "]{inputenc}\n";
1918 } else if (params.inputenc != "default") {
1919 ofs << "\\usepackage[" << params.inputenc
1924 // At the very beginning the text parameters.
1925 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1926 switch (params.paperpackage) {
1927 case BufferParams::PACKAGE_A4:
1928 ofs << "\\usepackage{a4}\n";
1931 case BufferParams::PACKAGE_A4WIDE:
1932 ofs << "\\usepackage{a4wide}\n";
1935 case BufferParams::PACKAGE_WIDEMARGINSA4:
1936 ofs << "\\usepackage[widemargins]{a4}\n";
1941 if (params.use_geometry) {
1942 ofs << "\\usepackage{geometry}\n";
1944 ofs << "\\geometry{verbose";
1945 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1946 ofs << ",landscape";
1947 switch (params.papersize2) {
1948 case BufferParams::VM_PAPER_CUSTOM:
1949 if (!params.paperwidth.empty())
1950 ofs << ",paperwidth="
1951 << params.paperwidth;
1952 if (!params.paperheight.empty())
1953 ofs << ",paperheight="
1954 << params.paperheight;
1956 case BufferParams::VM_PAPER_USLETTER:
1957 ofs << ",letterpaper";
1959 case BufferParams::VM_PAPER_USLEGAL:
1960 ofs << ",legalpaper";
1962 case BufferParams::VM_PAPER_USEXECUTIVE:
1963 ofs << ",executivepaper";
1965 case BufferParams::VM_PAPER_A3:
1968 case BufferParams::VM_PAPER_A4:
1971 case BufferParams::VM_PAPER_A5:
1974 case BufferParams::VM_PAPER_B3:
1977 case BufferParams::VM_PAPER_B4:
1980 case BufferParams::VM_PAPER_B5:
1984 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1985 switch (lyxrc.default_papersize) {
1986 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1987 case BufferParams::PAPER_USLETTER:
1988 ofs << ",letterpaper";
1990 case BufferParams::PAPER_LEGALPAPER:
1991 ofs << ",legalpaper";
1993 case BufferParams::PAPER_EXECUTIVEPAPER:
1994 ofs << ",executivepaper";
1996 case BufferParams::PAPER_A3PAPER:
1999 case BufferParams::PAPER_A4PAPER:
2002 case BufferParams::PAPER_A5PAPER:
2005 case BufferParams::PAPER_B5PAPER:
2010 if (!params.topmargin.empty())
2011 ofs << ",tmargin=" << params.topmargin;
2012 if (!params.bottommargin.empty())
2013 ofs << ",bmargin=" << params.bottommargin;
2014 if (!params.leftmargin.empty())
2015 ofs << ",lmargin=" << params.leftmargin;
2016 if (!params.rightmargin.empty())
2017 ofs << ",rmargin=" << params.rightmargin;
2018 if (!params.headheight.empty())
2019 ofs << ",headheight=" << params.headheight;
2020 if (!params.headsep.empty())
2021 ofs << ",headsep=" << params.headsep;
2022 if (!params.footskip.empty())
2023 ofs << ",footskip=" << params.footskip;
2027 if (params.use_amsmath
2028 && !tclass.provides(LyXTextClass::amsmath)) {
2029 ofs << "\\usepackage{amsmath}\n";
2033 if (tokenPos(tclass.opt_pagestyle(),
2034 '|', params.pagestyle) >= 0) {
2035 if (params.pagestyle == "fancy") {
2036 ofs << "\\usepackage{fancyhdr}\n";
2039 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2043 // We try to load babel late, in case it interferes
2044 // with other packages.
2046 ofs << lyxrc.language_package << endl;
2050 if (params.secnumdepth != tclass.secnumdepth()) {
2051 ofs << "\\setcounter{secnumdepth}{"
2052 << params.secnumdepth
2056 if (params.tocdepth != tclass.tocdepth()) {
2057 ofs << "\\setcounter{tocdepth}{"
2063 if (params.paragraph_separation) {
2064 switch (params.defskip.kind()) {
2065 case VSpace::SMALLSKIP:
2066 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2068 case VSpace::MEDSKIP:
2069 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2071 case VSpace::BIGSKIP:
2072 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2074 case VSpace::LENGTH:
2075 ofs << "\\setlength\\parskip{"
2076 << params.defskip.length().asLatexString()
2079 default: // should never happen // Then delete it.
2080 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2085 ofs << "\\setlength\\parindent{0pt}\n";
2089 // Now insert the LyX specific LaTeX commands...
2091 // The optional packages;
2092 string preamble(features.getPackages());
2094 // this might be useful...
2095 preamble += "\n\\makeatletter\n";
2097 // Some macros LyX will need
2098 string tmppreamble(features.getMacros());
2100 if (!tmppreamble.empty()) {
2101 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2102 "LyX specific LaTeX commands.\n"
2103 + tmppreamble + '\n';
2106 // the text class specific preamble
2107 tmppreamble = features.getTClassPreamble();
2108 if (!tmppreamble.empty()) {
2109 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2110 "Textclass specific LaTeX commands.\n"
2111 + tmppreamble + '\n';
2114 /* the user-defined preamble */
2115 if (!params.preamble.empty()) {
2116 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2117 "User specified LaTeX commands.\n"
2118 + params.preamble + '\n';
2121 preamble += "\\makeatother\n";
2123 // Itemize bullet settings need to be last in case the user
2124 // defines their own bullets that use a package included
2125 // in the user-defined preamble -- ARRae
2126 // Actually it has to be done much later than that
2127 // since some packages like frenchb make modifications
2128 // at \begin{document} time -- JMarc
2130 for (int i = 0; i < 4; ++i) {
2131 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2132 if (bullets_def.empty())
2133 bullets_def="\\AtBeginDocument{\n";
2134 bullets_def += " \\renewcommand{\\labelitemi";
2136 // `i' is one less than the item to modify
2143 bullets_def += "ii";
2149 bullets_def += "}{" +
2150 params.user_defined_bullets[i].getText()
2155 if (!bullets_def.empty())
2156 preamble += bullets_def + "}\n\n";
2158 for (int j = countChar(preamble, '\n'); j-- ;) {
2165 ofs << "\\begin{document}\n";
2168 lyxerr.debug() << "preamble finished, now the body." << endl;
2169 #ifdef DO_USE_DEFAULT_LANGUAGE
2170 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2172 if (!lyxrc.language_auto_begin) {
2174 ofs << subst(lyxrc.language_command_begin, "$$lang",
2175 params.language->babel())
2180 latexParagraphs(ofs, paragraph, 0, texrow);
2182 // add this just in case after all the paragraphs
2186 #ifdef DO_USE_DEFAULT_LANGUAGE
2187 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2189 if (!lyxrc.language_auto_end) {
2191 ofs << subst(lyxrc.language_command_end, "$$lang",
2192 params.language->babel())
2198 ofs << "\\end{document}\n";
2201 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2203 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2207 // Just to be sure. (Asger)
2210 // tex_code_break_column's value is used to decide
2211 // if we are in batchmode or not (within mathed_write()
2212 // in math_write.C) so we must set it to a non-zero
2213 // value when we leave otherwise we save incorrect .lyx files.
2214 tex_code_break_column = lyxrc.ascii_linelen;
2218 lyxerr << "File was not closed properly." << endl;
2221 lyxerr.debug() << "Finished making latex file." << endl;
2226 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2228 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2229 LyXParagraph * endpar, TexRow & texrow) const
2231 bool was_title = false;
2232 bool already_title = false;
2233 std::ostringstream ftnote;
2238 while (par != endpar) {
2241 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2244 LyXLayout const & layout =
2245 textclasslist.Style(params.textclass,
2248 if (layout.intitle) {
2249 if (already_title) {
2250 lyxerr <<"Error in latexParagraphs: You"
2251 " should not mix title layouts"
2252 " with normal ones." << endl;
2255 } else if (was_title && !already_title) {
2256 ofs << "\\maketitle\n";
2258 already_title = true;
2261 // We are at depth 0 so we can just use
2262 // ordinary \footnote{} generation
2263 // flag this with ftcount
2265 if (layout.isEnvironment()
2266 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2267 par = par->TeXEnvironment(this, params, ofs, texrow
2269 ,ftnote, ft_texrow, ftcount
2273 par = par->TeXOnePar(this, params, ofs, texrow, false
2276 ftnote, ft_texrow, ftcount
2281 // Write out what we've generated...
2284 ofs << "\\addtocounter{footnote}{-"
2288 ofs << ftnote.str();
2289 texrow += ft_texrow;
2291 // The extra .c_str() is needed when we use
2292 // lyxstring instead of the STL string class.
2293 ftnote.str(string().c_str());
2298 // It might be that we only have a title in this document
2299 if (was_title && !already_title) {
2300 ofs << "\\maketitle\n";
2306 bool Buffer::isLatex() const
2308 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2312 bool Buffer::isLinuxDoc() const
2314 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2318 bool Buffer::isLiterate() const
2320 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2324 bool Buffer::isDocBook() const
2326 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2330 bool Buffer::isSGML() const
2332 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2333 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2337 void Buffer::sgmlOpenTag(ostream & os, int depth,
2338 string const & latexname) const
2340 os << string(depth, ' ') << "<" << latexname << ">\n";
2344 void Buffer::sgmlCloseTag(ostream & os, int depth,
2345 string const & latexname) const
2347 os << string(depth, ' ') << "</" << latexname << ">\n";
2351 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2353 LyXParagraph * par = paragraph;
2355 niceFile = nice; // this will be used by Insetincludes.
2357 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2358 string environment_stack[10];
2361 int depth = 0; // paragraph depth
2363 ofstream ofs(fname.c_str());
2366 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2370 LyXTextClass const & tclass =
2371 textclasslist.TextClass(params.textclass);
2373 LaTeXFeatures features(params, tclass.numLayouts());
2377 tex_code_break_column = lyxrc.ascii_linelen;
2379 //tex_code_break_column = 0;
2384 string sgml_includedfiles=features.getIncludedFiles();
2386 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2387 ofs << "<!doctype linuxdoc system>\n\n";
2389 ofs << "<!doctype linuxdoc system [ "
2390 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2393 if(params.options.empty())
2394 sgmlOpenTag(ofs, 0, top_element);
2396 string top = top_element;
2398 top += params.options;
2399 sgmlOpenTag(ofs, 0, top);
2403 ofs << "<!-- " << LYX_DOCVERSION
2404 << " created this file. For more info see http://www.lyx.org/"
2408 int desc_on = 0; // description mode
2409 LyXLayout const & style =
2410 textclasslist.Style(params.textclass,
2413 // treat <toc> as a special case for compatibility with old code
2414 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2415 Inset * inset = par->GetInset(0);
2416 Inset::Code lyx_code = inset->LyxCode();
2417 if (lyx_code == Inset::TOC_CODE){
2418 string const temp = "toc";
2419 sgmlOpenTag(ofs, depth, temp);
2423 linuxDocHandleFootnote(ofs, par, depth);
2429 // environment tag closing
2430 for (; depth > par->depth; --depth) {
2431 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2432 environment_stack[depth].erase();
2435 // write opening SGML tags
2436 switch (style.latextype) {
2437 case LATEX_PARAGRAPH:
2438 if(depth == par->depth
2439 && !environment_stack[depth].empty()) {
2440 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2441 environment_stack[depth].erase();
2447 sgmlOpenTag(ofs, depth, style.latexname());
2452 LinuxDocError(par, 0,
2453 _("Error : Wrong depth for"
2454 " LatexType Command.\n"));
2456 if (!environment_stack[depth].empty()){
2457 sgmlCloseTag(ofs, depth,
2458 environment_stack[depth]);
2462 environment_stack[depth].erase();
2463 sgmlOpenTag(ofs, depth, style.latexname());
2466 case LATEX_ENVIRONMENT:
2467 case LATEX_ITEM_ENVIRONMENT:
2468 if (depth == par->depth
2469 && environment_stack[depth] != style.latexname()
2470 && !environment_stack[depth].empty()) {
2472 sgmlCloseTag(ofs, depth,
2473 environment_stack[depth]);
2474 environment_stack[depth].erase();
2476 if (depth < par->depth) {
2478 environment_stack[depth].erase();
2480 if (environment_stack[depth] != style.latexname()) {
2482 string const temp = "p";
2483 sgmlOpenTag(ofs, depth, temp);
2485 environment_stack[depth] = style.latexname();
2486 sgmlOpenTag(ofs, depth,
2487 environment_stack[depth]);
2489 if(style.latextype == LATEX_ENVIRONMENT) break;
2491 desc_on = (style.labeltype == LABEL_MANUAL);
2498 sgmlOpenTag(ofs, depth + 1, item_name);
2501 sgmlOpenTag(ofs, depth, style.latexname());
2508 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2512 linuxDocHandleFootnote(ofs, par, depth);
2514 while(par && par->IsDummy());
2518 // write closing SGML tags
2519 switch(style.latextype) {
2521 case LATEX_ENVIRONMENT:
2522 case LATEX_ITEM_ENVIRONMENT:
2525 sgmlCloseTag(ofs, depth, style.latexname());
2531 for(; depth > 0; --depth)
2532 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2534 if(!environment_stack[depth].empty())
2535 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2539 sgmlCloseTag(ofs, 0, top_element);
2543 // How to check for successful close
2548 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2551 string const tag = "footnote";
2553 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2554 sgmlOpenTag(os, depth + 1, tag);
2555 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2556 sgmlCloseTag(os, depth + 1, tag);
2563 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2564 int depth, int desc_on,
2565 LyXParagraph * & par)
2567 LyXParagraph * tpar = par;
2570 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2572 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2576 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2577 "Caption").second) {
2578 sgmlOpenTag(os, depth + 1, inner_tag);
2580 SimpleDocBookOnePar(os, extra_par, tpar,
2581 desc_on, depth + 2);
2582 sgmlCloseTag(os, depth+1, inner_tag);
2583 if(!extra_par.empty())
2590 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2593 string tag, inner_tag;
2594 string tmp_par, extra_par;
2595 bool inner_span = false;
2598 // Someone should give this enum a proper name (Lgb)
2606 SOME_ENUM last = NO_ONE;
2607 SOME_ENUM present = FOOTNOTE_LIKE;
2609 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2610 if (last == present) {
2612 if (!tmp_par.empty()) {
2615 sgmlCloseTag(os, depth + 1, inner_tag);
2616 sgmlOpenTag(os, depth + 1, inner_tag);
2623 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2625 if (!extra_par.empty()) os << extra_par;
2626 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2629 switch (par->footnotekind) {
2630 case LyXParagraph::FOOTNOTE:
2631 case LyXParagraph::ALGORITHM:
2634 present = FOOTNOTE_LIKE;
2637 case LyXParagraph::MARGIN:
2640 present = MARGIN_LIKE;
2643 case LyXParagraph::FIG:
2644 case LyXParagraph::WIDE_FIG:
2646 inner_tag = "title";
2650 case LyXParagraph::TAB:
2651 case LyXParagraph::WIDE_TAB:
2653 inner_tag = "title";
2658 sgmlOpenTag(os, depth, tag);
2659 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2660 DocBookHandleCaption(os, inner_tag, depth,
2664 sgmlOpenTag(os, depth + 1, inner_tag);
2667 // ignore all caption here, we processed them above!!!
2668 if (par->layout != textclasslist
2669 .NumberOfLayout(params.textclass,
2670 "Caption").second) {
2671 std::ostringstream ost;
2672 SimpleDocBookOnePar(ost, extra_par, par,
2673 desc_on, depth + 2);
2674 tmp_par += ost.str().c_str();
2676 tmp_par = frontStrip(strip(tmp_par));
2682 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2683 if(!extra_par.empty()) os << extra_par;
2684 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2689 // push a tag in a style stack
2690 void Buffer::push_tag(ostream & os, string const & tag,
2691 int & pos, char stack[5][3])
2693 #ifdef WITH_WARNINGS
2694 #warning Use a real stack! (Lgb)
2696 // pop all previous tags
2697 for (int j = pos; j >= 0; --j)
2698 os << "</" << stack[j] << ">";
2701 sprintf(stack[++pos], "%s", tag.c_str());
2704 for (int i = 0; i <= pos; ++i)
2705 os << "<" << stack[i] << ">";
2709 void Buffer::pop_tag(ostream & os, string const & tag,
2710 int & pos, char stack[5][3])
2712 #ifdef WITH_WARNINGS
2713 #warning Use a real stack! (Lgb)
2715 // Please, Lars, do not remove the global variable. I already
2716 // had to reintroduce it twice! (JMarc)
2719 // pop all tags till specified one
2720 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2721 os << "</" << stack[j] << ">";
2724 os << "</" << tag << ">";
2726 // push all tags, but the specified one
2727 for (j = j + 1; j <= pos; ++j) {
2728 os << "<" << stack[j] << ">";
2729 strcpy(stack[j-1], stack[j]);
2735 // Handle internal paragraph parsing -- layout already processed.
2737 // checks, if newcol chars should be put into this line
2738 // writes newline, if necessary.
2740 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2741 string::size_type newcol)
2744 if (colcount > lyxrc.ascii_linelen) {
2746 colcount = newcol; // assume write after this call
2751 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2752 int desc_on, int /*depth*/)
2757 LyXParagraph::size_type main_body;
2759 LyXLayout const & style = textclasslist.Style(params.textclass,
2762 char family_type = 0; // family font flag
2763 bool is_bold = false; // series font flag
2764 char shape_type = 0; // shape font flag
2765 bool is_em = false; // emphasis (italic) font flag
2767 int stack_num = -1; // style stack position
2768 // Can this be rewritten to use a std::stack, please. (Lgb)
2769 char stack[5][3]; // style stack
2770 string::size_type char_line_count = 5; // Heuristic choice ;-)
2772 if (style.labeltype != LABEL_MANUAL)
2775 main_body = par->BeginningOfMainBody();
2777 // gets paragraph main font
2779 font1 = style.labelfont;
2784 // parsing main loop
2785 for (LyXParagraph::size_type i = 0;
2786 i < par->size(); ++i) {
2798 LyXFont const font2 = par->getFont(params, i);
2800 if (font1.family() != font2.family()) {
2801 switch(family_type) {
2803 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2804 push_tag(os, "tt", stack_num, stack);
2807 else if (font2.family() == LyXFont::SANS_FAMILY) {
2808 push_tag(os, "sf", stack_num, stack);
2813 pop_tag(os, "tt", stack_num, stack);
2814 if (font2.family() == LyXFont::SANS_FAMILY) {
2815 push_tag(os, "sf", stack_num, stack);
2822 pop_tag(os, "sf", stack_num, stack);
2823 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2824 push_tag(os, "tt", stack_num, stack);
2833 if (font1.series() != font2.series()) {
2834 if (font2.series() == LyXFont::BOLD_SERIES) {
2835 push_tag(os, "bf", stack_num, stack);
2837 } else if (is_bold) {
2838 pop_tag(os, "bf", stack_num, stack);
2843 // handle italic and slanted fonts
2844 if (font1.shape() != font2.shape()) {
2845 switch(shape_type) {
2847 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2848 push_tag(os, "it", stack_num, stack);
2850 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2851 push_tag(os, "sl", stack_num, stack);
2856 pop_tag(os, "it", stack_num, stack);
2857 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2858 push_tag(os, "sl", stack_num, stack);
2865 pop_tag(os, "sl", stack_num, stack);
2866 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2867 push_tag(os, "it", stack_num, stack);
2875 if (font1.emph() != font2.emph()) {
2876 if (font2.emph() == LyXFont::ON) {
2877 push_tag(os, "em", stack_num, stack);
2880 pop_tag(os, "em", stack_num, stack);
2885 c = par->GetChar(i);
2887 if (c == LyXParagraph::META_INSET) {
2888 inset = par->GetInset(i);
2889 inset->Linuxdoc(this, os);
2892 if (font2.latex() == LyXFont::ON) {
2893 // "TeX"-Mode on == > SGML-Mode on.
2895 os << c; // see LaTeX-Generation...
2899 if (par->linuxDocConvertChar(c, sgml_string)
2900 && !style.free_spacing) { // in freespacing
2902 // non-breaking characters
2906 linux_doc_line_break(os, char_line_count, 6);
2910 linux_doc_line_break(os, char_line_count, 1);
2915 char_line_count += sgml_string.length();
2921 // needed if there is an optional argument but no contents
2922 if (main_body > 0 && main_body == par->size()) {
2926 // pop all defined Styles
2927 for (j = stack_num; j >= 0; --j) {
2928 linux_doc_line_break(os,
2930 3 + strlen(stack[j]));
2931 os << "</" << stack[j] << ">";
2934 // resets description flag correctly
2937 // <tag> not closed...
2938 linux_doc_line_break(os, char_line_count, 6);
2942 // fprintf(file, "</p>");
2948 // Print an error message.
2949 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2950 string const & message)
2952 // insert an error marker in text
2953 InsetError * new_inset = new InsetError(message);
2954 par->InsertInset(pos, new_inset);
2957 // This constant defines the maximum number of
2958 // environment layouts that can be nesteded.
2959 // The same applies for command layouts.
2960 // These values should be more than enough.
2961 // José Matos (1999/07/22)
2963 enum { MAX_NEST_LEVEL = 25};
2965 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2967 LyXParagraph * par = paragraph;
2969 niceFile = nice; // this will be used by Insetincludes.
2971 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2972 // Please use a real stack.
2973 string environment_stack[MAX_NEST_LEVEL];
2974 string environment_inner[MAX_NEST_LEVEL];
2975 // Please use a real stack.
2976 string command_stack[MAX_NEST_LEVEL];
2977 bool command_flag= false;
2978 int command_depth= 0, command_base= 0, cmd_depth= 0;
2980 string item_name, command_name;
2981 string c_depth, c_params, tmps;
2983 int depth = 0; // paragraph depth
2984 LyXTextClass const & tclass =
2985 textclasslist.TextClass(params.textclass);
2987 LaTeXFeatures features(params, tclass.numLayouts());
2991 tex_code_break_column = lyxrc.ascii_linelen;
2993 //tex_code_break_column = 0;
2995 ofstream ofs(fname.c_str());
2997 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3004 string sgml_includedfiles=features.getIncludedFiles();
3006 ofs << "<!doctype " << top_element
3007 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3009 if (params.preamble.empty() && sgml_includedfiles.empty())
3012 ofs << "\n [ " << params.preamble
3013 << sgml_includedfiles << " \n]>\n\n";
3015 if(params.options.empty())
3016 sgmlOpenTag(ofs, 0, top_element);
3018 string top = top_element;
3020 top += params.options;
3021 sgmlOpenTag(ofs, 0, top);
3025 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3026 << "\n See http://www.lyx.org/ for more information -->\n";
3029 int desc_on = 0; // description mode
3030 LyXLayout const & style =
3031 textclasslist.Style(params.textclass,
3034 // environment tag closing
3035 for( ; depth > par->depth; --depth) {
3036 if(environment_inner[depth] != "!-- --") {
3037 item_name= "listitem";
3038 sgmlCloseTag(ofs, command_depth + depth,
3040 if( environment_inner[depth] == "varlistentry")
3041 sgmlCloseTag(ofs, depth+command_depth,
3042 environment_inner[depth]);
3044 sgmlCloseTag(ofs, depth + command_depth,
3045 environment_stack[depth]);
3046 environment_stack[depth].erase();
3047 environment_inner[depth].erase();
3050 if(depth == par->depth
3051 && environment_stack[depth] != style.latexname()
3052 && !environment_stack[depth].empty()) {
3053 if(environment_inner[depth] != "!-- --") {
3054 item_name= "listitem";
3055 sgmlCloseTag(ofs, command_depth+depth,
3057 if( environment_inner[depth] == "varlistentry")
3059 depth + command_depth,
3060 environment_inner[depth]);
3063 sgmlCloseTag(ofs, depth + command_depth,
3064 environment_stack[depth]);
3066 environment_stack[depth].erase();
3067 environment_inner[depth].erase();
3070 // Write opening SGML tags.
3071 switch(style.latextype) {
3072 case LATEX_PARAGRAPH:
3073 if(style.latexname() != "dummy")
3074 sgmlOpenTag(ofs, depth+command_depth,
3080 LinuxDocError(par, 0,
3081 _("Error : Wrong depth for "
3082 "LatexType Command.\n"));
3084 command_name = style.latexname();
3086 tmps = style.latexparam();
3087 c_params = split(tmps, c_depth,'|');
3089 cmd_depth= lyx::atoi(c_depth);
3092 if(cmd_depth<command_base) {
3093 for(int j = command_depth;
3094 j >= command_base; --j)
3095 if(!command_stack[j].empty())
3096 sgmlCloseTag(ofs, j, command_stack[j]);
3097 command_depth= command_base= cmd_depth;
3098 } else if(cmd_depth <= command_depth) {
3099 for(int j = command_depth;
3100 j >= cmd_depth; --j)
3102 if(!command_stack[j].empty())
3103 sgmlCloseTag(ofs, j, command_stack[j]);
3104 command_depth= cmd_depth;
3106 command_depth= cmd_depth;
3108 command_depth = command_base = cmd_depth;
3109 command_flag = true;
3111 command_stack[command_depth]= command_name;
3113 // treat label as a special case for
3114 // more WYSIWYM handling.
3115 if (par->GetChar(0) == LyXParagraph::META_INSET) {
3116 Inset * inset = par->GetInset(0);
3117 Inset::Code lyx_code = inset->LyxCode();
3118 if (lyx_code == Inset::LABEL_CODE){
3119 command_name += " id=\"";
3120 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3121 command_name += "\"";
3126 sgmlOpenTag(ofs, depth + command_depth, command_name);
3127 item_name = "title";
3128 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3131 case LATEX_ENVIRONMENT:
3132 case LATEX_ITEM_ENVIRONMENT:
3133 if (depth < par->depth) {
3135 environment_stack[depth].erase();
3138 if (environment_stack[depth] != style.latexname()) {
3139 environment_stack[depth] = style.latexname();
3140 environment_inner[depth] = "!-- --";
3141 sgmlOpenTag(ofs, depth + command_depth,
3142 environment_stack[depth]);
3144 if(environment_inner[depth] != "!-- --") {
3145 item_name= "listitem";
3147 command_depth + depth,
3149 if (environment_inner[depth] == "varlistentry")
3151 depth + command_depth,
3152 environment_inner[depth]);
3156 if(style.latextype == LATEX_ENVIRONMENT) {
3157 if(!style.latexparam().empty())
3158 sgmlOpenTag(ofs, depth + command_depth,
3159 style.latexparam());
3163 desc_on = (style.labeltype == LABEL_MANUAL);
3166 environment_inner[depth]= "varlistentry";
3168 environment_inner[depth]= "listitem";
3170 sgmlOpenTag(ofs, depth + 1 + command_depth,
3171 environment_inner[depth]);
3175 sgmlOpenTag(ofs, depth + 1 + command_depth,
3179 sgmlOpenTag(ofs, depth + 1 + command_depth,
3184 sgmlOpenTag(ofs, depth + command_depth,
3193 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3194 depth + 1 + command_depth);
3197 DocBookHandleFootnote(ofs, par,
3198 depth + 1 + command_depth);
3200 while(par && par->IsDummy());
3203 // write closing SGML tags
3204 switch(style.latextype) {
3207 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3209 case LATEX_ENVIRONMENT:
3210 if(!style.latexparam().empty())
3211 sgmlCloseTag(ofs, depth + command_depth,
3212 style.latexparam());
3214 case LATEX_ITEM_ENVIRONMENT:
3215 if(desc_on == 1) break;
3217 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3219 case LATEX_PARAGRAPH:
3220 if(style.latexname() != "dummy")
3221 sgmlCloseTag(ofs, depth + command_depth,
3225 sgmlCloseTag(ofs, depth + command_depth,
3232 for(; depth >= 0; --depth) {
3233 if(!environment_stack[depth].empty()) {
3234 if(environment_inner[depth] != "!-- --") {
3235 item_name= "listitem";
3236 sgmlCloseTag(ofs, command_depth + depth,
3238 if( environment_inner[depth] == "varlistentry")
3239 sgmlCloseTag(ofs, depth + command_depth,
3240 environment_inner[depth]);
3243 sgmlCloseTag(ofs, depth + command_depth,
3244 environment_stack[depth]);
3248 for(int j = command_depth; j >= command_base; --j)
3249 if(!command_stack[j].empty())
3250 sgmlCloseTag(ofs, j, command_stack[j]);
3254 sgmlCloseTag(ofs, 0, top_element);
3258 // How to check for successful close
3262 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3263 LyXParagraph * par, int & desc_on,
3266 bool emph_flag = false;
3268 LyXLayout const & style = textclasslist.Style(params.textclass,
3271 LyXParagraph::size_type main_body;
3272 if (style.labeltype != LABEL_MANUAL)
3275 main_body = par->BeginningOfMainBody();
3277 // gets paragraph main font
3278 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3280 int char_line_count = depth;
3281 if(!style.free_spacing)
3282 for (int j = 0; j < depth; ++j)
3285 // parsing main loop
3286 for (LyXParagraph::size_type i = 0;
3287 i < par->size(); ++i) {
3288 LyXFont font2 = par->getFont(params, i);
3290 // handle <emphasis> tag
3291 if (font1.emph() != font2.emph() && i) {
3292 if (font2.emph() == LyXFont::ON) {
3296 os << "</emphasis>";
3301 char c = par->GetChar(i);
3303 if (c == LyXParagraph::META_INSET) {
3304 Inset * inset = par->GetInset(i);
3305 std::ostringstream ost;
3306 inset->DocBook(this, ost);
3307 string tmp_out = ost.str().c_str();
3310 // This code needs some explanation:
3311 // Two insets are treated specially
3312 // label if it is the first element in a command paragraph
3314 // graphics inside tables or figure floats can't go on
3315 // title (the equivalente in latex for this case is caption
3316 // and title should come first
3319 if(desc_on!= 3 || i!= 0) {
3320 if(!tmp_out.empty() && tmp_out[0] == '@') {
3322 extra += frontStrip(tmp_out, '@');
3324 os << frontStrip(tmp_out, '@');
3329 } else if (font2.latex() == LyXFont::ON) {
3330 // "TeX"-Mode on ==> SGML-Mode on.
3336 if (par->linuxDocConvertChar(c, sgml_string)
3337 && !style.free_spacing) { // in freespacing
3339 // non-breaking characters
3343 os << "\n</term><listitem><para>";
3355 // needed if there is an optional argument but no contents
3356 if (main_body > 0 && main_body == par->size()) {
3360 os << "</emphasis>";
3363 // resets description flag correctly
3366 // <term> not closed...
3374 // This should be enabled when the Chktex class is implemented. (Asger)
3375 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3376 // Other flags: -wall -v0 -x
3377 int Buffer::runChktex()
3379 if (!users->text) return 0;
3381 ProhibitInput(users);
3383 // get LaTeX-Filename
3384 string const name = getLatexName();
3385 string path = OnlyPath(filename);
3387 string const org_path = path;
3388 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3392 Path p(path); // path to LaTeX file
3393 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3395 // Remove all error insets
3396 bool const removedErrorInsets = users->removeAutoInsets();
3398 // Generate the LaTeX file if neccessary
3399 makeLaTeXFile(name, org_path, false);
3402 Chktex chktex(lyxrc.chktex_command, name, filepath);
3403 int res = chktex.run(terr); // run chktex
3406 WriteAlert(_("chktex did not work!"),
3407 _("Could not run with file:"), name);
3408 } else if (res > 0) {
3409 // Insert all errors as errors boxes
3410 users->insertErrors(terr);
3413 // if we removed error insets before we ran chktex or if we inserted
3414 // error insets after we ran chktex, this must be run:
3415 if (removedErrorInsets || res){
3417 users->fitCursor(users->text);
3425 void Buffer::validate(LaTeXFeatures & features) const
3427 LyXParagraph * par = paragraph;
3428 LyXTextClass const & tclass =
3429 textclasslist.TextClass(params.textclass);
3431 // AMS Style is at document level
3433 features.amsstyle = (params.use_amsmath ||
3434 tclass.provides(LyXTextClass::amsmath));
3437 // We don't use "lyxerr.debug" because of speed. (Asger)
3438 if (lyxerr.debugging(Debug::LATEX))
3439 lyxerr << "Paragraph: " << par << endl;
3441 // Now just follow the list of paragraphs and run
3442 // validate on each of them.
3443 par->validate(features);
3445 // and then the next paragraph
3449 // the bullet shapes are buffer level not paragraph level
3450 // so they are tested here
3451 for (int i = 0; i < 4; ++i) {
3452 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3453 int const font = params.user_defined_bullets[i].getFont();
3455 int const c = params
3456 .user_defined_bullets[i]
3463 features.latexsym = true;
3465 } else if (font == 1) {
3466 features.amssymb = true;
3467 } else if ((font >= 2 && font <= 5)) {
3468 features.pifont = true;
3473 if (lyxerr.debugging(Debug::LATEX)) {
3474 features.showStruct();
3479 void Buffer::setPaperStuff()
3481 params.papersize = BufferParams::PAPER_DEFAULT;
3482 char const c1 = params.paperpackage;
3483 if (c1 == BufferParams::PACKAGE_NONE) {
3484 char const c2 = params.papersize2;
3485 if (c2 == BufferParams::VM_PAPER_USLETTER)
3486 params.papersize = BufferParams::PAPER_USLETTER;
3487 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3488 params.papersize = BufferParams::PAPER_LEGALPAPER;
3489 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3490 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3491 else if (c2 == BufferParams::VM_PAPER_A3)
3492 params.papersize = BufferParams::PAPER_A3PAPER;
3493 else if (c2 == BufferParams::VM_PAPER_A4)
3494 params.papersize = BufferParams::PAPER_A4PAPER;
3495 else if (c2 == BufferParams::VM_PAPER_A5)
3496 params.papersize = BufferParams::PAPER_A5PAPER;
3497 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3498 (c2 == BufferParams::VM_PAPER_B5))
3499 params.papersize = BufferParams::PAPER_B5PAPER;
3500 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3501 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3502 params.papersize = BufferParams::PAPER_A4PAPER;
3506 // This function should be in Buffer because it's a buffer's property (ale)
3507 string const Buffer::getIncludeonlyList(char delim)
3510 for (inset_iterator it = inset_iterator_begin();
3511 it != inset_iterator_end(); ++it) {
3512 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3513 InsetInclude * insetinc =
3514 static_cast<InsetInclude *>(*it);
3515 if (insetinc->isInclude()
3516 && insetinc->isNoLoad()) {
3519 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3523 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3528 vector<string> const Buffer::getLabelList()
3530 /// if this is a child document and the parent is already loaded
3531 /// Use the parent's list instead [ale990407]
3532 if (!params.parentname.empty()
3533 && bufferlist.exists(params.parentname)) {
3534 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3536 return tmp->getLabelList();
3539 vector<string> label_list;
3540 for (inset_iterator it = inset_iterator_begin();
3541 it != inset_iterator_end(); ++it) {
3542 vector<string> const l = (*it)->getLabelList();
3543 label_list.insert(label_list.end(), l.begin(), l.end());
3549 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3551 vector<vector<TocItem> > l(4);
3552 LyXParagraph * par = paragraph;
3555 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3556 if (textclasslist.Style(params.textclass,
3557 par->GetLayout()).labeltype
3558 == LABEL_SENSITIVE) {
3562 tmp.str = par->String(this, false);
3563 switch (par->footnotekind) {
3564 case LyXParagraph::FIG:
3565 case LyXParagraph::WIDE_FIG:
3566 l[TOC_LOF].push_back(tmp);
3568 case LyXParagraph::TAB:
3569 case LyXParagraph::WIDE_TAB:
3570 l[TOC_LOT].push_back(tmp);
3572 case LyXParagraph::ALGORITHM:
3573 l[TOC_LOA].push_back(tmp);
3575 case LyXParagraph::FOOTNOTE:
3576 case LyXParagraph::MARGIN:
3580 } else if (!par->IsDummy()) {
3582 char const labeltype =
3583 textclasslist.Style(params.textclass,
3584 par->GetLayout()).labeltype;
3586 if (labeltype >= LABEL_COUNTER_CHAPTER
3587 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3588 // insert this into the table of contents
3593 textclasslist.TextClass(params.textclass).maxcounter());
3594 tmp.str = par->String(this, true);
3595 l[TOC_TOC].push_back(tmp);
3606 // This is also a buffer property (ale)
3607 vector<pair<string,string> > const Buffer::getBibkeyList()
3609 /// if this is a child document and the parent is already loaded
3610 /// Use the parent's list instead [ale990412]
3611 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3612 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3614 return tmp->getBibkeyList();
3617 vector<pair<string, string> > keys;
3618 LyXParagraph * par = paragraph;
3621 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3622 par->String(this, false)));
3626 // Might be either using bibtex or a child has bibliography
3628 for (inset_iterator it = inset_iterator_begin();
3629 it != inset_iterator_end(); ++it) {
3630 // Search for Bibtex or Include inset
3631 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3632 vector<pair<string,string> > tmp =
3633 static_cast<InsetBibtex*>(*it)->getKeys(this);
3634 keys.insert(keys.end(), tmp.begin(), tmp.end());
3635 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3636 vector<pair<string,string> > const tmp =
3637 static_cast<InsetInclude*>(*it)->getKeys();
3638 keys.insert(keys.end(), tmp.begin(), tmp.end());
3647 bool Buffer::isDepClean(string const & name) const
3649 DEPCLEAN * item = dep_clean;
3650 while (item && item->master != name)
3652 if (!item) return true;
3657 void Buffer::markDepClean(string const & name)
3660 dep_clean = new DEPCLEAN;
3661 dep_clean->clean = true;
3662 dep_clean->master = name;
3663 dep_clean->next = 0;
3665 DEPCLEAN * item = dep_clean;
3666 while (item && item->master != name)
3671 item = new DEPCLEAN;
3673 item->master = name;
3680 bool Buffer::Dispatch(string const & command)
3682 // Split command string into command and argument
3684 string line = frontStrip(command);
3685 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3687 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3691 bool Buffer::Dispatch(int action, string const & argument)
3693 bool dispatched = true;
3696 Exporter::Export(this, argument, false);
3706 void Buffer::resize()
3708 /// resize the BufferViews!
3714 void Buffer::resizeInsets(BufferView * bv)
3716 /// then remove all LyXText in text-insets
3717 LyXParagraph * par = paragraph;
3718 for(; par; par = par->next) {
3719 par->resizeInsetsLyXText(bv);
3723 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3726 LyXParagraph * par = paragraph;
3728 par->ChangeLanguage(params, from, to);
3734 bool Buffer::isMultiLingual()
3736 LyXParagraph * par = paragraph;
3738 if (par->isMultiLingual(params))
3746 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3747 LyXParagraph::size_type pos)
3750 it = par->InsetIterator(pos);
3751 if (it == par->inset_iterator_end()) {
3758 void Buffer::inset_iterator::SetParagraph()
3761 it = par->inset_iterator_begin();
3762 if (it != par->inset_iterator_end())
3767 // We maintain an invariant that whenever par = 0 then it = 0