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;
1286 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1290 int ltype_depth = 0;
1291 unsigned int currlinelen = 0;
1292 bool ref_printed = false;
1298 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1302 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1306 /* begins a footnote environment ? */
1307 if (footnoteflag != par->footnoteflag) {
1308 footnoteflag = par->footnoteflag;
1310 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1311 if ((linelen > 0) &&
1312 ((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 string const 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 (strstr(tmp.c_str(), "ection")) {
1347 ltype_depth = depth+1;
1348 } else if (strstr(tmp.c_str(), "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;
1387 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1388 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1396 for (char j = 0; j < depth; ++j)
1398 currlinelen = depth * 2;
1400 case 0: /* Standard */
1401 case 4: /* (Sub)Paragraph */
1402 case 5: /* Description */
1404 case 6: /* Abstract */
1406 buffer << "Abstract\n\n";
1408 buffer << "Abstract: ";
1410 case 7: /* Bibliography */
1413 buffer << "References\n\n";
1415 buffer << "References: ";
1420 buffer << par->labelstring << " ";
1423 if (ltype_depth > depth) {
1424 for (char j = ltype_depth - 1; j > depth; --j)
1426 currlinelen += (ltype_depth-depth)*2;
1429 font2 = par->GetFontSettings(params, i);
1430 if (font1.latex() != font2.latex()) {
1431 if (font2.latex() == LyXFont::OFF)
1438 c = par->GetChar(i);
1442 case LyXParagraph::META_INSET:
1443 if ((inset = par->GetInset(i))) {
1444 if (!inset->Ascii(this, buffer)) {
1446 string s = rsplit(buffer.str().c_str(),
1448 currlinelen += s.length();
1450 // to be sure it breaks paragraph
1451 currlinelen += linelen;
1455 case LyXParagraph::META_NEWLINE:
1458 for (char j = 0; j < depth; ++j)
1461 currlinelen = depth * 2;
1462 if (ltype_depth > depth) {
1463 for (char j = ltype_depth;
1466 currlinelen += (ltype_depth - depth) * 2;
1469 case LyXParagraph::META_HFILL:
1476 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1477 (c == ' ') && ((i + 2) < par->size()))
1480 for (char j = 0; j < depth; ++j)
1482 currlinelen = depth * 2;
1483 if (ltype_depth > depth) {
1484 for (char j = ltype_depth;
1487 currlinelen += (ltype_depth-depth)*2;
1489 } else if (c != '\0')
1492 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1497 return buffer.str().c_str();
1501 void Buffer::writeFileAscii(string const & fname, int linelen)
1503 ofstream ofs(fname.c_str());
1505 WriteFSAlert(_("Error: Cannot write file:"), fname);
1508 writeFileAscii(ofs, linelen);
1512 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1514 LyXParagraph * par = paragraph;
1516 ofs << asciiParagraph(par, linelen);
1523 void Buffer::makeLaTeXFile(string const & fname,
1524 string const & original_path,
1525 bool nice, bool only_body)
1527 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1529 niceFile = nice; // this will be used by Insetincludes.
1531 tex_code_break_column = lyxrc.ascii_linelen;
1533 LyXTextClass const & tclass =
1534 textclasslist.TextClass(params.textclass);
1536 ofstream ofs(fname.c_str());
1538 WriteFSAlert(_("Error: Cannot open file: "), fname);
1542 // validate the buffer.
1543 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1544 LaTeXFeatures features(params, tclass.numLayouts());
1546 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1549 // The starting paragraph of the coming rows is the
1550 // first paragraph of the document. (Asger)
1551 texrow.start(paragraph, 0);
1553 if (!only_body && nice) {
1554 ofs << "%% " LYX_DOCVERSION " created this file. "
1555 "For more info, see http://www.lyx.org/.\n"
1556 "%% Do not edit unless you really know what "
1561 lyxerr.debug() << "lyx header finished" << endl;
1562 // There are a few differences between nice LaTeX and usual files:
1563 // usual is \batchmode and has a
1564 // special input@path to allow the including of figures
1565 // with either \input or \includegraphics (what figinsets do).
1566 // batchmode is not set if there is a tex_code_break_column.
1567 // In this case somebody is interested in the generated LaTeX,
1568 // so this is OK. input@path is set when the actual parameter
1569 // original_path is set. This is done for usual tex-file, but not
1570 // for nice-latex-file. (Matthias 250696)
1573 // code for usual, NOT nice-latex-file
1574 ofs << "\\batchmode\n"; // changed
1575 // from \nonstopmode
1578 if (!original_path.empty()) {
1579 ofs << "\\makeatletter\n"
1580 << "\\def\\input@path{{"
1581 << original_path << "/}}\n"
1582 << "\\makeatother\n";
1588 ofs << "\\documentclass";
1590 string options; // the document class options.
1592 if (tokenPos(tclass.opt_fontsize(),
1593 '|', params.fontsize) >= 0) {
1594 // only write if existing in list (and not default)
1595 options += params.fontsize;
1600 if (!params.use_geometry &&
1601 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1602 switch (params.papersize) {
1603 case BufferParams::PAPER_A4PAPER:
1604 options += "a4paper,";
1606 case BufferParams::PAPER_USLETTER:
1607 options += "letterpaper,";
1609 case BufferParams::PAPER_A5PAPER:
1610 options += "a5paper,";
1612 case BufferParams::PAPER_B5PAPER:
1613 options += "b5paper,";
1615 case BufferParams::PAPER_EXECUTIVEPAPER:
1616 options += "executivepaper,";
1618 case BufferParams::PAPER_LEGALPAPER:
1619 options += "legalpaper,";
1625 if (params.sides != tclass.sides()) {
1626 switch (params.sides) {
1627 case LyXTextClass::OneSide:
1628 options += "oneside,";
1630 case LyXTextClass::TwoSides:
1631 options += "twoside,";
1638 if (params.columns != tclass.columns()) {
1639 if (params.columns == 2)
1640 options += "twocolumn,";
1642 options += "onecolumn,";
1645 if (!params.use_geometry
1646 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1647 options += "landscape,";
1649 // language should be a parameter to \documentclass
1650 bool use_babel = false;
1651 if (params.language->babel() == "hebrew") // This seems necessary
1652 features.UsedLanguages.insert(default_language);
1653 #ifdef DO_USE_DEFAULT_LANGUAGE
1654 if (params.language->lang() != "default" ||
1655 !features.UsedLanguages.empty()) {
1658 for (LaTeXFeatures::LanguageList::const_iterator cit =
1659 features.UsedLanguages.begin();
1660 cit != features.UsedLanguages.end(); ++cit)
1661 options += (*cit)->babel() + ",";
1662 options += params.language->babel() + ',';
1663 #ifdef DO_USE_DEFAULT_LANGUAGE
1667 // the user-defined options
1668 if (!params.options.empty()) {
1669 options += params.options + ',';
1672 if (!options.empty()){
1673 options = strip(options, ',');
1674 ofs << '[' << options << ']';
1678 << textclasslist.LatexnameOfClass(params.textclass)
1681 // end of \documentclass defs
1683 // font selection must be done before loading fontenc.sty
1684 if (params.fonts != "default") {
1685 ofs << "\\usepackage{" << params.fonts << "}\n";
1688 // this one is not per buffer
1689 if (lyxrc.fontenc != "default") {
1690 ofs << "\\usepackage[" << lyxrc.fontenc
1695 if (params.inputenc == "auto") {
1696 string const doc_encoding =
1697 params.language->encoding()->LatexName();
1699 // Create a list with all the input encodings used
1701 set<string> encodings;
1702 for (LaTeXFeatures::LanguageList::const_iterator it =
1703 features.UsedLanguages.begin();
1704 it != features.UsedLanguages.end(); ++it)
1705 if ((*it)->encoding()->LatexName() != doc_encoding)
1706 encodings.insert((*it)->encoding()->LatexName());
1708 ofs << "\\usepackage[";
1709 std::copy(encodings.begin(), encodings.end(),
1710 std::ostream_iterator<string>(ofs, ","));
1711 ofs << doc_encoding << "]{inputenc}\n";
1713 } else if (params.inputenc != "default") {
1714 ofs << "\\usepackage[" << params.inputenc
1719 // At the very beginning the text parameters.
1720 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1721 switch (params.paperpackage) {
1722 case BufferParams::PACKAGE_A4:
1723 ofs << "\\usepackage{a4}\n";
1726 case BufferParams::PACKAGE_A4WIDE:
1727 ofs << "\\usepackage{a4wide}\n";
1730 case BufferParams::PACKAGE_WIDEMARGINSA4:
1731 ofs << "\\usepackage[widemargins]{a4}\n";
1736 if (params.use_geometry) {
1737 ofs << "\\usepackage{geometry}\n";
1739 ofs << "\\geometry{verbose";
1740 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1741 ofs << ",landscape";
1742 switch (params.papersize2) {
1743 case BufferParams::VM_PAPER_CUSTOM:
1744 if (!params.paperwidth.empty())
1745 ofs << ",paperwidth="
1746 << params.paperwidth;
1747 if (!params.paperheight.empty())
1748 ofs << ",paperheight="
1749 << params.paperheight;
1751 case BufferParams::VM_PAPER_USLETTER:
1752 ofs << ",letterpaper";
1754 case BufferParams::VM_PAPER_USLEGAL:
1755 ofs << ",legalpaper";
1757 case BufferParams::VM_PAPER_USEXECUTIVE:
1758 ofs << ",executivepaper";
1760 case BufferParams::VM_PAPER_A3:
1763 case BufferParams::VM_PAPER_A4:
1766 case BufferParams::VM_PAPER_A5:
1769 case BufferParams::VM_PAPER_B3:
1772 case BufferParams::VM_PAPER_B4:
1775 case BufferParams::VM_PAPER_B5:
1779 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1780 switch (lyxrc.default_papersize) {
1781 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1782 case BufferParams::PAPER_USLETTER:
1783 ofs << ",letterpaper";
1785 case BufferParams::PAPER_LEGALPAPER:
1786 ofs << ",legalpaper";
1788 case BufferParams::PAPER_EXECUTIVEPAPER:
1789 ofs << ",executivepaper";
1791 case BufferParams::PAPER_A3PAPER:
1794 case BufferParams::PAPER_A4PAPER:
1797 case BufferParams::PAPER_A5PAPER:
1800 case BufferParams::PAPER_B5PAPER:
1805 if (!params.topmargin.empty())
1806 ofs << ",tmargin=" << params.topmargin;
1807 if (!params.bottommargin.empty())
1808 ofs << ",bmargin=" << params.bottommargin;
1809 if (!params.leftmargin.empty())
1810 ofs << ",lmargin=" << params.leftmargin;
1811 if (!params.rightmargin.empty())
1812 ofs << ",rmargin=" << params.rightmargin;
1813 if (!params.headheight.empty())
1814 ofs << ",headheight=" << params.headheight;
1815 if (!params.headsep.empty())
1816 ofs << ",headsep=" << params.headsep;
1817 if (!params.footskip.empty())
1818 ofs << ",footskip=" << params.footskip;
1822 if (params.use_amsmath
1823 && !tclass.provides(LyXTextClass::amsmath)) {
1824 ofs << "\\usepackage{amsmath}\n";
1828 if (tokenPos(tclass.opt_pagestyle(),
1829 '|', params.pagestyle) >= 0) {
1830 if (params.pagestyle == "fancy") {
1831 ofs << "\\usepackage{fancyhdr}\n";
1834 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1838 // We try to load babel late, in case it interferes
1839 // with other packages.
1841 ofs << lyxrc.language_package << endl;
1845 if (params.secnumdepth != tclass.secnumdepth()) {
1846 ofs << "\\setcounter{secnumdepth}{"
1847 << params.secnumdepth
1851 if (params.tocdepth != tclass.tocdepth()) {
1852 ofs << "\\setcounter{tocdepth}{"
1858 if (params.paragraph_separation) {
1859 switch (params.defskip.kind()) {
1860 case VSpace::SMALLSKIP:
1861 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1863 case VSpace::MEDSKIP:
1864 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1866 case VSpace::BIGSKIP:
1867 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1869 case VSpace::LENGTH:
1870 ofs << "\\setlength\\parskip{"
1871 << params.defskip.length().asLatexString()
1874 default: // should never happen // Then delete it.
1875 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1880 ofs << "\\setlength\\parindent{0pt}\n";
1884 // Now insert the LyX specific LaTeX commands...
1886 // The optional packages;
1887 string preamble(features.getPackages());
1889 // this might be useful...
1890 preamble += "\n\\makeatletter\n";
1892 // Some macros LyX will need
1893 string tmppreamble(features.getMacros());
1895 if (!tmppreamble.empty()) {
1896 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1897 "LyX specific LaTeX commands.\n"
1898 + tmppreamble + '\n';
1901 // the text class specific preamble
1902 tmppreamble = features.getTClassPreamble();
1903 if (!tmppreamble.empty()) {
1904 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1905 "Textclass specific LaTeX commands.\n"
1906 + tmppreamble + '\n';
1909 /* the user-defined preamble */
1910 if (!params.preamble.empty()) {
1911 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1912 "User specified LaTeX commands.\n"
1913 + params.preamble + '\n';
1916 preamble += "\\makeatother\n";
1918 // Itemize bullet settings need to be last in case the user
1919 // defines their own bullets that use a package included
1920 // in the user-defined preamble -- ARRae
1921 // Actually it has to be done much later than that
1922 // since some packages like frenchb make modifications
1923 // at \begin{document} time -- JMarc
1925 for (int i = 0; i < 4; ++i) {
1926 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1927 if (bullets_def.empty())
1928 bullets_def="\\AtBeginDocument{\n";
1929 bullets_def += " \\renewcommand{\\labelitemi";
1931 // `i' is one less than the item to modify
1938 bullets_def += "ii";
1944 bullets_def += "}{" +
1945 params.user_defined_bullets[i].getText()
1950 if (!bullets_def.empty())
1951 preamble += bullets_def + "}\n\n";
1953 for (int j = countChar(preamble, '\n'); j-- ;) {
1960 ofs << "\\begin{document}\n";
1963 lyxerr.debug() << "preamble finished, now the body." << endl;
1964 #ifdef DO_USE_DEFAULT_LANGUAGE
1965 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
1967 if (!lyxrc.language_auto_begin) {
1969 ofs << subst(lyxrc.language_command_begin, "$$lang",
1970 params.language->babel())
1975 latexParagraphs(ofs, paragraph, 0, texrow);
1977 // add this just in case after all the paragraphs
1981 #ifdef DO_USE_DEFAULT_LANGUAGE
1982 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
1984 if (!lyxrc.language_auto_end) {
1986 ofs << subst(lyxrc.language_command_end, "$$lang",
1987 params.language->babel())
1993 ofs << "\\end{document}\n";
1996 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1998 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2002 // Just to be sure. (Asger)
2005 // tex_code_break_column's value is used to decide
2006 // if we are in batchmode or not (within mathed_write()
2007 // in math_write.C) so we must set it to a non-zero
2008 // value when we leave otherwise we save incorrect .lyx files.
2009 tex_code_break_column = lyxrc.ascii_linelen;
2013 lyxerr << "File was not closed properly." << endl;
2016 lyxerr.debug() << "Finished making latex file." << endl;
2021 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2023 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2024 LyXParagraph * endpar, TexRow & texrow) const
2026 bool was_title = false;
2027 bool already_title = false;
2028 std::ostringstream ftnote;
2033 while (par != endpar) {
2036 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2039 LyXLayout const & layout =
2040 textclasslist.Style(params.textclass,
2043 if (layout.intitle) {
2044 if (already_title) {
2045 lyxerr <<"Error in latexParagraphs: You"
2046 " should not mix title layouts"
2047 " with normal ones." << endl;
2050 } else if (was_title && !already_title) {
2051 ofs << "\\maketitle\n";
2053 already_title = true;
2056 // We are at depth 0 so we can just use
2057 // ordinary \footnote{} generation
2058 // flag this with ftcount
2060 if (layout.isEnvironment()
2061 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2062 par = par->TeXEnvironment(this, params, ofs, texrow
2064 ,ftnote, ft_texrow, ftcount
2068 par = par->TeXOnePar(this, params, ofs, texrow, false
2071 ftnote, ft_texrow, ftcount
2076 // Write out what we've generated...
2079 ofs << "\\addtocounter{footnote}{-"
2083 ofs << ftnote.str();
2084 texrow += ft_texrow;
2086 // The extra .c_str() is needed when we use
2087 // lyxstring instead of the STL string class.
2088 ftnote.str(string().c_str());
2093 // It might be that we only have a title in this document
2094 if (was_title && !already_title) {
2095 ofs << "\\maketitle\n";
2101 bool Buffer::isLatex() const
2103 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2107 bool Buffer::isLinuxDoc() const
2109 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2113 bool Buffer::isLiterate() const
2115 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2119 bool Buffer::isDocBook() const
2121 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2125 bool Buffer::isSGML() const
2127 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2128 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2132 void Buffer::sgmlOpenTag(ostream & os, int depth,
2133 string const & latexname) const
2135 if (latexname != "!-- --")
2136 os << string(depth, ' ') << "<" << latexname << ">\n";
2140 void Buffer::sgmlCloseTag(ostream & os, int depth,
2141 string const & latexname) const
2143 if (latexname != "!-- --")
2144 os << string(depth, ' ') << "</" << latexname << ">\n";
2148 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2150 LyXParagraph * par = paragraph;
2152 niceFile = nice; // this will be used by Insetincludes.
2154 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2155 string environment_stack[10];
2158 int depth = 0; // paragraph depth
2160 ofstream ofs(fname.c_str());
2163 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2167 LyXTextClass const & tclass =
2168 textclasslist.TextClass(params.textclass);
2170 LaTeXFeatures features(params, tclass.numLayouts());
2174 tex_code_break_column = lyxrc.ascii_linelen;
2176 //tex_code_break_column = 0;
2181 string sgml_includedfiles=features.getIncludedFiles(fname);
2183 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2184 ofs << "<!doctype linuxdoc system>\n\n";
2186 ofs << "<!doctype linuxdoc system [ "
2187 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2190 if (params.options.empty())
2191 sgmlOpenTag(ofs, 0, top_element);
2193 string top = top_element;
2195 top += params.options;
2196 sgmlOpenTag(ofs, 0, top);
2200 ofs << "<!-- " << LYX_DOCVERSION
2201 << " created this file. For more info see http://www.lyx.org/"
2205 int desc_on = 0; // description mode
2206 LyXLayout const & style =
2207 textclasslist.Style(params.textclass,
2210 // treat <toc> as a special case for compatibility with old code
2211 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2212 Inset * inset = par->GetInset(0);
2213 Inset::Code lyx_code = inset->LyxCode();
2214 if (lyx_code == Inset::TOC_CODE){
2215 string const temp = "toc";
2216 sgmlOpenTag(ofs, depth, temp);
2220 linuxDocHandleFootnote(ofs, par, depth);
2226 // environment tag closing
2227 for (; depth > par->depth; --depth) {
2228 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2229 environment_stack[depth].erase();
2232 // write opening SGML tags
2233 switch (style.latextype) {
2234 case LATEX_PARAGRAPH:
2235 if (depth == par->depth
2236 && !environment_stack[depth].empty()) {
2237 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2238 environment_stack[depth].erase();
2244 sgmlOpenTag(ofs, depth, style.latexname());
2249 LinuxDocError(par, 0,
2250 _("Error : Wrong depth for"
2251 " LatexType Command.\n"));
2253 if (!environment_stack[depth].empty()){
2254 sgmlCloseTag(ofs, depth,
2255 environment_stack[depth]);
2259 environment_stack[depth].erase();
2260 sgmlOpenTag(ofs, depth, style.latexname());
2263 case LATEX_ENVIRONMENT:
2264 case LATEX_ITEM_ENVIRONMENT:
2265 if (depth == par->depth
2266 && environment_stack[depth] != style.latexname()
2267 && !environment_stack[depth].empty()) {
2269 sgmlCloseTag(ofs, depth,
2270 environment_stack[depth]);
2271 environment_stack[depth].erase();
2273 if (depth < par->depth) {
2275 environment_stack[depth].erase();
2277 if (environment_stack[depth] != style.latexname()) {
2279 string const temp = "p";
2280 sgmlOpenTag(ofs, depth, temp);
2282 environment_stack[depth] = style.latexname();
2283 sgmlOpenTag(ofs, depth,
2284 environment_stack[depth]);
2286 if (style.latextype == LATEX_ENVIRONMENT) break;
2288 desc_on = (style.labeltype == LABEL_MANUAL);
2295 sgmlOpenTag(ofs, depth + 1, item_name);
2298 sgmlOpenTag(ofs, depth, style.latexname());
2305 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2309 linuxDocHandleFootnote(ofs, par, depth);
2311 while(par && par->IsDummy());
2315 // write closing SGML tags
2316 switch (style.latextype) {
2318 case LATEX_ENVIRONMENT:
2319 case LATEX_ITEM_ENVIRONMENT:
2322 sgmlCloseTag(ofs, depth, style.latexname());
2328 for (; depth > 0; --depth)
2329 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2331 if (!environment_stack[depth].empty())
2332 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2336 sgmlCloseTag(ofs, 0, top_element);
2340 // How to check for successful close
2345 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2348 string const tag = "footnote";
2350 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2351 sgmlOpenTag(os, depth + 1, tag);
2352 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2353 sgmlCloseTag(os, depth + 1, tag);
2360 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2361 int depth, int desc_on,
2362 LyXParagraph * & par)
2364 LyXParagraph * tpar = par;
2367 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2369 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2373 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2374 "Caption").second) {
2375 sgmlOpenTag(os, depth + 1, inner_tag);
2377 SimpleDocBookOnePar(os, extra_par, tpar,
2378 desc_on, depth + 2);
2379 sgmlCloseTag(os, depth+1, inner_tag);
2380 if (!extra_par.empty())
2387 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2390 string tag, inner_tag;
2391 string tmp_par, extra_par;
2392 bool inner_span = false;
2395 // Someone should give this enum a proper name (Lgb)
2403 SOME_ENUM last = NO_ONE;
2404 SOME_ENUM present = FOOTNOTE_LIKE;
2406 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2407 if (last == present) {
2409 if (!tmp_par.empty()) {
2412 sgmlCloseTag(os, depth + 1, inner_tag);
2413 sgmlOpenTag(os, depth + 1, inner_tag);
2420 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2422 if (!extra_par.empty()) os << extra_par;
2423 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2426 switch (par->footnotekind) {
2427 case LyXParagraph::FOOTNOTE:
2428 case LyXParagraph::ALGORITHM:
2431 present = FOOTNOTE_LIKE;
2434 case LyXParagraph::MARGIN:
2437 present = MARGIN_LIKE;
2440 case LyXParagraph::FIG:
2441 case LyXParagraph::WIDE_FIG:
2443 inner_tag = "title";
2447 case LyXParagraph::TAB:
2448 case LyXParagraph::WIDE_TAB:
2450 inner_tag = "title";
2455 sgmlOpenTag(os, depth, tag);
2456 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2457 DocBookHandleCaption(os, inner_tag, depth,
2461 sgmlOpenTag(os, depth + 1, inner_tag);
2464 // ignore all caption here, we processed them above!!!
2465 if (par->layout != textclasslist
2466 .NumberOfLayout(params.textclass,
2467 "Caption").second) {
2468 std::ostringstream ost;
2469 SimpleDocBookOnePar(ost, extra_par, par,
2470 desc_on, depth + 2);
2471 tmp_par += ost.str().c_str();
2473 tmp_par = frontStrip(strip(tmp_par));
2479 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2480 if (!extra_par.empty()) os << extra_par;
2481 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2486 // push a tag in a style stack
2487 void Buffer::push_tag(ostream & os, string const & tag,
2488 int & pos, char stack[5][3])
2490 #ifdef WITH_WARNINGS
2491 #warning Use a real stack! (Lgb)
2493 // pop all previous tags
2494 for (int j = pos; j >= 0; --j)
2495 os << "</" << stack[j] << ">";
2498 sprintf(stack[++pos], "%s", tag.c_str());
2501 for (int i = 0; i <= pos; ++i)
2502 os << "<" << stack[i] << ">";
2506 void Buffer::pop_tag(ostream & os, string const & tag,
2507 int & pos, char stack[5][3])
2509 #ifdef WITH_WARNINGS
2510 #warning Use a real stack! (Lgb)
2512 // Please, Lars, do not remove the global variable. I already
2513 // had to reintroduce it twice! (JMarc)
2514 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2518 // pop all tags till specified one
2519 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2520 os << "</" << stack[j] << ">";
2523 os << "</" << tag << ">";
2525 // push all tags, but the specified one
2526 for (j = j + 1; j <= pos; ++j) {
2527 os << "<" << stack[j] << ">";
2528 strcpy(stack[j - 1], stack[j]);
2532 // pop all tags till specified one
2534 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2535 os << "</" << stack[j] << ">";
2538 os << "</" << tag << ">";
2540 // push all tags, but the specified one
2541 for (int i = j + 1; i <= pos; ++i) {
2542 os << "<" << stack[i] << ">";
2543 strcpy(stack[i - 1], stack[i]);
2550 // Handle internal paragraph parsing -- layout already processed.
2552 // checks, if newcol chars should be put into this line
2553 // writes newline, if necessary.
2555 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2556 string::size_type newcol)
2559 if (colcount > lyxrc.ascii_linelen) {
2561 colcount = newcol; // assume write after this call
2566 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2567 int desc_on, int /*depth*/)
2572 LyXParagraph::size_type main_body;
2574 LyXLayout const & style = textclasslist.Style(params.textclass,
2577 char family_type = 0; // family font flag
2578 bool is_bold = false; // series font flag
2579 char shape_type = 0; // shape font flag
2580 bool is_em = false; // emphasis (italic) font flag
2582 int stack_num = -1; // style stack position
2583 // Can this be rewritten to use a std::stack, please. (Lgb)
2584 char stack[5][3]; // style stack
2585 string::size_type char_line_count = 5; // Heuristic choice ;-)
2587 if (style.labeltype != LABEL_MANUAL)
2590 main_body = par->BeginningOfMainBody();
2592 // gets paragraph main font
2594 font1 = style.labelfont;
2599 // parsing main loop
2600 for (LyXParagraph::size_type i = 0;
2601 i < par->size(); ++i) {
2613 LyXFont const font2 = par->getFont(params, i);
2615 if (font1.family() != font2.family()) {
2616 switch (family_type) {
2618 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2619 push_tag(os, "tt", stack_num, stack);
2622 else if (font2.family() == LyXFont::SANS_FAMILY) {
2623 push_tag(os, "sf", stack_num, stack);
2628 pop_tag(os, "tt", stack_num, stack);
2629 if (font2.family() == LyXFont::SANS_FAMILY) {
2630 push_tag(os, "sf", stack_num, stack);
2637 pop_tag(os, "sf", stack_num, stack);
2638 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2639 push_tag(os, "tt", stack_num, stack);
2648 if (font1.series() != font2.series()) {
2649 if (font2.series() == LyXFont::BOLD_SERIES) {
2650 push_tag(os, "bf", stack_num, stack);
2652 } else if (is_bold) {
2653 pop_tag(os, "bf", stack_num, stack);
2658 // handle italic and slanted fonts
2659 if (font1.shape() != font2.shape()) {
2660 switch (shape_type) {
2662 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2663 push_tag(os, "it", stack_num, stack);
2665 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2666 push_tag(os, "sl", stack_num, stack);
2671 pop_tag(os, "it", stack_num, stack);
2672 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2673 push_tag(os, "sl", stack_num, stack);
2680 pop_tag(os, "sl", stack_num, stack);
2681 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2682 push_tag(os, "it", stack_num, stack);
2690 if (font1.emph() != font2.emph()) {
2691 if (font2.emph() == LyXFont::ON) {
2692 push_tag(os, "em", stack_num, stack);
2695 pop_tag(os, "em", stack_num, stack);
2700 c = par->GetChar(i);
2702 if (c == LyXParagraph::META_INSET) {
2703 inset = par->GetInset(i);
2704 inset->Linuxdoc(this, os);
2707 if (font2.latex() == LyXFont::ON) {
2708 // "TeX"-Mode on == > SGML-Mode on.
2710 os << c; // see LaTeX-Generation...
2714 if (par->linuxDocConvertChar(c, sgml_string)
2715 && !style.free_spacing) { // in freespacing
2717 // non-breaking characters
2721 linux_doc_line_break(os, char_line_count, 6);
2725 linux_doc_line_break(os, char_line_count, 1);
2730 char_line_count += sgml_string.length();
2736 // needed if there is an optional argument but no contents
2737 if (main_body > 0 && main_body == par->size()) {
2741 // pop all defined Styles
2742 for (j = stack_num; j >= 0; --j) {
2743 linux_doc_line_break(os,
2745 3 + strlen(stack[j]));
2746 os << "</" << stack[j] << ">";
2749 // resets description flag correctly
2752 // <tag> not closed...
2753 linux_doc_line_break(os, char_line_count, 6);
2757 // fprintf(file, "</p>");
2763 // Print an error message.
2764 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2765 string const & message)
2767 // insert an error marker in text
2768 InsetError * new_inset = new InsetError(message);
2769 par->InsertInset(pos, new_inset);
2772 // This constant defines the maximum number of
2773 // environment layouts that can be nesteded.
2774 // The same applies for command layouts.
2775 // These values should be more than enough.
2776 // José Matos (1999/07/22)
2778 enum { MAX_NEST_LEVEL = 25};
2780 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2782 LyXParagraph * par = paragraph;
2784 niceFile = nice; // this will be used by Insetincludes.
2786 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2787 // Please use a real stack.
2788 string environment_stack[MAX_NEST_LEVEL];
2789 string environment_inner[MAX_NEST_LEVEL];
2790 // Please use a real stack.
2791 string command_stack[MAX_NEST_LEVEL];
2792 bool command_flag= false;
2793 int command_depth= 0, command_base= 0, cmd_depth= 0;
2795 string item_name, command_name;
2796 string c_depth, c_params, tmps;
2798 int depth = 0; // paragraph depth
2799 LyXTextClass const & tclass =
2800 textclasslist.TextClass(params.textclass);
2802 LaTeXFeatures features(params, tclass.numLayouts());
2806 tex_code_break_column = lyxrc.ascii_linelen;
2808 //tex_code_break_column = 0;
2810 ofstream ofs(fname.c_str());
2812 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2819 string sgml_includedfiles=features.getIncludedFiles(fname);
2821 ofs << "<!doctype " << top_element
2822 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2824 if (params.preamble.empty() && sgml_includedfiles.empty())
2827 ofs << "\n [ " << params.preamble
2828 << sgml_includedfiles << " \n]>\n\n";
2831 if (params.options.empty())
2832 sgmlOpenTag(ofs, 0, top_element);
2834 string top = top_element;
2836 top += params.options;
2837 sgmlOpenTag(ofs, 0, top);
2840 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2841 << "\n See http://www.lyx.org/ for more information -->\n";
2844 int desc_on = 0; // description mode
2845 LyXLayout const & style =
2846 textclasslist.Style(params.textclass,
2849 // environment tag closing
2850 for (; depth > par->depth; --depth) {
2851 if (environment_inner[depth] != "!-- --") {
2852 item_name= "listitem";
2853 sgmlCloseTag(ofs, command_depth + depth,
2855 if (environment_inner[depth] == "varlistentry")
2856 sgmlCloseTag(ofs, depth+command_depth,
2857 environment_inner[depth]);
2859 sgmlCloseTag(ofs, depth + command_depth,
2860 environment_stack[depth]);
2861 environment_stack[depth].erase();
2862 environment_inner[depth].erase();
2865 if (depth == par->depth
2866 && environment_stack[depth] != style.latexname()
2867 && !environment_stack[depth].empty()) {
2868 if (environment_inner[depth] != "!-- --") {
2869 item_name= "listitem";
2870 sgmlCloseTag(ofs, command_depth+depth,
2872 if (environment_inner[depth] == "varlistentry")
2874 depth + command_depth,
2875 environment_inner[depth]);
2878 sgmlCloseTag(ofs, depth + command_depth,
2879 environment_stack[depth]);
2881 environment_stack[depth].erase();
2882 environment_inner[depth].erase();
2885 // Write opening SGML tags.
2886 switch (style.latextype) {
2887 case LATEX_PARAGRAPH:
2888 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2893 LinuxDocError(par, 0,
2894 _("Error : Wrong depth for "
2895 "LatexType Command.\n"));
2897 command_name = style.latexname();
2899 tmps = style.latexparam();
2900 c_params = split(tmps, c_depth,'|');
2902 cmd_depth= lyx::atoi(c_depth);
2905 if (cmd_depth<command_base) {
2906 for (int j = command_depth;
2907 j >= command_base; --j)
2908 if (!command_stack[j].empty())
2909 sgmlCloseTag(ofs, j, command_stack[j]);
2910 command_depth= command_base= cmd_depth;
2911 } else if (cmd_depth <= command_depth) {
2912 for (int j = command_depth;
2913 j >= cmd_depth; --j)
2915 if (!command_stack[j].empty())
2916 sgmlCloseTag(ofs, j, command_stack[j]);
2917 command_depth= cmd_depth;
2919 command_depth= cmd_depth;
2921 command_depth = command_base = cmd_depth;
2922 command_flag = true;
2924 command_stack[command_depth]= command_name;
2926 // treat label as a special case for
2927 // more WYSIWYM handling.
2928 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2929 Inset * inset = par->GetInset(0);
2930 Inset::Code lyx_code = inset->LyxCode();
2931 if (lyx_code == Inset::LABEL_CODE){
2932 command_name += " id=\"";
2933 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2934 command_name += "\"";
2939 sgmlOpenTag(ofs, depth + command_depth, command_name);
2940 item_name = "title";
2941 if (command_name != "!-- --")
2942 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2945 case LATEX_ENVIRONMENT:
2946 case LATEX_ITEM_ENVIRONMENT:
2947 if (depth < par->depth) {
2949 environment_stack[depth].erase();
2952 if (environment_stack[depth] != style.latexname()) {
2953 environment_stack[depth] = style.latexname();
2954 environment_inner[depth] = "!-- --";
2955 sgmlOpenTag(ofs, depth + command_depth,
2956 environment_stack[depth]);
2958 if (environment_inner[depth] != "!-- --") {
2959 item_name= "listitem";
2961 command_depth + depth,
2963 if (environment_inner[depth] == "varlistentry")
2965 depth + command_depth,
2966 environment_inner[depth]);
2970 if (style.latextype == LATEX_ENVIRONMENT) {
2971 if (!style.latexparam().empty())
2972 sgmlOpenTag(ofs, depth + command_depth,
2973 style.latexparam());
2977 desc_on = (style.labeltype == LABEL_MANUAL);
2980 environment_inner[depth]= "varlistentry";
2982 environment_inner[depth]= "listitem";
2984 sgmlOpenTag(ofs, depth + 1 + command_depth,
2985 environment_inner[depth]);
2989 sgmlOpenTag(ofs, depth + 1 + command_depth,
2993 sgmlOpenTag(ofs, depth + 1 + command_depth,
2998 sgmlOpenTag(ofs, depth + command_depth,
3007 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3008 depth + 1 + command_depth);
3011 DocBookHandleFootnote(ofs, par,
3012 depth + 1 + command_depth);
3014 while(par && par->IsDummy());
3017 // write closing SGML tags
3018 switch (style.latextype) {
3021 if (command_name != "!-- --")
3022 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3024 case LATEX_ENVIRONMENT:
3025 if (!style.latexparam().empty())
3026 sgmlCloseTag(ofs, depth + command_depth,
3027 style.latexparam());
3029 case LATEX_ITEM_ENVIRONMENT:
3030 if (desc_on == 1) break;
3032 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3034 case LATEX_PARAGRAPH:
3035 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3038 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3044 for (; depth >= 0; --depth) {
3045 if (!environment_stack[depth].empty()) {
3046 if (environment_inner[depth] != "!-- --") {
3047 item_name= "listitem";
3048 sgmlCloseTag(ofs, command_depth + depth,
3050 if (environment_inner[depth] == "varlistentry")
3051 sgmlCloseTag(ofs, depth + command_depth,
3052 environment_inner[depth]);
3055 sgmlCloseTag(ofs, depth + command_depth,
3056 environment_stack[depth]);
3060 for (int j = command_depth; j >= command_base; --j)
3061 if (!command_stack[j].empty())
3062 sgmlCloseTag(ofs, j, command_stack[j]);
3065 sgmlCloseTag(ofs, 0, top_element);
3068 // How to check for successful close
3072 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3073 LyXParagraph * par, int & desc_on,
3076 bool emph_flag = false;
3078 LyXLayout const & style = textclasslist.Style(params.textclass,
3081 LyXParagraph::size_type main_body;
3082 if (style.labeltype != LABEL_MANUAL)
3085 main_body = par->BeginningOfMainBody();
3087 // gets paragraph main font
3088 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3090 int char_line_count = depth;
3091 if (!style.free_spacing)
3092 for (int j = 0; j < depth; ++j)
3095 // parsing main loop
3096 for (LyXParagraph::size_type i = 0;
3097 i < par->size(); ++i) {
3098 LyXFont font2 = par->getFont(params, i);
3100 // handle <emphasis> tag
3101 if (font1.emph() != font2.emph() && i) {
3102 if (font2.emph() == LyXFont::ON) {
3106 os << "</emphasis>";
3111 char c = par->GetChar(i);
3113 if (c == LyXParagraph::META_INSET) {
3114 Inset * inset = par->GetInset(i);
3115 std::ostringstream ost;
3116 inset->DocBook(this, ost);
3117 string tmp_out = ost.str().c_str();
3120 // This code needs some explanation:
3121 // Two insets are treated specially
3122 // label if it is the first element in a command paragraph
3124 // graphics inside tables or figure floats can't go on
3125 // title (the equivalente in latex for this case is caption
3126 // and title should come first
3129 if (desc_on!= 3 || i!= 0) {
3130 if (!tmp_out.empty() && tmp_out[0] == '@') {
3132 extra += frontStrip(tmp_out, '@');
3134 os << frontStrip(tmp_out, '@');
3139 } else if (font2.latex() == LyXFont::ON) {
3140 // "TeX"-Mode on ==> SGML-Mode on.
3146 if (par->linuxDocConvertChar(c, sgml_string)
3147 && !style.free_spacing) { // in freespacing
3149 // non-breaking characters
3153 os << "\n</term><listitem><para>";
3165 // needed if there is an optional argument but no contents
3166 if (main_body > 0 && main_body == par->size()) {
3170 os << "</emphasis>";
3173 // resets description flag correctly
3176 // <term> not closed...
3184 // This should be enabled when the Chktex class is implemented. (Asger)
3185 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3186 // Other flags: -wall -v0 -x
3187 int Buffer::runChktex()
3189 if (!users->text) return 0;
3191 ProhibitInput(users);
3193 // get LaTeX-Filename
3194 string const name = getLatexName();
3195 string path = OnlyPath(filename);
3197 string const org_path = path;
3198 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3202 Path p(path); // path to LaTeX file
3203 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3205 // Remove all error insets
3206 bool const removedErrorInsets = users->removeAutoInsets();
3208 // Generate the LaTeX file if neccessary
3209 makeLaTeXFile(name, org_path, false);
3212 Chktex chktex(lyxrc.chktex_command, name, filepath);
3213 int res = chktex.run(terr); // run chktex
3216 WriteAlert(_("chktex did not work!"),
3217 _("Could not run with file:"), name);
3218 } else if (res > 0) {
3219 // Insert all errors as errors boxes
3220 users->insertErrors(terr);
3223 // if we removed error insets before we ran chktex or if we inserted
3224 // error insets after we ran chktex, this must be run:
3225 if (removedErrorInsets || res){
3227 users->fitCursor(users->text);
3235 void Buffer::validate(LaTeXFeatures & features) const
3237 LyXParagraph * par = paragraph;
3238 LyXTextClass const & tclass =
3239 textclasslist.TextClass(params.textclass);
3241 // AMS Style is at document level
3243 features.amsstyle = (params.use_amsmath ||
3244 tclass.provides(LyXTextClass::amsmath));
3247 // We don't use "lyxerr.debug" because of speed. (Asger)
3248 if (lyxerr.debugging(Debug::LATEX))
3249 lyxerr << "Paragraph: " << par << endl;
3251 // Now just follow the list of paragraphs and run
3252 // validate on each of them.
3253 par->validate(features);
3255 // and then the next paragraph
3259 // the bullet shapes are buffer level not paragraph level
3260 // so they are tested here
3261 for (int i = 0; i < 4; ++i) {
3262 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3263 int const font = params.user_defined_bullets[i].getFont();
3265 int const c = params
3266 .user_defined_bullets[i]
3273 features.latexsym = true;
3275 } else if (font == 1) {
3276 features.amssymb = true;
3277 } else if ((font >= 2 && font <= 5)) {
3278 features.pifont = true;
3283 if (lyxerr.debugging(Debug::LATEX)) {
3284 features.showStruct();
3289 void Buffer::setPaperStuff()
3291 params.papersize = BufferParams::PAPER_DEFAULT;
3292 char const c1 = params.paperpackage;
3293 if (c1 == BufferParams::PACKAGE_NONE) {
3294 char const c2 = params.papersize2;
3295 if (c2 == BufferParams::VM_PAPER_USLETTER)
3296 params.papersize = BufferParams::PAPER_USLETTER;
3297 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3298 params.papersize = BufferParams::PAPER_LEGALPAPER;
3299 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3300 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3301 else if (c2 == BufferParams::VM_PAPER_A3)
3302 params.papersize = BufferParams::PAPER_A3PAPER;
3303 else if (c2 == BufferParams::VM_PAPER_A4)
3304 params.papersize = BufferParams::PAPER_A4PAPER;
3305 else if (c2 == BufferParams::VM_PAPER_A5)
3306 params.papersize = BufferParams::PAPER_A5PAPER;
3307 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3308 (c2 == BufferParams::VM_PAPER_B5))
3309 params.papersize = BufferParams::PAPER_B5PAPER;
3310 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3311 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3312 params.papersize = BufferParams::PAPER_A4PAPER;
3316 // This function should be in Buffer because it's a buffer's property (ale)
3317 string const Buffer::getIncludeonlyList(char delim)
3320 for (inset_iterator it = inset_iterator_begin();
3321 it != inset_iterator_end(); ++it) {
3322 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3323 InsetInclude * insetinc =
3324 static_cast<InsetInclude *>(*it);
3325 if (insetinc->isInclude()
3326 && insetinc->isNoLoad()) {
3329 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3333 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3338 vector<string> const Buffer::getLabelList()
3340 /// if this is a child document and the parent is already loaded
3341 /// Use the parent's list instead [ale990407]
3342 if (!params.parentname.empty()
3343 && bufferlist.exists(params.parentname)) {
3344 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3346 return tmp->getLabelList();
3349 vector<string> label_list;
3350 for (inset_iterator it = inset_iterator_begin();
3351 it != inset_iterator_end(); ++it) {
3352 vector<string> const l = (*it)->getLabelList();
3353 label_list.insert(label_list.end(), l.begin(), l.end());
3359 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3364 vector<vector<TocItem> > l(4);
3365 LyXParagraph * par = paragraph;
3368 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3369 if (textclasslist.Style(params.textclass,
3370 par->GetLayout()).labeltype
3371 == LABEL_SENSITIVE) {
3375 tmp.str = par->String(this, false);
3376 switch (par->footnotekind) {
3377 case LyXParagraph::FIG:
3378 case LyXParagraph::WIDE_FIG:
3379 tmp.str = tostr(++figs) + ". "
3381 l[TOC_LOF].push_back(tmp);
3383 case LyXParagraph::TAB:
3384 case LyXParagraph::WIDE_TAB:
3385 tmp.str = tostr(++tables) + ". "
3387 l[TOC_LOT].push_back(tmp);
3389 case LyXParagraph::ALGORITHM:
3390 tmp.str = tostr(++algs) + ". "
3392 l[TOC_LOA].push_back(tmp);
3394 case LyXParagraph::FOOTNOTE:
3395 case LyXParagraph::MARGIN:
3399 } else if (!par->IsDummy()) {
3401 char const labeltype =
3402 textclasslist.Style(params.textclass,
3403 par->GetLayout()).labeltype;
3405 if (labeltype >= LABEL_COUNTER_CHAPTER
3406 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3407 // insert this into the table of contents
3412 textclasslist.TextClass(params.textclass).maxcounter());
3413 tmp.str = par->String(this, true);
3414 l[TOC_TOC].push_back(tmp);
3425 // This is also a buffer property (ale)
3426 vector<pair<string,string> > const Buffer::getBibkeyList()
3428 /// if this is a child document and the parent is already loaded
3429 /// Use the parent's list instead [ale990412]
3430 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3431 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3433 return tmp->getBibkeyList();
3436 vector<pair<string, string> > keys;
3437 LyXParagraph * par = paragraph;
3440 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3441 par->String(this, false)));
3445 // Might be either using bibtex or a child has bibliography
3447 for (inset_iterator it = inset_iterator_begin();
3448 it != inset_iterator_end(); ++it) {
3449 // Search for Bibtex or Include inset
3450 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3451 vector<pair<string,string> > tmp =
3452 static_cast<InsetBibtex*>(*it)->getKeys(this);
3453 keys.insert(keys.end(), tmp.begin(), tmp.end());
3454 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3455 vector<pair<string,string> > const tmp =
3456 static_cast<InsetInclude*>(*it)->getKeys();
3457 keys.insert(keys.end(), tmp.begin(), tmp.end());
3466 bool Buffer::isDepClean(string const & name) const
3468 DEPCLEAN * item = dep_clean;
3469 while (item && item->master != name)
3471 if (!item) return true;
3476 void Buffer::markDepClean(string const & name)
3479 dep_clean = new DEPCLEAN;
3480 dep_clean->clean = true;
3481 dep_clean->master = name;
3482 dep_clean->next = 0;
3484 DEPCLEAN * item = dep_clean;
3485 while (item && item->master != name)
3490 item = new DEPCLEAN;
3492 item->master = name;
3499 bool Buffer::Dispatch(string const & command)
3501 // Split command string into command and argument
3503 string line = frontStrip(command);
3504 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3506 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3510 bool Buffer::Dispatch(int action, string const & argument)
3512 bool dispatched = true;
3515 Exporter::Export(this, argument, false);
3525 void Buffer::resize()
3527 /// resize the BufferViews!
3533 void Buffer::resizeInsets(BufferView * bv)
3535 /// then remove all LyXText in text-insets
3536 LyXParagraph * par = paragraph;
3537 for (; par; par = par->next) {
3538 par->resizeInsetsLyXText(bv);
3542 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3545 LyXParagraph * par = paragraph;
3547 par->ChangeLanguage(params, from, to);
3553 bool Buffer::isMultiLingual()
3555 LyXParagraph * par = paragraph;
3557 if (par->isMultiLingual(params))
3565 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3566 LyXParagraph::size_type pos)
3569 it = par->InsetIterator(pos);
3570 if (it == par->inset_iterator_end()) {
3577 void Buffer::inset_iterator::SetParagraph()
3580 it = par->inset_iterator_begin();
3581 if (it != par->inset_iterator_end())
3586 // We maintain an invariant that whenever par = 0 then it = 0