1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
23 #include <sys/types.h>
33 #pragma implementation "buffer.h"
37 #include "bufferlist.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
43 #include "tex-strings.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h"
59 #include "insets/insetcite.h"
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h"
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
92 #include "lyx_gui_misc.h" // WarnReadonly()
93 #include "frontends/Dialogs.h"
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
113 extern LyXAction lyxaction;
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 WriteAlert(string(_("Textclass error")),
489 string(_("The document uses an unknown textclass \"")) +
490 lex.GetString() + string("\"."),
491 string(_("LyX will not be able to produce output correctly.")));
492 params.textclass = 0;
494 if (!textclasslist.Load(params.textclass)) {
495 // if the textclass wasn't loaded properly
496 // we need to either substitute another
497 // or stop loading the file.
498 // I can substitute but I don't see how I can
499 // stop loading... ideas?? ARRae980418
500 WriteAlert(_("Textclass Loading Error!"),
501 string(_("Can't load textclass ")) +
502 textclasslist.NameOfClass(params.textclass),
503 _("-- substituting default"));
504 params.textclass = 0;
506 } else if (token == "\\options") {
508 params.options = lex.GetString();
509 } else if (token == "\\language") {
510 params.readLanguage(lex);
511 } else if (token == "\\fontencoding") {
513 } else if (token == "\\inputencoding") {
515 params.inputenc = lex.GetString();
516 } else if (token == "\\graphics") {
517 params.readGraphicsDriver(lex);
518 } else if (token == "\\fontscheme") {
520 params.fonts = lex.GetString();
521 } else if (token == "\\noindent") {
522 par->noindent = true;
523 } else if (token == "\\fill_top") {
524 par->added_space_top = VSpace(VSpace::VFILL);
525 } else if (token == "\\fill_bottom") {
526 par->added_space_bottom = VSpace(VSpace::VFILL);
527 } else if (token == "\\line_top") {
528 par->line_top = true;
529 } else if (token == "\\line_bottom") {
530 par->line_bottom = true;
531 } else if (token == "\\pagebreak_top") {
532 par->pagebreak_top = true;
533 } else if (token == "\\pagebreak_bottom") {
534 par->pagebreak_bottom = true;
535 } else if (token == "\\start_of_appendix") {
536 par->start_of_appendix = true;
537 } else if (token == "\\paragraph_separation") {
538 int tmpret = lex.FindToken(string_paragraph_separation);
539 if (tmpret == -1) ++tmpret;
540 if (tmpret != LYX_LAYOUT_DEFAULT)
541 params.paragraph_separation =
542 static_cast<BufferParams::PARSEP>(tmpret);
543 } else if (token == "\\defskip") {
545 params.defskip = VSpace(lex.GetString());
546 } else if (token == "\\epsfig") { // obsolete
547 // Indeed it is obsolete, but we HAVE to be backwards
548 // compatible until 0.14, because otherwise all figures
549 // in existing documents are irretrivably lost. (Asger)
550 params.readGraphicsDriver(lex);
551 } else if (token == "\\quotes_language") {
552 int tmpret = lex.FindToken(string_quotes_language);
553 if (tmpret == -1) ++tmpret;
554 if (tmpret != LYX_LAYOUT_DEFAULT) {
555 InsetQuotes::quote_language tmpl =
556 InsetQuotes::EnglishQ;
559 tmpl = InsetQuotes::EnglishQ;
562 tmpl = InsetQuotes::SwedishQ;
565 tmpl = InsetQuotes::GermanQ;
568 tmpl = InsetQuotes::PolishQ;
571 tmpl = InsetQuotes::FrenchQ;
574 tmpl = InsetQuotes::DanishQ;
577 params.quotes_language = tmpl;
579 } else if (token == "\\quotes_times") {
581 switch (lex.GetInteger()) {
583 params.quotes_times = InsetQuotes::SingleQ;
586 params.quotes_times = InsetQuotes::DoubleQ;
589 } else if (token == "\\papersize") {
590 int tmpret = lex.FindToken(string_papersize);
594 params.papersize2 = tmpret;
595 } else if (token == "\\paperpackage") {
596 int tmpret = lex.FindToken(string_paperpackages);
599 params.paperpackage = BufferParams::PACKAGE_NONE;
601 params.paperpackage = tmpret;
602 } else if (token == "\\use_geometry") {
604 params.use_geometry = lex.GetInteger();
605 } else if (token == "\\use_amsmath") {
607 params.use_amsmath = lex.GetInteger();
608 } else if (token == "\\paperorientation") {
609 int tmpret = lex.FindToken(string_orientation);
610 if (tmpret == -1) ++tmpret;
611 if (tmpret != LYX_LAYOUT_DEFAULT)
612 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
613 } else if (token == "\\paperwidth") {
615 params.paperwidth = lex.GetString();
616 } else if (token == "\\paperheight") {
618 params.paperheight = lex.GetString();
619 } else if (token == "\\leftmargin") {
621 params.leftmargin = lex.GetString();
622 } else if (token == "\\topmargin") {
624 params.topmargin = lex.GetString();
625 } else if (token == "\\rightmargin") {
627 params.rightmargin = lex.GetString();
628 } else if (token == "\\bottommargin") {
630 params.bottommargin = lex.GetString();
631 } else if (token == "\\headheight") {
633 params.headheight = lex.GetString();
634 } else if (token == "\\headsep") {
636 params.headsep = lex.GetString();
637 } else if (token == "\\footskip") {
639 params.footskip = lex.GetString();
640 } else if (token == "\\paperfontsize") {
642 params.fontsize = strip(lex.GetString());
643 } else if (token == "\\papercolumns") {
645 params.columns = lex.GetInteger();
646 } else if (token == "\\papersides") {
648 switch (lex.GetInteger()) {
650 case 1: params.sides = LyXTextClass::OneSide; break;
651 case 2: params.sides = LyXTextClass::TwoSides; break;
653 } else if (token == "\\paperpagestyle") {
655 params.pagestyle = strip(lex.GetString());
656 } else if (token == "\\bullet") {
658 int const index = lex.GetInteger();
660 int temp_int = lex.GetInteger();
661 params.user_defined_bullets[index].setFont(temp_int);
662 params.temp_bullets[index].setFont(temp_int);
664 temp_int = lex.GetInteger();
665 params.user_defined_bullets[index].setCharacter(temp_int);
666 params.temp_bullets[index].setCharacter(temp_int);
668 temp_int = lex.GetInteger();
669 params.user_defined_bullets[index].setSize(temp_int);
670 params.temp_bullets[index].setSize(temp_int);
672 string const temp_str = lex.GetString();
673 if (temp_str != "\\end_bullet") {
674 // this element isn't really necessary for
675 // parsing but is easier for humans
676 // to understand bullets. Put it back and
677 // set a debug message?
678 lex.printError("\\end_bullet expected, got" + temp_str);
679 //how can I put it back?
681 } else if (token == "\\bulletLaTeX") {
683 int const index = lex.GetInteger();
685 string temp_str = lex.GetString();
687 while (temp_str != "\\end_bullet") {
688 // this loop structure is needed when user
689 // enters an empty string since the first
690 // thing returned will be the \\end_bullet
692 // if the LaTeX entry has spaces. Each element
693 // therefore needs to be read in turn
696 temp_str = lex.GetString();
698 params.user_defined_bullets[index].setText(sum_str);
699 params.temp_bullets[index].setText(sum_str);
700 } else if (token == "\\secnumdepth") {
702 params.secnumdepth = lex.GetInteger();
703 } else if (token == "\\tocdepth") {
705 params.tocdepth = lex.GetInteger();
706 } else if (token == "\\spacing") {
708 string const tmp = strip(lex.GetString());
709 Spacing::Space tmp_space = Spacing::Default;
711 if (tmp == "single") {
712 tmp_space = Spacing::Single;
713 } else if (tmp == "onehalf") {
714 tmp_space = Spacing::Onehalf;
715 } else if (tmp == "double") {
716 tmp_space = Spacing::Double;
717 } else if (tmp == "other") {
719 tmp_space = Spacing::Other;
720 tmp_val = lex.GetFloat();
722 lex.printError("Unknown spacing token: '$$Token'");
724 // Small hack so that files written with klyx will be
727 par->spacing.set(tmp_space, tmp_val);
729 params.spacing.set(tmp_space, tmp_val);
731 } else if (token == "\\paragraph_spacing") {
733 string const tmp = strip(lex.GetString());
734 if (tmp == "single") {
735 par->spacing.set(Spacing::Single);
736 } else if (tmp == "onehalf") {
737 par->spacing.set(Spacing::Onehalf);
738 } else if (tmp == "double") {
739 par->spacing.set(Spacing::Double);
740 } else if (tmp == "other") {
742 par->spacing.set(Spacing::Other,
745 lex.printError("Unknown spacing token: '$$Token'");
747 } else if (token == "\\float_placement") {
749 params.float_placement = lex.GetString();
750 } else if (token == "\\family") {
752 font.setLyXFamily(lex.GetString());
753 } else if (token == "\\series") {
755 font.setLyXSeries(lex.GetString());
756 } else if (token == "\\shape") {
758 font.setLyXShape(lex.GetString());
759 } else if (token == "\\size") {
761 font.setLyXSize(lex.GetString());
762 } else if (token == "\\latex") {
764 string const tok = lex.GetString();
765 // This is dirty, but gone with LyX3. (Asger)
766 if (tok == "no_latex")
767 font.setLatex(LyXFont::OFF);
768 else if (tok == "latex")
769 font.setLatex(LyXFont::ON);
770 else if (tok == "default")
771 font.setLatex(LyXFont::INHERIT);
773 lex.printError("Unknown LaTeX font flag "
775 } else if (token == "\\lang") {
777 string const tok = lex.GetString();
778 Language const * lang = languages.getLanguage(tok);
780 font.setLanguage(lang);
782 font.setLanguage(params.language);
783 lex.printError("Unknown language `$$Token'");
785 } else if (token == "\\numeric") {
787 font.setNumber(font.setLyXMisc(lex.GetString()));
788 } else if (token == "\\emph") {
790 font.setEmph(font.setLyXMisc(lex.GetString()));
791 } else if (token == "\\bar") {
793 string const tok = lex.GetString();
794 // This is dirty, but gone with LyX3. (Asger)
796 font.setUnderbar(LyXFont::ON);
797 else if (tok == "no")
798 font.setUnderbar(LyXFont::OFF);
799 else if (tok == "default")
800 font.setUnderbar(LyXFont::INHERIT);
802 lex.printError("Unknown bar font flag "
804 } else if (token == "\\noun") {
806 font.setNoun(font.setLyXMisc(lex.GetString()));
807 } else if (token == "\\color") {
809 font.setLyXColor(lex.GetString());
810 } else if (token == "\\align") {
811 int tmpret = lex.FindToken(string_align);
812 if (tmpret == -1) ++tmpret;
813 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
816 for (; tmpret > 0; --tmpret)
817 tmpret2 = tmpret2 * 2;
819 int const tmpret2 = int(pow(2.0, tmpret));
821 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
822 par->align = LyXAlignment(tmpret2);
824 } else if (token == "\\added_space_top") {
826 par->added_space_top = VSpace(lex.GetString());
827 } else if (token == "\\added_space_bottom") {
829 par->added_space_bottom = VSpace(lex.GetString());
830 } else if (token == "\\pextra_type") {
832 par->pextra_type = lex.GetInteger();
833 } else if (token == "\\pextra_width") {
835 par->pextra_width = lex.GetString();
836 } else if (token == "\\pextra_widthp") {
838 par->pextra_widthp = lex.GetString();
839 } else if (token == "\\pextra_alignment") {
841 par->pextra_alignment = lex.GetInteger();
842 } else if (token == "\\pextra_hfill") {
844 par->pextra_hfill = lex.GetInteger();
845 } else if (token == "\\pextra_start_minipage") {
847 par->pextra_start_minipage = lex.GetInteger();
848 } else if (token == "\\labelwidthstring") {
850 par->labelwidthstring = lex.GetString();
851 // do not delete this token, it is still needed!
852 } else if (token == "\\end_inset") {
853 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
854 << "Last inset read was: " << last_inset_read
856 // Simply ignore this. The insets do not have
858 // But insets should read it, it is a part of
859 // the inset isn't it? Lgb.
860 } else if (token == "\\begin_inset") {
861 readInset(lex, par, pos, font);
862 } else if (token == "\\SpecialChar") {
863 LyXLayout const & layout =
864 textclasslist.Style(params.textclass,
867 // Insets don't make sense in a free-spacing context! ---Kayvan
868 if (layout.free_spacing) {
871 string next_token = lex.GetString();
872 if (next_token == "\\-") {
873 par->InsertChar(pos, '-', font);
874 } else if (next_token == "\\protected_separator"
875 || next_token == "~") {
876 par->InsertChar(pos, ' ', font);
878 lex.printError("Token `$$Token' "
880 "paragraph layout!");
885 Inset * inset = new InsetSpecialChar;
886 inset->Read(this, lex);
887 par->InsertInset(pos, inset, font);
890 } else if (token == "\\newline") {
891 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
893 } else if (token == "\\LyXTable") {
894 Inset * inset = new InsetTabular(*this);
895 inset->Read(this, lex);
896 par->InsertInset(pos, inset, font);
898 } else if (token == "\\hfill") {
899 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
901 } else if (token == "\\protected_separator") { // obsolete
902 // This is a backward compability thingie. (Lgb)
903 // Remove it later some time...introduced with fileformat
905 LyXLayout const & layout =
906 textclasslist.Style(params.textclass,
909 if (layout.free_spacing) {
910 par->InsertChar(pos, ' ', font);
912 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
913 par->InsertInset(pos, inset, font);
916 } else if (token == "\\bibitem") { // ale970302
918 InsetCommandParams p( "bibitem" );
919 par->bibkey = new InsetBibKey(p);
921 par->bibkey->Read(this, lex);
922 } else if (token == "\\backslash") {
923 par->InsertChar(pos, '\\', font);
925 } else if (token == "\\the_end") {
928 // This should be insurance for the future: (Asger)
929 lex.printError("Unknown token `$$Token'. "
930 "Inserting as text.");
931 string::const_iterator cit = token.begin();
932 string::const_iterator end = token.end();
933 for (; cit != end; ++cit) {
934 par->InsertChar(pos, (*cit), font);
942 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
943 int & pos, LyXFont & font)
946 if (lex.GetString() != "\\begin_inset") {
947 lyxerr << "Buffer::readInset: Consistency check failed."
954 string const tmptok = lex.GetString();
955 last_inset_read = tmptok;
957 // test the different insets
958 if (tmptok == "LatexCommand") {
959 InsetCommandParams inscmd;
962 if (inscmd.getCmdName() == "cite") {
963 inset = new InsetCitation(inscmd);
964 } else if (inscmd.getCmdName() == "bibitem") {
965 lex.printError("Wrong place for bibitem");
966 inset = new InsetBibKey(inscmd);
967 } else if (inscmd.getCmdName() == "BibTeX") {
968 inset = new InsetBibtex(inscmd);
969 } else if (inscmd.getCmdName() == "index") {
970 inset = new InsetIndex(inscmd);
971 } else if (inscmd.getCmdName() == "include") {
972 inset = new InsetInclude(inscmd, *this);
973 } else if (inscmd.getCmdName() == "label") {
974 inset = new InsetLabel(inscmd);
975 } else if (inscmd.getCmdName() == "url"
976 || inscmd.getCmdName() == "htmlurl") {
977 inset = new InsetUrl(inscmd);
978 } else if (inscmd.getCmdName() == "ref"
979 || inscmd.getCmdName() == "pageref"
980 || inscmd.getCmdName() == "vref"
981 || inscmd.getCmdName() == "vpageref"
982 || inscmd.getCmdName() == "prettyref") {
983 if (!inscmd.getOptions().empty()
984 || !inscmd.getContents().empty()) {
985 inset = new InsetRef(inscmd, *this);
987 } else if (inscmd.getCmdName() == "tableofcontents"
988 || inscmd.getCmdName() == "listofalgorithms"
989 || inscmd.getCmdName() == "listoffigures"
990 || inscmd.getCmdName() == "listoftables") {
991 inset = new InsetTOC(inscmd);
992 } else if (inscmd.getCmdName() == "printindex") {
993 inset = new InsetPrintIndex(inscmd);
994 } else if (inscmd.getCmdName() == "lyxparent") {
995 inset = new InsetParent(inscmd, *this);
998 if (tmptok == "Quotes") {
999 inset = new InsetQuotes;
1000 } else if (tmptok == "External") {
1001 inset = new InsetExternal;
1002 } else if (tmptok == "FormulaMacro") {
1003 inset = new InsetFormulaMacro;
1004 } else if (tmptok == "Formula") {
1005 inset = new InsetFormula;
1006 } else if (tmptok == "Figure") {
1007 inset = new InsetFig(100, 100, *this);
1008 } else if (tmptok == "Info") {
1009 inset = new InsetInfo;
1010 } else if (tmptok == "Include") {
1011 InsetCommandParams p( "Include" );
1012 inset = new InsetInclude(p, *this);
1013 } else if (tmptok == "ERT") {
1014 inset = new InsetERT;
1015 } else if (tmptok == "Tabular") {
1016 inset = new InsetTabular(*this);
1017 } else if (tmptok == "Text") {
1018 inset = new InsetText;
1019 } else if (tmptok == "Foot") {
1020 inset = new InsetFoot;
1021 } else if (tmptok == "Marginal") {
1022 inset = new InsetMarginal;
1023 } else if (tmptok == "Minipage") {
1024 inset = new InsetMinipage;
1025 } else if (tmptok == "Float") {
1027 string tmptok = lex.GetString();
1028 inset = new InsetFloat(tmptok);
1029 } else if (tmptok == "List") {
1030 inset = new InsetList;
1031 } else if (tmptok == "Theorem") {
1032 inset = new InsetList;
1033 } else if (tmptok == "Caption") {
1034 inset = new InsetCaption;
1035 } else if (tmptok == "GRAPHICS") {
1036 inset = new InsetGraphics;
1039 if (inset) inset->Read(this, lex);
1043 par->InsertInset(pos, inset, font);
1049 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1053 string const token(lex.GetString());
1054 if (token == "\\lyxformat") { // the first token _must_ be...
1056 format = lex.GetFloat();
1058 if (LYX_FORMAT - format > 0.05) {
1059 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1060 LYX_FORMAT, format) << endl;
1062 if (format - LYX_FORMAT > 0.05) {
1063 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1064 LYX_FORMAT, format) << endl;
1066 bool the_end = readLyXformat2(lex, par);
1067 // Formats >= 2.13 support "\the_end" marker
1074 WriteAlert(_("Warning!"),
1075 _("Reading of document is not complete"),
1076 _("Maybe the document is truncated"));
1077 // We simulate a safe reading anyways to allow
1078 // users to take the chance... (Asger)
1082 WriteAlert(_("ERROR!"),
1083 _("Old LyX file format found. "
1084 "Use LyX 0.10.x to read this!"));
1088 } else { // "\\lyxformat" not found
1089 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1092 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1098 // Should probably be moved to somewhere else: BufferView? LyXView?
1099 bool Buffer::save() const
1101 // We don't need autosaves in the immediate future. (Asger)
1102 resetAutosaveTimers();
1106 if (lyxrc.make_backup) {
1107 s = fileName() + '~';
1108 if (!lyxrc.backupdir_path.empty())
1109 s = AddName(lyxrc.backupdir_path,
1110 subst(CleanupPath(s),'/','!'));
1112 // Rename is the wrong way of making a backup,
1113 // this is the correct way.
1114 /* truss cp fil fil2:
1115 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1116 stat("LyXVC.lyx", 0xEFFFF688) = 0
1117 open("LyXVC.lyx", O_RDONLY) = 3
1118 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1119 fstat(4, 0xEFFFF508) = 0
1120 fstat(3, 0xEFFFF508) = 0
1121 read(3, " # T h i s f i l e w".., 8192) = 5579
1122 write(4, " # T h i s f i l e w".., 5579) = 5579
1123 read(3, 0xEFFFD4A0, 8192) = 0
1126 chmod("LyXVC3.lyx", 0100644) = 0
1127 lseek(0, 0, SEEK_CUR) = 46440
1131 // Should proabaly have some more error checking here.
1132 // Should be cleaned up in 0.13, at least a bit.
1133 // Doing it this way, also makes the inodes stay the same.
1134 // This is still not a very good solution, in particular we
1135 // might loose the owner of the backup.
1136 FileInfo finfo(fileName());
1137 if (finfo.exist()) {
1138 mode_t fmode = finfo.getMode();
1139 struct utimbuf times = {
1140 finfo.getAccessTime(),
1141 finfo.getModificationTime() };
1143 ifstream ifs(fileName().c_str());
1144 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1149 ::chmod(s.c_str(), fmode);
1151 if (::utime(s.c_str(), ×)) {
1152 lyxerr << "utime error." << endl;
1155 lyxerr << "LyX was not able to make "
1156 "backupcopy. Beware." << endl;
1161 if (writeFile(fileName(), false)) {
1163 removeAutosaveFile(fileName());
1165 // Saving failed, so backup is not backup
1166 if (lyxrc.make_backup) {
1167 lyx::rename(s, fileName());
1175 // Returns false if unsuccesful
1176 bool Buffer::writeFile(string const & fname, bool flag) const
1178 // if flag is false writeFile will not create any GUI
1179 // warnings, only cerr.
1180 // Needed for autosave in background or panic save (Matthias 120496)
1182 if (read_only && (fname == filename)) {
1183 // Here we should come with a question if we should
1184 // perform the write anyway.
1186 lyxerr << _("Error! Document is read-only: ")
1189 WriteAlert(_("Error! Document is read-only: "),
1194 FileInfo finfo(fname);
1195 if (finfo.exist() && !finfo.writable()) {
1196 // Here we should come with a question if we should
1197 // try to do the save anyway. (i.e. do a chmod first)
1199 lyxerr << _("Error! Cannot write file: ")
1202 WriteFSAlert(_("Error! Cannot write file: "),
1207 ofstream ofs(fname.c_str());
1210 lyxerr << _("Error! Cannot open file: ")
1213 WriteFSAlert(_("Error! Cannot open file: "),
1219 // Use the standard "C" locale for file output.
1220 ofs.imbue(std::locale::classic());
1223 // The top of the file should not be written by params.
1225 // write out a comment in the top of the file
1226 ofs << '#' << LYX_DOCVERSION
1227 << " created this file. For more info see http://www.lyx.org/\n";
1228 ofs.setf(ios::showpoint|ios::fixed);
1231 char dummy_format[512];
1232 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1233 ofs << "\\lyxformat " << dummy_format << "\n";
1235 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1237 // now write out the buffer paramters.
1238 params.writeFile(ofs);
1240 char footnoteflag = 0;
1243 // this will write out all the paragraphs
1244 // using recursive descent.
1245 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1247 // Write marker that shows file is complete
1248 ofs << "\n\\the_end" << endl;
1252 // how to check if close went ok?
1253 // Following is an attempt... (BE 20001011)
1255 // good() returns false if any error occured, including some
1256 // formatting error.
1257 // bad() returns true if something bad happened in the buffer,
1258 // which should include file system full errors.
1265 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1267 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1277 string const Buffer::asciiParagraph(LyXParagraph const * par,
1278 unsigned int linelen) const
1280 ostringstream buffer;
1283 Inset const * inset;
1285 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1288 int ltype_depth = 0;
1289 unsigned int currlinelen = 0;
1290 bool ref_printed = false;
1296 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1300 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1304 /* begins a footnote environment ? */
1305 if (footnoteflag != par->footnoteflag) {
1306 footnoteflag = par->footnoteflag;
1308 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1309 if ((linelen > 0) &&
1310 ((currlinelen + j) > linelen)) {
1315 << string_footnotekinds[par->footnotekind]
1321 /* begins or ends a deeper area ?*/
1322 if (depth != par->depth) {
1323 if (par->depth > depth) {
1324 while (par->depth > depth) {
1329 while (par->depth < depth) {
1335 /* First write the layout */
1336 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1337 if (tmp == "Itemize") {
1339 ltype_depth = depth+1;
1340 } else if (tmp == "Enumerate") {
1342 ltype_depth = depth+1;
1343 } else if (strstr(tmp.c_str(), "ection")) {
1345 ltype_depth = depth+1;
1346 } else if (strstr(tmp.c_str(), "aragraph")) {
1348 ltype_depth = depth+1;
1349 } else if (tmp == "Description") {
1351 ltype_depth = depth+1;
1352 } else if (tmp == "Abstract") {
1355 } else if (tmp == "Bibliography") {
1363 /* maybe some vertical spaces */
1365 /* the labelwidthstring used in lists */
1369 /* some pagebreaks? */
1373 /* what about the alignment */
1376 /* dummy layout, that means a footnote ended */
1377 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1381 lyxerr << "Should this ever happen?" << endl;
1385 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1386 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1387 if (!i && !footnoteflag && !noparbreak){
1390 for (char j = 0; j < depth; ++j)
1392 currlinelen = depth * 2;
1394 case 0: /* Standard */
1395 case 4: /* (Sub)Paragraph */
1396 case 5: /* Description */
1398 case 6: /* Abstract */
1400 buffer << "Abstract\n\n";
1402 buffer << "Abstract: ";
1404 case 7: /* Bibliography */
1407 buffer << "References\n\n";
1409 buffer << "References: ";
1414 buffer << par->labelstring << " ";
1417 if (ltype_depth > depth) {
1418 for (char j = ltype_depth - 1; j > depth; --j)
1420 currlinelen += (ltype_depth-depth)*2;
1423 font2 = par->GetFontSettings(params, i);
1424 if (font1.latex() != font2.latex()) {
1425 if (font2.latex() == LyXFont::OFF)
1432 c = par->GetChar(i);
1436 case LyXParagraph::META_INSET:
1437 if ((inset = par->GetInset(i))) {
1438 if (!inset->Ascii(this, buffer)) {
1440 string s = rsplit(buffer.str().c_str(),
1442 currlinelen += s.length();
1444 // to be sure it breaks paragraph
1445 currlinelen += linelen;
1449 case LyXParagraph::META_NEWLINE:
1452 for (char j = 0; j < depth; ++j)
1455 currlinelen = depth * 2;
1456 if (ltype_depth > depth) {
1457 for (char j = ltype_depth;
1460 currlinelen += (ltype_depth - depth) * 2;
1463 case LyXParagraph::META_HFILL:
1470 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1471 (c == ' ') && ((i + 2) < par->size()))
1474 for (char j = 0; j < depth; ++j)
1476 currlinelen = depth * 2;
1477 if (ltype_depth > depth) {
1478 for (char j = ltype_depth;
1481 currlinelen += (ltype_depth-depth)*2;
1483 } else if (c != '\0')
1486 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1491 return buffer.str().c_str();
1495 void Buffer::writeFileAscii(string const & fname, int linelen)
1497 ofstream ofs(fname.c_str());
1499 WriteFSAlert(_("Error: Cannot write file:"), fname);
1502 writeFileAscii(ofs, linelen);
1506 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1508 LyXParagraph * par = paragraph;
1510 ofs << asciiParagraph(par, linelen);
1517 void Buffer::makeLaTeXFile(string const & fname,
1518 string const & original_path,
1519 bool nice, bool only_body)
1521 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1523 niceFile = nice; // this will be used by Insetincludes.
1525 tex_code_break_column = lyxrc.ascii_linelen;
1527 LyXTextClass const & tclass =
1528 textclasslist.TextClass(params.textclass);
1530 ofstream ofs(fname.c_str());
1532 WriteFSAlert(_("Error: Cannot open file: "), fname);
1536 // validate the buffer.
1537 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1538 LaTeXFeatures features(params, tclass.numLayouts());
1540 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1543 // The starting paragraph of the coming rows is the
1544 // first paragraph of the document. (Asger)
1545 texrow.start(paragraph, 0);
1547 if (!only_body && nice) {
1548 ofs << "%% " LYX_DOCVERSION " created this file. "
1549 "For more info, see http://www.lyx.org/.\n"
1550 "%% Do not edit unless you really know what "
1555 lyxerr.debug() << "lyx header finished" << endl;
1556 // There are a few differences between nice LaTeX and usual files:
1557 // usual is \batchmode and has a
1558 // special input@path to allow the including of figures
1559 // with either \input or \includegraphics (what figinsets do).
1560 // batchmode is not set if there is a tex_code_break_column.
1561 // In this case somebody is interested in the generated LaTeX,
1562 // so this is OK. input@path is set when the actual parameter
1563 // original_path is set. This is done for usual tex-file, but not
1564 // for nice-latex-file. (Matthias 250696)
1567 // code for usual, NOT nice-latex-file
1568 ofs << "\\batchmode\n"; // changed
1569 // from \nonstopmode
1572 if (!original_path.empty()) {
1573 ofs << "\\makeatletter\n"
1574 << "\\def\\input@path{{"
1575 << original_path << "/}}\n"
1576 << "\\makeatother\n";
1582 ofs << "\\documentclass";
1584 string options; // the document class options.
1586 if (tokenPos(tclass.opt_fontsize(),
1587 '|', params.fontsize) >= 0) {
1588 // only write if existing in list (and not default)
1589 options += params.fontsize;
1594 if (!params.use_geometry &&
1595 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1596 switch (params.papersize) {
1597 case BufferParams::PAPER_A4PAPER:
1598 options += "a4paper,";
1600 case BufferParams::PAPER_USLETTER:
1601 options += "letterpaper,";
1603 case BufferParams::PAPER_A5PAPER:
1604 options += "a5paper,";
1606 case BufferParams::PAPER_B5PAPER:
1607 options += "b5paper,";
1609 case BufferParams::PAPER_EXECUTIVEPAPER:
1610 options += "executivepaper,";
1612 case BufferParams::PAPER_LEGALPAPER:
1613 options += "legalpaper,";
1619 if (params.sides != tclass.sides()) {
1620 switch (params.sides) {
1621 case LyXTextClass::OneSide:
1622 options += "oneside,";
1624 case LyXTextClass::TwoSides:
1625 options += "twoside,";
1632 if (params.columns != tclass.columns()) {
1633 if (params.columns == 2)
1634 options += "twocolumn,";
1636 options += "onecolumn,";
1639 if (!params.use_geometry
1640 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1641 options += "landscape,";
1643 // language should be a parameter to \documentclass
1644 bool use_babel = false;
1645 if (params.language->babel() == "hebrew") // This seems necessary
1646 features.UsedLanguages.insert(default_language);
1647 #ifdef DO_USE_DEFAULT_LANGUAGE
1648 if (params.language->lang() != "default" ||
1649 !features.UsedLanguages.empty()) {
1652 for (LaTeXFeatures::LanguageList::const_iterator cit =
1653 features.UsedLanguages.begin();
1654 cit != features.UsedLanguages.end(); ++cit)
1655 options += (*cit)->babel() + ",";
1656 options += params.language->babel() + ',';
1657 #ifdef DO_USE_DEFAULT_LANGUAGE
1661 // the user-defined options
1662 if (!params.options.empty()) {
1663 options += params.options + ',';
1666 if (!options.empty()){
1667 options = strip(options, ',');
1668 ofs << '[' << options << ']';
1672 << textclasslist.LatexnameOfClass(params.textclass)
1675 // end of \documentclass defs
1677 // font selection must be done before loading fontenc.sty
1678 if (params.fonts != "default") {
1679 ofs << "\\usepackage{" << params.fonts << "}\n";
1682 // this one is not per buffer
1683 if (lyxrc.fontenc != "default") {
1684 ofs << "\\usepackage[" << lyxrc.fontenc
1689 if (params.inputenc == "auto") {
1690 string const doc_encoding =
1691 params.language->encoding()->LatexName();
1693 // Create a list with all the input encodings used
1695 set<string> encodings;
1696 for (LaTeXFeatures::LanguageList::const_iterator it =
1697 features.UsedLanguages.begin();
1698 it != features.UsedLanguages.end(); ++it)
1699 if ((*it)->encoding()->LatexName() != doc_encoding)
1700 encodings.insert((*it)->encoding()->LatexName());
1702 ofs << "\\usepackage[";
1703 std::copy(encodings.begin(), encodings.end(),
1704 std::ostream_iterator<string>(ofs, ","));
1705 ofs << doc_encoding << "]{inputenc}\n";
1707 } else if (params.inputenc != "default") {
1708 ofs << "\\usepackage[" << params.inputenc
1713 // At the very beginning the text parameters.
1714 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1715 switch (params.paperpackage) {
1716 case BufferParams::PACKAGE_A4:
1717 ofs << "\\usepackage{a4}\n";
1720 case BufferParams::PACKAGE_A4WIDE:
1721 ofs << "\\usepackage{a4wide}\n";
1724 case BufferParams::PACKAGE_WIDEMARGINSA4:
1725 ofs << "\\usepackage[widemargins]{a4}\n";
1730 if (params.use_geometry) {
1731 ofs << "\\usepackage{geometry}\n";
1733 ofs << "\\geometry{verbose";
1734 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1735 ofs << ",landscape";
1736 switch (params.papersize2) {
1737 case BufferParams::VM_PAPER_CUSTOM:
1738 if (!params.paperwidth.empty())
1739 ofs << ",paperwidth="
1740 << params.paperwidth;
1741 if (!params.paperheight.empty())
1742 ofs << ",paperheight="
1743 << params.paperheight;
1745 case BufferParams::VM_PAPER_USLETTER:
1746 ofs << ",letterpaper";
1748 case BufferParams::VM_PAPER_USLEGAL:
1749 ofs << ",legalpaper";
1751 case BufferParams::VM_PAPER_USEXECUTIVE:
1752 ofs << ",executivepaper";
1754 case BufferParams::VM_PAPER_A3:
1757 case BufferParams::VM_PAPER_A4:
1760 case BufferParams::VM_PAPER_A5:
1763 case BufferParams::VM_PAPER_B3:
1766 case BufferParams::VM_PAPER_B4:
1769 case BufferParams::VM_PAPER_B5:
1773 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1774 switch (lyxrc.default_papersize) {
1775 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1776 case BufferParams::PAPER_USLETTER:
1777 ofs << ",letterpaper";
1779 case BufferParams::PAPER_LEGALPAPER:
1780 ofs << ",legalpaper";
1782 case BufferParams::PAPER_EXECUTIVEPAPER:
1783 ofs << ",executivepaper";
1785 case BufferParams::PAPER_A3PAPER:
1788 case BufferParams::PAPER_A4PAPER:
1791 case BufferParams::PAPER_A5PAPER:
1794 case BufferParams::PAPER_B5PAPER:
1799 if (!params.topmargin.empty())
1800 ofs << ",tmargin=" << params.topmargin;
1801 if (!params.bottommargin.empty())
1802 ofs << ",bmargin=" << params.bottommargin;
1803 if (!params.leftmargin.empty())
1804 ofs << ",lmargin=" << params.leftmargin;
1805 if (!params.rightmargin.empty())
1806 ofs << ",rmargin=" << params.rightmargin;
1807 if (!params.headheight.empty())
1808 ofs << ",headheight=" << params.headheight;
1809 if (!params.headsep.empty())
1810 ofs << ",headsep=" << params.headsep;
1811 if (!params.footskip.empty())
1812 ofs << ",footskip=" << params.footskip;
1816 if (params.use_amsmath
1817 && !tclass.provides(LyXTextClass::amsmath)) {
1818 ofs << "\\usepackage{amsmath}\n";
1822 if (tokenPos(tclass.opt_pagestyle(),
1823 '|', params.pagestyle) >= 0) {
1824 if (params.pagestyle == "fancy") {
1825 ofs << "\\usepackage{fancyhdr}\n";
1828 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1832 // We try to load babel late, in case it interferes
1833 // with other packages.
1835 ofs << lyxrc.language_package << endl;
1839 if (params.secnumdepth != tclass.secnumdepth()) {
1840 ofs << "\\setcounter{secnumdepth}{"
1841 << params.secnumdepth
1845 if (params.tocdepth != tclass.tocdepth()) {
1846 ofs << "\\setcounter{tocdepth}{"
1852 if (params.paragraph_separation) {
1853 switch (params.defskip.kind()) {
1854 case VSpace::SMALLSKIP:
1855 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1857 case VSpace::MEDSKIP:
1858 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1860 case VSpace::BIGSKIP:
1861 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1863 case VSpace::LENGTH:
1864 ofs << "\\setlength\\parskip{"
1865 << params.defskip.length().asLatexString()
1868 default: // should never happen // Then delete it.
1869 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1874 ofs << "\\setlength\\parindent{0pt}\n";
1878 // Now insert the LyX specific LaTeX commands...
1880 // The optional packages;
1881 string preamble(features.getPackages());
1883 // this might be useful...
1884 preamble += "\n\\makeatletter\n";
1886 // Some macros LyX will need
1887 string tmppreamble(features.getMacros());
1889 if (!tmppreamble.empty()) {
1890 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1891 "LyX specific LaTeX commands.\n"
1892 + tmppreamble + '\n';
1895 // the text class specific preamble
1896 tmppreamble = features.getTClassPreamble();
1897 if (!tmppreamble.empty()) {
1898 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1899 "Textclass specific LaTeX commands.\n"
1900 + tmppreamble + '\n';
1903 /* the user-defined preamble */
1904 if (!params.preamble.empty()) {
1905 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1906 "User specified LaTeX commands.\n"
1907 + params.preamble + '\n';
1910 preamble += "\\makeatother\n";
1912 // Itemize bullet settings need to be last in case the user
1913 // defines their own bullets that use a package included
1914 // in the user-defined preamble -- ARRae
1915 // Actually it has to be done much later than that
1916 // since some packages like frenchb make modifications
1917 // at \begin{document} time -- JMarc
1919 for (int i = 0; i < 4; ++i) {
1920 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1921 if (bullets_def.empty())
1922 bullets_def="\\AtBeginDocument{\n";
1923 bullets_def += " \\renewcommand{\\labelitemi";
1925 // `i' is one less than the item to modify
1932 bullets_def += "ii";
1938 bullets_def += "}{" +
1939 params.user_defined_bullets[i].getText()
1944 if (!bullets_def.empty())
1945 preamble += bullets_def + "}\n\n";
1947 for (int j = countChar(preamble, '\n'); j-- ;) {
1954 ofs << "\\begin{document}\n";
1957 lyxerr.debug() << "preamble finished, now the body." << endl;
1958 #ifdef DO_USE_DEFAULT_LANGUAGE
1959 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
1961 if (!lyxrc.language_auto_begin) {
1963 ofs << subst(lyxrc.language_command_begin, "$$lang",
1964 params.language->babel())
1969 latexParagraphs(ofs, paragraph, 0, texrow);
1971 // add this just in case after all the paragraphs
1975 #ifdef DO_USE_DEFAULT_LANGUAGE
1976 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
1978 if (!lyxrc.language_auto_end) {
1980 ofs << subst(lyxrc.language_command_end, "$$lang",
1981 params.language->babel())
1987 ofs << "\\end{document}\n";
1990 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1992 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1996 // Just to be sure. (Asger)
1999 // tex_code_break_column's value is used to decide
2000 // if we are in batchmode or not (within mathed_write()
2001 // in math_write.C) so we must set it to a non-zero
2002 // value when we leave otherwise we save incorrect .lyx files.
2003 tex_code_break_column = lyxrc.ascii_linelen;
2007 lyxerr << "File was not closed properly." << endl;
2010 lyxerr.debug() << "Finished making latex file." << endl;
2015 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2017 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2018 LyXParagraph * endpar, TexRow & texrow) const
2020 bool was_title = false;
2021 bool already_title = false;
2022 std::ostringstream ftnote;
2027 while (par != endpar) {
2030 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2033 LyXLayout const & layout =
2034 textclasslist.Style(params.textclass,
2037 if (layout.intitle) {
2038 if (already_title) {
2039 lyxerr <<"Error in latexParagraphs: You"
2040 " should not mix title layouts"
2041 " with normal ones." << endl;
2044 } else if (was_title && !already_title) {
2045 ofs << "\\maketitle\n";
2047 already_title = true;
2050 // We are at depth 0 so we can just use
2051 // ordinary \footnote{} generation
2052 // flag this with ftcount
2054 if (layout.isEnvironment()
2055 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2056 par = par->TeXEnvironment(this, params, ofs, texrow
2058 ,ftnote, ft_texrow, ftcount
2062 par = par->TeXOnePar(this, params, ofs, texrow, false
2065 ftnote, ft_texrow, ftcount
2070 // Write out what we've generated...
2073 ofs << "\\addtocounter{footnote}{-"
2077 ofs << ftnote.str();
2078 texrow += ft_texrow;
2080 // The extra .c_str() is needed when we use
2081 // lyxstring instead of the STL string class.
2082 ftnote.str(string().c_str());
2087 // It might be that we only have a title in this document
2088 if (was_title && !already_title) {
2089 ofs << "\\maketitle\n";
2095 bool Buffer::isLatex() const
2097 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2101 bool Buffer::isLinuxDoc() const
2103 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2107 bool Buffer::isLiterate() const
2109 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2113 bool Buffer::isDocBook() const
2115 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2119 bool Buffer::isSGML() const
2121 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2122 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2126 void Buffer::sgmlOpenTag(ostream & os, int depth,
2127 string const & latexname) const
2129 if (latexname != "!-- --")
2130 os << string(depth, ' ') << "<" << latexname << ">\n";
2134 void Buffer::sgmlCloseTag(ostream & os, int depth,
2135 string const & latexname) const
2137 if (latexname != "!-- --")
2138 os << string(depth, ' ') << "</" << latexname << ">\n";
2142 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2144 LyXParagraph * par = paragraph;
2146 niceFile = nice; // this will be used by Insetincludes.
2148 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2149 string environment_stack[10];
2152 int depth = 0; // paragraph depth
2154 ofstream ofs(fname.c_str());
2157 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2161 LyXTextClass const & tclass =
2162 textclasslist.TextClass(params.textclass);
2164 LaTeXFeatures features(params, tclass.numLayouts());
2168 tex_code_break_column = lyxrc.ascii_linelen;
2170 //tex_code_break_column = 0;
2175 string sgml_includedfiles=features.getIncludedFiles(fname);
2177 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2178 ofs << "<!doctype linuxdoc system>\n\n";
2180 ofs << "<!doctype linuxdoc system [ "
2181 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2184 if (params.options.empty())
2185 sgmlOpenTag(ofs, 0, top_element);
2187 string top = top_element;
2189 top += params.options;
2190 sgmlOpenTag(ofs, 0, top);
2194 ofs << "<!-- " << LYX_DOCVERSION
2195 << " created this file. For more info see http://www.lyx.org/"
2199 int desc_on = 0; // description mode
2200 LyXLayout const & style =
2201 textclasslist.Style(params.textclass,
2204 // treat <toc> as a special case for compatibility with old code
2205 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2206 Inset * inset = par->GetInset(0);
2207 Inset::Code lyx_code = inset->LyxCode();
2208 if (lyx_code == Inset::TOC_CODE){
2209 string const temp = "toc";
2210 sgmlOpenTag(ofs, depth, temp);
2214 linuxDocHandleFootnote(ofs, par, depth);
2220 // environment tag closing
2221 for (; depth > par->depth; --depth) {
2222 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2223 environment_stack[depth].erase();
2226 // write opening SGML tags
2227 switch (style.latextype) {
2228 case LATEX_PARAGRAPH:
2229 if (depth == par->depth
2230 && !environment_stack[depth].empty()) {
2231 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2232 environment_stack[depth].erase();
2238 sgmlOpenTag(ofs, depth, style.latexname());
2243 LinuxDocError(par, 0,
2244 _("Error : Wrong depth for"
2245 " LatexType Command.\n"));
2247 if (!environment_stack[depth].empty()){
2248 sgmlCloseTag(ofs, depth,
2249 environment_stack[depth]);
2253 environment_stack[depth].erase();
2254 sgmlOpenTag(ofs, depth, style.latexname());
2257 case LATEX_ENVIRONMENT:
2258 case LATEX_ITEM_ENVIRONMENT:
2259 if (depth == par->depth
2260 && environment_stack[depth] != style.latexname()
2261 && !environment_stack[depth].empty()) {
2263 sgmlCloseTag(ofs, depth,
2264 environment_stack[depth]);
2265 environment_stack[depth].erase();
2267 if (depth < par->depth) {
2269 environment_stack[depth].erase();
2271 if (environment_stack[depth] != style.latexname()) {
2273 string const temp = "p";
2274 sgmlOpenTag(ofs, depth, temp);
2276 environment_stack[depth] = style.latexname();
2277 sgmlOpenTag(ofs, depth,
2278 environment_stack[depth]);
2280 if (style.latextype == LATEX_ENVIRONMENT) break;
2282 desc_on = (style.labeltype == LABEL_MANUAL);
2289 sgmlOpenTag(ofs, depth + 1, item_name);
2292 sgmlOpenTag(ofs, depth, style.latexname());
2299 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2303 linuxDocHandleFootnote(ofs, par, depth);
2305 while(par && par->IsDummy());
2309 // write closing SGML tags
2310 switch (style.latextype) {
2312 case LATEX_ENVIRONMENT:
2313 case LATEX_ITEM_ENVIRONMENT:
2316 sgmlCloseTag(ofs, depth, style.latexname());
2322 for (; depth > 0; --depth)
2323 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2325 if (!environment_stack[depth].empty())
2326 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2330 sgmlCloseTag(ofs, 0, top_element);
2334 // How to check for successful close
2339 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2342 string const tag = "footnote";
2344 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2345 sgmlOpenTag(os, depth + 1, tag);
2346 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2347 sgmlCloseTag(os, depth + 1, tag);
2354 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2355 int depth, int desc_on,
2356 LyXParagraph * & par)
2358 LyXParagraph * tpar = par;
2361 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2363 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2367 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2368 "Caption").second) {
2369 sgmlOpenTag(os, depth + 1, inner_tag);
2371 SimpleDocBookOnePar(os, extra_par, tpar,
2372 desc_on, depth + 2);
2373 sgmlCloseTag(os, depth+1, inner_tag);
2374 if (!extra_par.empty())
2381 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2384 string tag, inner_tag;
2385 string tmp_par, extra_par;
2386 bool inner_span = false;
2389 // Someone should give this enum a proper name (Lgb)
2397 SOME_ENUM last = NO_ONE;
2398 SOME_ENUM present = FOOTNOTE_LIKE;
2400 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2401 if (last == present) {
2403 if (!tmp_par.empty()) {
2406 sgmlCloseTag(os, depth + 1, inner_tag);
2407 sgmlOpenTag(os, depth + 1, inner_tag);
2414 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2416 if (!extra_par.empty()) os << extra_par;
2417 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2420 switch (par->footnotekind) {
2421 case LyXParagraph::FOOTNOTE:
2422 case LyXParagraph::ALGORITHM:
2425 present = FOOTNOTE_LIKE;
2428 case LyXParagraph::MARGIN:
2431 present = MARGIN_LIKE;
2434 case LyXParagraph::FIG:
2435 case LyXParagraph::WIDE_FIG:
2437 inner_tag = "title";
2441 case LyXParagraph::TAB:
2442 case LyXParagraph::WIDE_TAB:
2444 inner_tag = "title";
2449 sgmlOpenTag(os, depth, tag);
2450 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2451 DocBookHandleCaption(os, inner_tag, depth,
2455 sgmlOpenTag(os, depth + 1, inner_tag);
2458 // ignore all caption here, we processed them above!!!
2459 if (par->layout != textclasslist
2460 .NumberOfLayout(params.textclass,
2461 "Caption").second) {
2462 std::ostringstream ost;
2463 SimpleDocBookOnePar(ost, extra_par, par,
2464 desc_on, depth + 2);
2465 tmp_par += ost.str().c_str();
2467 tmp_par = frontStrip(strip(tmp_par));
2473 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2474 if (!extra_par.empty()) os << extra_par;
2475 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2480 // push a tag in a style stack
2481 void Buffer::push_tag(ostream & os, string const & tag,
2482 int & pos, char stack[5][3])
2484 #ifdef WITH_WARNINGS
2485 #warning Use a real stack! (Lgb)
2487 // pop all previous tags
2488 for (int j = pos; j >= 0; --j)
2489 os << "</" << stack[j] << ">";
2492 sprintf(stack[++pos], "%s", tag.c_str());
2495 for (int i = 0; i <= pos; ++i)
2496 os << "<" << stack[i] << ">";
2500 void Buffer::pop_tag(ostream & os, string const & tag,
2501 int & pos, char stack[5][3])
2503 #ifdef WITH_WARNINGS
2504 #warning Use a real stack! (Lgb)
2506 // Please, Lars, do not remove the global variable. I already
2507 // had to reintroduce it twice! (JMarc)
2508 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2512 // pop all tags till specified one
2513 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2514 os << "</" << stack[j] << ">";
2517 os << "</" << tag << ">";
2519 // push all tags, but the specified one
2520 for (j = j + 1; j <= pos; ++j) {
2521 os << "<" << stack[j] << ">";
2522 strcpy(stack[j - 1], stack[j]);
2526 // pop all tags till specified one
2528 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2529 os << "</" << stack[j] << ">";
2532 os << "</" << tag << ">";
2534 // push all tags, but the specified one
2535 for (int i = j + 1; i <= pos; ++i) {
2536 os << "<" << stack[i] << ">";
2537 strcpy(stack[i - 1], stack[i]);
2544 // Handle internal paragraph parsing -- layout already processed.
2546 // checks, if newcol chars should be put into this line
2547 // writes newline, if necessary.
2549 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2550 string::size_type newcol)
2553 if (colcount > lyxrc.ascii_linelen) {
2555 colcount = newcol; // assume write after this call
2560 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2561 int desc_on, int /*depth*/)
2566 LyXParagraph::size_type main_body;
2568 LyXLayout const & style = textclasslist.Style(params.textclass,
2571 char family_type = 0; // family font flag
2572 bool is_bold = false; // series font flag
2573 char shape_type = 0; // shape font flag
2574 bool is_em = false; // emphasis (italic) font flag
2576 int stack_num = -1; // style stack position
2577 // Can this be rewritten to use a std::stack, please. (Lgb)
2578 char stack[5][3]; // style stack
2579 string::size_type char_line_count = 5; // Heuristic choice ;-)
2581 if (style.labeltype != LABEL_MANUAL)
2584 main_body = par->BeginningOfMainBody();
2586 // gets paragraph main font
2588 font1 = style.labelfont;
2593 // parsing main loop
2594 for (LyXParagraph::size_type i = 0;
2595 i < par->size(); ++i) {
2607 LyXFont const font2 = par->getFont(params, i);
2609 if (font1.family() != font2.family()) {
2610 switch (family_type) {
2612 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2613 push_tag(os, "tt", stack_num, stack);
2616 else if (font2.family() == LyXFont::SANS_FAMILY) {
2617 push_tag(os, "sf", stack_num, stack);
2622 pop_tag(os, "tt", stack_num, stack);
2623 if (font2.family() == LyXFont::SANS_FAMILY) {
2624 push_tag(os, "sf", stack_num, stack);
2631 pop_tag(os, "sf", stack_num, stack);
2632 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2633 push_tag(os, "tt", stack_num, stack);
2642 if (font1.series() != font2.series()) {
2643 if (font2.series() == LyXFont::BOLD_SERIES) {
2644 push_tag(os, "bf", stack_num, stack);
2646 } else if (is_bold) {
2647 pop_tag(os, "bf", stack_num, stack);
2652 // handle italic and slanted fonts
2653 if (font1.shape() != font2.shape()) {
2654 switch (shape_type) {
2656 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2657 push_tag(os, "it", stack_num, stack);
2659 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2660 push_tag(os, "sl", stack_num, stack);
2665 pop_tag(os, "it", stack_num, stack);
2666 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2667 push_tag(os, "sl", stack_num, stack);
2674 pop_tag(os, "sl", stack_num, stack);
2675 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2676 push_tag(os, "it", stack_num, stack);
2684 if (font1.emph() != font2.emph()) {
2685 if (font2.emph() == LyXFont::ON) {
2686 push_tag(os, "em", stack_num, stack);
2689 pop_tag(os, "em", stack_num, stack);
2694 c = par->GetChar(i);
2696 if (c == LyXParagraph::META_INSET) {
2697 inset = par->GetInset(i);
2698 inset->Linuxdoc(this, os);
2701 if (font2.latex() == LyXFont::ON) {
2702 // "TeX"-Mode on == > SGML-Mode on.
2704 os << c; // see LaTeX-Generation...
2708 if (par->linuxDocConvertChar(c, sgml_string)
2709 && !style.free_spacing) { // in freespacing
2711 // non-breaking characters
2715 linux_doc_line_break(os, char_line_count, 6);
2719 linux_doc_line_break(os, char_line_count, 1);
2724 char_line_count += sgml_string.length();
2730 // needed if there is an optional argument but no contents
2731 if (main_body > 0 && main_body == par->size()) {
2735 // pop all defined Styles
2736 for (j = stack_num; j >= 0; --j) {
2737 linux_doc_line_break(os,
2739 3 + strlen(stack[j]));
2740 os << "</" << stack[j] << ">";
2743 // resets description flag correctly
2746 // <tag> not closed...
2747 linux_doc_line_break(os, char_line_count, 6);
2751 // fprintf(file, "</p>");
2757 // Print an error message.
2758 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2759 string const & message)
2761 // insert an error marker in text
2762 InsetError * new_inset = new InsetError(message);
2763 par->InsertInset(pos, new_inset);
2766 // This constant defines the maximum number of
2767 // environment layouts that can be nesteded.
2768 // The same applies for command layouts.
2769 // These values should be more than enough.
2770 // José Matos (1999/07/22)
2772 enum { MAX_NEST_LEVEL = 25};
2774 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2776 LyXParagraph * par = paragraph;
2778 niceFile = nice; // this will be used by Insetincludes.
2780 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2781 // Please use a real stack.
2782 string environment_stack[MAX_NEST_LEVEL];
2783 string environment_inner[MAX_NEST_LEVEL];
2784 // Please use a real stack.
2785 string command_stack[MAX_NEST_LEVEL];
2786 bool command_flag= false;
2787 int command_depth= 0, command_base= 0, cmd_depth= 0;
2789 string item_name, command_name;
2790 string c_depth, c_params, tmps;
2792 int depth = 0; // paragraph depth
2793 LyXTextClass const & tclass =
2794 textclasslist.TextClass(params.textclass);
2796 LaTeXFeatures features(params, tclass.numLayouts());
2800 tex_code_break_column = lyxrc.ascii_linelen;
2802 //tex_code_break_column = 0;
2804 ofstream ofs(fname.c_str());
2806 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2813 string sgml_includedfiles=features.getIncludedFiles(fname);
2815 ofs << "<!doctype " << top_element
2816 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2818 if (params.preamble.empty() && sgml_includedfiles.empty())
2821 ofs << "\n [ " << params.preamble
2822 << sgml_includedfiles << " \n]>\n\n";
2825 if (params.options.empty())
2826 sgmlOpenTag(ofs, 0, top_element);
2828 string top = top_element;
2830 top += params.options;
2831 sgmlOpenTag(ofs, 0, top);
2834 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2835 << "\n See http://www.lyx.org/ for more information -->\n";
2838 int desc_on = 0; // description mode
2839 LyXLayout const & style =
2840 textclasslist.Style(params.textclass,
2843 // environment tag closing
2844 for (; depth > par->depth; --depth) {
2845 if (environment_inner[depth] != "!-- --") {
2846 item_name= "listitem";
2847 sgmlCloseTag(ofs, command_depth + depth,
2849 if (environment_inner[depth] == "varlistentry")
2850 sgmlCloseTag(ofs, depth+command_depth,
2851 environment_inner[depth]);
2853 sgmlCloseTag(ofs, depth + command_depth,
2854 environment_stack[depth]);
2855 environment_stack[depth].erase();
2856 environment_inner[depth].erase();
2859 if (depth == par->depth
2860 && environment_stack[depth] != style.latexname()
2861 && !environment_stack[depth].empty()) {
2862 if (environment_inner[depth] != "!-- --") {
2863 item_name= "listitem";
2864 sgmlCloseTag(ofs, command_depth+depth,
2866 if (environment_inner[depth] == "varlistentry")
2868 depth + command_depth,
2869 environment_inner[depth]);
2872 sgmlCloseTag(ofs, depth + command_depth,
2873 environment_stack[depth]);
2875 environment_stack[depth].erase();
2876 environment_inner[depth].erase();
2879 // Write opening SGML tags.
2880 switch (style.latextype) {
2881 case LATEX_PARAGRAPH:
2882 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2887 LinuxDocError(par, 0,
2888 _("Error : Wrong depth for "
2889 "LatexType Command.\n"));
2891 command_name = style.latexname();
2893 tmps = style.latexparam();
2894 c_params = split(tmps, c_depth,'|');
2896 cmd_depth= lyx::atoi(c_depth);
2899 if (cmd_depth<command_base) {
2900 for (int j = command_depth;
2901 j >= command_base; --j)
2902 if (!command_stack[j].empty())
2903 sgmlCloseTag(ofs, j, command_stack[j]);
2904 command_depth= command_base= cmd_depth;
2905 } else if (cmd_depth <= command_depth) {
2906 for (int j = command_depth;
2907 j >= cmd_depth; --j)
2909 if (!command_stack[j].empty())
2910 sgmlCloseTag(ofs, j, command_stack[j]);
2911 command_depth= cmd_depth;
2913 command_depth= cmd_depth;
2915 command_depth = command_base = cmd_depth;
2916 command_flag = true;
2918 command_stack[command_depth]= command_name;
2920 // treat label as a special case for
2921 // more WYSIWYM handling.
2922 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2923 Inset * inset = par->GetInset(0);
2924 Inset::Code lyx_code = inset->LyxCode();
2925 if (lyx_code == Inset::LABEL_CODE){
2926 command_name += " id=\"";
2927 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2928 command_name += "\"";
2933 sgmlOpenTag(ofs, depth + command_depth, command_name);
2934 item_name = "title";
2935 if (command_name != "!-- --")
2936 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2939 case LATEX_ENVIRONMENT:
2940 case LATEX_ITEM_ENVIRONMENT:
2941 if (depth < par->depth) {
2943 environment_stack[depth].erase();
2946 if (environment_stack[depth] != style.latexname()) {
2947 environment_stack[depth] = style.latexname();
2948 environment_inner[depth] = "!-- --";
2949 sgmlOpenTag(ofs, depth + command_depth,
2950 environment_stack[depth]);
2952 if (environment_inner[depth] != "!-- --") {
2953 item_name= "listitem";
2955 command_depth + depth,
2957 if (environment_inner[depth] == "varlistentry")
2959 depth + command_depth,
2960 environment_inner[depth]);
2964 if (style.latextype == LATEX_ENVIRONMENT) {
2965 if (!style.latexparam().empty())
2966 sgmlOpenTag(ofs, depth + command_depth,
2967 style.latexparam());
2971 desc_on = (style.labeltype == LABEL_MANUAL);
2974 environment_inner[depth]= "varlistentry";
2976 environment_inner[depth]= "listitem";
2978 sgmlOpenTag(ofs, depth + 1 + command_depth,
2979 environment_inner[depth]);
2983 sgmlOpenTag(ofs, depth + 1 + command_depth,
2987 sgmlOpenTag(ofs, depth + 1 + command_depth,
2992 sgmlOpenTag(ofs, depth + command_depth,
3001 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3002 depth + 1 + command_depth);
3005 DocBookHandleFootnote(ofs, par,
3006 depth + 1 + command_depth);
3008 while(par && par->IsDummy());
3011 // write closing SGML tags
3012 switch (style.latextype) {
3015 if (command_name != "!-- --")
3016 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3018 case LATEX_ENVIRONMENT:
3019 if (!style.latexparam().empty())
3020 sgmlCloseTag(ofs, depth + command_depth,
3021 style.latexparam());
3023 case LATEX_ITEM_ENVIRONMENT:
3024 if (desc_on == 1) break;
3026 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3028 case LATEX_PARAGRAPH:
3029 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3032 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3038 for (; depth >= 0; --depth) {
3039 if (!environment_stack[depth].empty()) {
3040 if (environment_inner[depth] != "!-- --") {
3041 item_name= "listitem";
3042 sgmlCloseTag(ofs, command_depth + depth,
3044 if (environment_inner[depth] == "varlistentry")
3045 sgmlCloseTag(ofs, depth + command_depth,
3046 environment_inner[depth]);
3049 sgmlCloseTag(ofs, depth + command_depth,
3050 environment_stack[depth]);
3054 for (int j = command_depth; j >= command_base; --j)
3055 if (!command_stack[j].empty())
3056 sgmlCloseTag(ofs, j, command_stack[j]);
3059 sgmlCloseTag(ofs, 0, top_element);
3062 // How to check for successful close
3066 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3067 LyXParagraph * par, int & desc_on,
3070 bool emph_flag = false;
3072 LyXLayout const & style = textclasslist.Style(params.textclass,
3075 LyXParagraph::size_type main_body;
3076 if (style.labeltype != LABEL_MANUAL)
3079 main_body = par->BeginningOfMainBody();
3081 // gets paragraph main font
3082 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3084 int char_line_count = depth;
3085 if (!style.free_spacing)
3086 for (int j = 0; j < depth; ++j)
3089 // parsing main loop
3090 for (LyXParagraph::size_type i = 0;
3091 i < par->size(); ++i) {
3092 LyXFont font2 = par->getFont(params, i);
3094 // handle <emphasis> tag
3095 if (font1.emph() != font2.emph() && i) {
3096 if (font2.emph() == LyXFont::ON) {
3100 os << "</emphasis>";
3105 char c = par->GetChar(i);
3107 if (c == LyXParagraph::META_INSET) {
3108 Inset * inset = par->GetInset(i);
3109 std::ostringstream ost;
3110 inset->DocBook(this, ost);
3111 string tmp_out = ost.str().c_str();
3114 // This code needs some explanation:
3115 // Two insets are treated specially
3116 // label if it is the first element in a command paragraph
3118 // graphics inside tables or figure floats can't go on
3119 // title (the equivalente in latex for this case is caption
3120 // and title should come first
3123 if (desc_on!= 3 || i!= 0) {
3124 if (!tmp_out.empty() && tmp_out[0] == '@') {
3126 extra += frontStrip(tmp_out, '@');
3128 os << frontStrip(tmp_out, '@');
3133 } else if (font2.latex() == LyXFont::ON) {
3134 // "TeX"-Mode on ==> SGML-Mode on.
3140 if (par->linuxDocConvertChar(c, sgml_string)
3141 && !style.free_spacing) { // in freespacing
3143 // non-breaking characters
3147 os << "\n</term><listitem><para>";
3159 // needed if there is an optional argument but no contents
3160 if (main_body > 0 && main_body == par->size()) {
3164 os << "</emphasis>";
3167 // resets description flag correctly
3170 // <term> not closed...
3178 // This should be enabled when the Chktex class is implemented. (Asger)
3179 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3180 // Other flags: -wall -v0 -x
3181 int Buffer::runChktex()
3183 if (!users->text) return 0;
3185 ProhibitInput(users);
3187 // get LaTeX-Filename
3188 string const name = getLatexName();
3189 string path = OnlyPath(filename);
3191 string const org_path = path;
3192 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3196 Path p(path); // path to LaTeX file
3197 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3199 // Remove all error insets
3200 bool const removedErrorInsets = users->removeAutoInsets();
3202 // Generate the LaTeX file if neccessary
3203 makeLaTeXFile(name, org_path, false);
3206 Chktex chktex(lyxrc.chktex_command, name, filepath);
3207 int res = chktex.run(terr); // run chktex
3210 WriteAlert(_("chktex did not work!"),
3211 _("Could not run with file:"), name);
3212 } else if (res > 0) {
3213 // Insert all errors as errors boxes
3214 users->insertErrors(terr);
3217 // if we removed error insets before we ran chktex or if we inserted
3218 // error insets after we ran chktex, this must be run:
3219 if (removedErrorInsets || res){
3221 users->fitCursor(users->text);
3229 void Buffer::validate(LaTeXFeatures & features) const
3231 LyXParagraph * par = paragraph;
3232 LyXTextClass const & tclass =
3233 textclasslist.TextClass(params.textclass);
3235 // AMS Style is at document level
3237 features.amsstyle = (params.use_amsmath ||
3238 tclass.provides(LyXTextClass::amsmath));
3241 // We don't use "lyxerr.debug" because of speed. (Asger)
3242 if (lyxerr.debugging(Debug::LATEX))
3243 lyxerr << "Paragraph: " << par << endl;
3245 // Now just follow the list of paragraphs and run
3246 // validate on each of them.
3247 par->validate(features);
3249 // and then the next paragraph
3253 // the bullet shapes are buffer level not paragraph level
3254 // so they are tested here
3255 for (int i = 0; i < 4; ++i) {
3256 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3257 int const font = params.user_defined_bullets[i].getFont();
3259 int const c = params
3260 .user_defined_bullets[i]
3267 features.latexsym = true;
3269 } else if (font == 1) {
3270 features.amssymb = true;
3271 } else if ((font >= 2 && font <= 5)) {
3272 features.pifont = true;
3277 if (lyxerr.debugging(Debug::LATEX)) {
3278 features.showStruct();
3283 void Buffer::setPaperStuff()
3285 params.papersize = BufferParams::PAPER_DEFAULT;
3286 char const c1 = params.paperpackage;
3287 if (c1 == BufferParams::PACKAGE_NONE) {
3288 char const c2 = params.papersize2;
3289 if (c2 == BufferParams::VM_PAPER_USLETTER)
3290 params.papersize = BufferParams::PAPER_USLETTER;
3291 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3292 params.papersize = BufferParams::PAPER_LEGALPAPER;
3293 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3294 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3295 else if (c2 == BufferParams::VM_PAPER_A3)
3296 params.papersize = BufferParams::PAPER_A3PAPER;
3297 else if (c2 == BufferParams::VM_PAPER_A4)
3298 params.papersize = BufferParams::PAPER_A4PAPER;
3299 else if (c2 == BufferParams::VM_PAPER_A5)
3300 params.papersize = BufferParams::PAPER_A5PAPER;
3301 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3302 (c2 == BufferParams::VM_PAPER_B5))
3303 params.papersize = BufferParams::PAPER_B5PAPER;
3304 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3305 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3306 params.papersize = BufferParams::PAPER_A4PAPER;
3310 // This function should be in Buffer because it's a buffer's property (ale)
3311 string const Buffer::getIncludeonlyList(char delim)
3314 for (inset_iterator it = inset_iterator_begin();
3315 it != inset_iterator_end(); ++it) {
3316 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3317 InsetInclude * insetinc =
3318 static_cast<InsetInclude *>(*it);
3319 if (insetinc->isInclude()
3320 && insetinc->isNoLoad()) {
3323 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3327 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3332 vector<string> const Buffer::getLabelList()
3334 /// if this is a child document and the parent is already loaded
3335 /// Use the parent's list instead [ale990407]
3336 if (!params.parentname.empty()
3337 && bufferlist.exists(params.parentname)) {
3338 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3340 return tmp->getLabelList();
3343 vector<string> label_list;
3344 for (inset_iterator it = inset_iterator_begin();
3345 it != inset_iterator_end(); ++it) {
3346 vector<string> const l = (*it)->getLabelList();
3347 label_list.insert(label_list.end(), l.begin(), l.end());
3353 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3358 vector<vector<TocItem> > l(4);
3359 LyXParagraph * par = paragraph;
3362 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3363 if (textclasslist.Style(params.textclass,
3364 par->GetLayout()).labeltype
3365 == LABEL_SENSITIVE) {
3369 tmp.str = par->String(this, false);
3370 switch (par->footnotekind) {
3371 case LyXParagraph::FIG:
3372 case LyXParagraph::WIDE_FIG:
3373 tmp.str = tostr(++figs) + ". "
3375 l[TOC_LOF].push_back(tmp);
3377 case LyXParagraph::TAB:
3378 case LyXParagraph::WIDE_TAB:
3379 tmp.str = tostr(++tables) + ". "
3381 l[TOC_LOT].push_back(tmp);
3383 case LyXParagraph::ALGORITHM:
3384 tmp.str = tostr(++algs) + ". "
3386 l[TOC_LOA].push_back(tmp);
3388 case LyXParagraph::FOOTNOTE:
3389 case LyXParagraph::MARGIN:
3393 } else if (!par->IsDummy()) {
3395 char const labeltype =
3396 textclasslist.Style(params.textclass,
3397 par->GetLayout()).labeltype;
3399 if (labeltype >= LABEL_COUNTER_CHAPTER
3400 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3401 // insert this into the table of contents
3406 textclasslist.TextClass(params.textclass).maxcounter());
3407 tmp.str = par->String(this, true);
3408 l[TOC_TOC].push_back(tmp);
3419 // This is also a buffer property (ale)
3420 vector<pair<string,string> > const Buffer::getBibkeyList()
3422 /// if this is a child document and the parent is already loaded
3423 /// Use the parent's list instead [ale990412]
3424 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3425 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3427 return tmp->getBibkeyList();
3430 vector<pair<string, string> > keys;
3431 LyXParagraph * par = paragraph;
3434 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3435 par->String(this, false)));
3439 // Might be either using bibtex or a child has bibliography
3441 for (inset_iterator it = inset_iterator_begin();
3442 it != inset_iterator_end(); ++it) {
3443 // Search for Bibtex or Include inset
3444 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3445 vector<pair<string,string> > tmp =
3446 static_cast<InsetBibtex*>(*it)->getKeys(this);
3447 keys.insert(keys.end(), tmp.begin(), tmp.end());
3448 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3449 vector<pair<string,string> > const tmp =
3450 static_cast<InsetInclude*>(*it)->getKeys();
3451 keys.insert(keys.end(), tmp.begin(), tmp.end());
3460 bool Buffer::isDepClean(string const & name) const
3462 DEPCLEAN * item = dep_clean;
3463 while (item && item->master != name)
3465 if (!item) return true;
3470 void Buffer::markDepClean(string const & name)
3473 dep_clean = new DEPCLEAN;
3474 dep_clean->clean = true;
3475 dep_clean->master = name;
3476 dep_clean->next = 0;
3478 DEPCLEAN * item = dep_clean;
3479 while (item && item->master != name)
3484 item = new DEPCLEAN;
3486 item->master = name;
3493 bool Buffer::Dispatch(string const & command)
3495 // Split command string into command and argument
3497 string line = frontStrip(command);
3498 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3500 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3504 bool Buffer::Dispatch(int action, string const & argument)
3506 bool dispatched = true;
3509 Exporter::Export(this, argument, false);
3519 void Buffer::resize()
3521 /// resize the BufferViews!
3527 void Buffer::resizeInsets(BufferView * bv)
3529 /// then remove all LyXText in text-insets
3530 LyXParagraph * par = paragraph;
3531 for (; par; par = par->next) {
3532 par->resizeInsetsLyXText(bv);
3536 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3539 LyXParagraph * par = paragraph;
3541 par->ChangeLanguage(params, from, to);
3547 bool Buffer::isMultiLingual()
3549 LyXParagraph * par = paragraph;
3551 if (par->isMultiLingual(params))
3559 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3560 LyXParagraph::size_type pos)
3563 it = par->InsetIterator(pos);
3564 if (it == par->inset_iterator_end()) {
3571 void Buffer::inset_iterator::SetParagraph()
3574 it = par->inset_iterator_begin();
3575 if (it != par->inset_iterator_end())
3580 // We maintain an invariant that whenever par = 0 then it = 0