1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
22 #include <sys/types.h>
32 #pragma implementation "buffer.h"
36 #include "bufferlist.h"
38 #include "lyx_gui_misc.h"
39 #include "LyXAction.h"
42 #include "tex-strings.h"
44 #include "bufferview_funcs.h"
45 #include "minibuffer.h"
48 #include "mathed/formulamacro.h"
49 #include "insets/lyxinset.h"
50 #include "insets/inseterror.h"
51 #include "insets/insetlabel.h"
52 #include "insets/insetref.h"
53 #include "insets/inseturl.h"
54 #include "insets/insetinfo.h"
55 #include "insets/insetquotes.h"
56 #include "insets/insetlatexaccent.h"
57 #include "insets/insetbib.h"
58 #include "insets/insetcite.h"
59 #include "insets/insetexternal.h"
60 #include "insets/insetindex.h"
61 #include "insets/insetinclude.h"
62 #include "insets/insettoc.h"
63 #include "insets/insetparent.h"
64 #include "insets/insetspecialchar.h"
65 #include "insets/figinset.h"
66 #include "insets/insettext.h"
67 #include "insets/insetert.h"
68 #include "insets/insetgraphics.h"
69 #include "insets/insetfoot.h"
70 #include "insets/insetmarginal.h"
71 #include "insets/insetminipage.h"
72 #include "insets/insetfloat.h"
73 #include "insets/insetlist.h"
74 #include "insets/insettabular.h"
75 #include "insets/insettheorem.h"
76 #include "insets/insetcaption.h"
77 #include "support/filetools.h"
78 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
91 #include "lyx_gui_misc.h" // WarnReadonly()
92 #include "frontends/Dialogs.h"
107 using std::istringstream;
109 // all these externs should eventually be removed.
110 extern BufferList bufferlist;
112 extern LyXAction lyxaction;
115 static const float LYX_FORMAT = 2.17;
117 extern int tex_code_break_column;
120 Buffer::Buffer(string const & file, bool ronly)
122 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
124 filepath = OnlyPath(file);
133 if (read_only || (lyxrc.use_tempdir)) {
134 tmppath = CreateBufferTmpDir();
135 } else tmppath.erase();
141 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142 // here the buffer should take care that it is
143 // saved properly, before it goes into the void.
145 // make sure that views using this buffer
150 if (!tmppath.empty()) {
151 DestroyBufferTmpDir(tmppath);
154 LyXParagraph * par = paragraph;
155 LyXParagraph * tmppar;
165 string const Buffer::getLatexName(bool no_path) const
168 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
171 return ChangeExtension(MakeLatexName(filename),
176 void Buffer::setReadonly(bool flag)
178 if (read_only != flag) {
181 users->owner()->getDialogs()->updateBufferDependent();
184 WarnReadonly(filename);
189 bool Buffer::saveParamsAsDefaults() // const
191 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
193 Buffer defaults = Buffer(fname);
195 // Use the current buffer's parameters as default
196 defaults.params = params;
198 // add an empty paragraph. Is this enough?
199 defaults.paragraph = new LyXParagraph;
201 return defaults.writeFile(defaults.filename, false);
205 /// Update window titles of all users
206 // Should work on a list
207 void Buffer::updateTitles() const
209 if (users) users->owner()->updateWindowTitle();
213 /// Reset autosave timer of all users
214 // Should work on a list
215 void Buffer::resetAutosaveTimers() const
217 if (users) users->owner()->resetAutosaveTimer();
221 void Buffer::fileName(string const & newfile)
223 filename = MakeAbsPath(newfile);
224 filepath = OnlyPath(filename);
225 setReadonly(IsFileWriteable(filename) == 0);
230 // candidate for move to BufferView
231 // (at least some parts in the beginning of the func)
234 // changed to be public and have one parameter
235 // if par = 0 normal behavior
236 // else insert behavior
237 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
238 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
241 char depth = 0; // signed or unsigned?
243 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
244 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
246 bool the_end_read = false;
248 LyXParagraph * return_par = 0;
249 LyXFont font(LyXFont::ALL_INHERIT, params.language_info);
250 if (format < 2.16 && params.language == "hebrew")
251 font.setLanguage(default_language);
253 // If we are inserting, we cheat and get a token in advance
254 bool has_token = false;
258 par = new LyXParagraph;
260 users->text->BreakParagraph(users);
261 return_par = users->text->FirstParagraph();
264 // We don't want to adopt the parameters from the
265 // document we insert, so we skip until the text begins:
268 pretoken = lex.GetString();
269 if (pretoken == "\\layout") {
281 pretoken = lex.GetString();
284 if (pretoken.empty()) continue;
287 parseSingleLyXformat2Token(lex, par, return_par,
288 pretoken, pos, depth,
300 paragraph = return_par;
306 // We'll remove this later. (Lgb)
307 static string last_inset_read;
311 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
312 LyXParagraph *& return_par,
313 string const & token, int & pos,
314 char & depth, LyXFont & font
316 , LyXParagraph::footnote_flag & footnoteflag,
317 LyXParagraph::footnote_kind & footnotekind
321 bool the_end_read = false;
323 if (token[0] != '\\') {
324 for (string::const_iterator cit = token.begin();
325 cit != token.end(); ++cit) {
326 par->InsertChar(pos, (*cit), font);
329 } else if (token == "\\i") {
330 Inset * inset = new InsetLatexAccent;
331 inset->Read(this, lex);
332 par->InsertInset(pos, inset, font);
334 } else if (token == "\\layout") {
339 par = new LyXParagraph(par);
343 string const layoutname = lex.GetString();
344 pair<bool, LyXTextClass::LayoutList::size_type> pp
345 = textclasslist.NumberOfLayout(params.textclass,
348 par->layout = pp.second;
349 } else { // layout not found
350 // use default layout "Standard" (0)
353 // Test whether the layout is obsolete.
354 LyXLayout const & layout =
355 textclasslist.Style(params.textclass,
357 if (!layout.obsoleted_by().empty())
359 textclasslist.NumberOfLayout(params.textclass,
360 layout.obsoleted_by()).second;
362 par->footnoteflag = footnoteflag;
363 par->footnotekind = footnotekind;
366 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
367 if (format < 2.16 && params.language == "hebrew")
368 font.setLanguage(default_language);
370 } else if (token == "\\end_float") {
375 par = new LyXParagraph(par);
377 footnotekind = LyXParagraph::FOOTNOTE;
378 footnoteflag = LyXParagraph::NO_FOOTNOTE;
381 par->layout = LYX_DUMMY_LAYOUT;
382 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
383 if (format < 2.16 && params.language == "hebrew")
384 font.setLanguage(default_language);
385 } else if (token == "\\begin_float") {
386 int tmpret = lex.FindToken(string_footnotekinds);
387 if (tmpret == -1) ++tmpret;
388 if (tmpret != LYX_LAYOUT_DEFAULT)
389 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
390 if (footnotekind == LyXParagraph::FOOTNOTE
391 || footnotekind == LyXParagraph::MARGIN)
392 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
394 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
396 } else if (token == "\\begin_float") {
397 // This is the compability reader, unfinished but tested.
400 string const tmptok = lex.GetString();
401 //lyxerr << "old float: " << tmptok << endl;
406 if (tmptok == "footnote") {
407 inset = new InsetFoot;
408 } else if (tmptok == "margin") {
409 inset = new InsetMarginal;
410 } else if (tmptok == "fig") {
411 inset = new InsetFloat("figure");
412 old_float += "placement htbp\n";
413 } else if (tmptok == "tab") {
414 inset = new InsetFloat("table");
415 old_float += "placement htbp\n";
416 } else if (tmptok == "alg") {
417 inset = new InsetFloat("algorithm");
418 old_float += "placement htbp\n";
419 } else if (tmptok == "wide-fig") {
420 InsetFloat * tmp = new InsetFloat("figure");
423 old_float += "placement htbp\n";
424 } else if (tmptok == "wide-tab") {
425 InsetFloat * tmp = new InsetFloat("table");
428 old_float += "placement htbp\n";
431 if (!inset) return false; // no end read yet
433 old_float += "collapsed true\n";
435 // Here we need to check for \end_deeper and handle that
436 // before we do the footnote parsing.
437 // This _is_ a hack! (Lgb)
440 string const tmp = lex.GetString();
441 if (tmp == "\\end_deeper") {
442 lyxerr << "\\end_deeper caught!" << endl;
444 lex.printError("\\end_deeper: "
445 "depth is already null");
456 old_float += lex.getLongString("\\end_float");
457 old_float += "\n\\end_inset\n";
458 //lyxerr << "float body: " << old_float << endl;
460 istringstream istr(old_float);
463 nylex.setStream(istr);
465 inset->Read(this, nylex);
466 par->InsertInset(pos, inset, font);
469 } else if (token == "\\begin_deeper") {
471 } else if (token == "\\end_deeper") {
473 lex.printError("\\end_deeper: "
474 "depth is already null");
478 } else if (token == "\\begin_preamble") {
479 params.readPreamble(lex);
480 } else if (token == "\\textclass") {
482 pair<bool, LyXTextClassList::size_type> pp =
483 textclasslist.NumberOfClass(lex.GetString());
485 params.textclass = pp.second;
487 lex.printError("Unknown textclass `$$Token'");
488 params.textclass = 0;
490 if (!textclasslist.Load(params.textclass)) {
491 // if the textclass wasn't loaded properly
492 // we need to either substitute another
493 // or stop loading the file.
494 // I can substitute but I don't see how I can
495 // stop loading... ideas?? ARRae980418
496 WriteAlert(_("Textclass Loading Error!"),
497 string(_("Can't load textclass ")) +
498 textclasslist.NameOfClass(params.textclass),
499 _("-- substituting default"));
500 params.textclass = 0;
502 } else if (token == "\\options") {
504 params.options = lex.GetString();
505 } else if (token == "\\language") {
506 params.readLanguage(lex);
507 } else if (token == "\\fontencoding") {
509 } else if (token == "\\inputencoding") {
511 params.inputenc = lex.GetString();
512 } else if (token == "\\graphics") {
513 params.readGraphicsDriver(lex);
514 } else if (token == "\\fontscheme") {
516 params.fonts = lex.GetString();
517 } else if (token == "\\noindent") {
518 par->noindent = true;
519 } else if (token == "\\fill_top") {
520 par->added_space_top = VSpace(VSpace::VFILL);
521 } else if (token == "\\fill_bottom") {
522 par->added_space_bottom = VSpace(VSpace::VFILL);
523 } else if (token == "\\line_top") {
524 par->line_top = true;
525 } else if (token == "\\line_bottom") {
526 par->line_bottom = true;
527 } else if (token == "\\pagebreak_top") {
528 par->pagebreak_top = true;
529 } else if (token == "\\pagebreak_bottom") {
530 par->pagebreak_bottom = true;
531 } else if (token == "\\start_of_appendix") {
532 par->start_of_appendix = true;
533 } else if (token == "\\paragraph_separation") {
534 int tmpret = lex.FindToken(string_paragraph_separation);
535 if (tmpret == -1) ++tmpret;
536 if (tmpret != LYX_LAYOUT_DEFAULT)
537 params.paragraph_separation =
538 static_cast<BufferParams::PARSEP>(tmpret);
539 } else if (token == "\\defskip") {
541 params.defskip = VSpace(lex.GetString());
542 } else if (token == "\\epsfig") { // obsolete
543 // Indeed it is obsolete, but we HAVE to be backwards
544 // compatible until 0.14, because otherwise all figures
545 // in existing documents are irretrivably lost. (Asger)
546 params.readGraphicsDriver(lex);
547 } else if (token == "\\quotes_language") {
548 int tmpret = lex.FindToken(string_quotes_language);
549 if (tmpret == -1) ++tmpret;
550 if (tmpret != LYX_LAYOUT_DEFAULT) {
551 InsetQuotes::quote_language tmpl =
552 InsetQuotes::EnglishQ;
555 tmpl = InsetQuotes::EnglishQ;
558 tmpl = InsetQuotes::SwedishQ;
561 tmpl = InsetQuotes::GermanQ;
564 tmpl = InsetQuotes::PolishQ;
567 tmpl = InsetQuotes::FrenchQ;
570 tmpl = InsetQuotes::DanishQ;
573 params.quotes_language = tmpl;
575 } else if (token == "\\quotes_times") {
577 switch(lex.GetInteger()) {
579 params.quotes_times = InsetQuotes::SingleQ;
582 params.quotes_times = InsetQuotes::DoubleQ;
585 } else if (token == "\\papersize") {
586 int tmpret = lex.FindToken(string_papersize);
590 params.papersize2 = tmpret;
591 } else if (token == "\\paperpackage") {
592 int tmpret = lex.FindToken(string_paperpackages);
595 params.paperpackage = BufferParams::PACKAGE_NONE;
597 params.paperpackage = tmpret;
598 } else if (token == "\\use_geometry") {
600 params.use_geometry = lex.GetInteger();
601 } else if (token == "\\use_amsmath") {
603 params.use_amsmath = lex.GetInteger();
604 } else if (token == "\\paperorientation") {
605 int tmpret = lex.FindToken(string_orientation);
606 if (tmpret == -1) ++tmpret;
607 if (tmpret != LYX_LAYOUT_DEFAULT)
608 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
609 } else if (token == "\\paperwidth") {
611 params.paperwidth = lex.GetString();
612 } else if (token == "\\paperheight") {
614 params.paperheight = lex.GetString();
615 } else if (token == "\\leftmargin") {
617 params.leftmargin = lex.GetString();
618 } else if (token == "\\topmargin") {
620 params.topmargin = lex.GetString();
621 } else if (token == "\\rightmargin") {
623 params.rightmargin = lex.GetString();
624 } else if (token == "\\bottommargin") {
626 params.bottommargin = lex.GetString();
627 } else if (token == "\\headheight") {
629 params.headheight = lex.GetString();
630 } else if (token == "\\headsep") {
632 params.headsep = lex.GetString();
633 } else if (token == "\\footskip") {
635 params.footskip = lex.GetString();
636 } else if (token == "\\paperfontsize") {
638 params.fontsize = strip(lex.GetString());
639 } else if (token == "\\papercolumns") {
641 params.columns = lex.GetInteger();
642 } else if (token == "\\papersides") {
644 switch(lex.GetInteger()) {
646 case 1: params.sides = LyXTextClass::OneSide; break;
647 case 2: params.sides = LyXTextClass::TwoSides; break;
649 } else if (token == "\\paperpagestyle") {
651 params.pagestyle = strip(lex.GetString());
652 } else if (token == "\\bullet") {
654 int const index = lex.GetInteger();
656 int temp_int = lex.GetInteger();
657 params.user_defined_bullets[index].setFont(temp_int);
658 params.temp_bullets[index].setFont(temp_int);
660 temp_int = lex.GetInteger();
661 params.user_defined_bullets[index].setCharacter(temp_int);
662 params.temp_bullets[index].setCharacter(temp_int);
664 temp_int = lex.GetInteger();
665 params.user_defined_bullets[index].setSize(temp_int);
666 params.temp_bullets[index].setSize(temp_int);
668 string const temp_str = lex.GetString();
669 if (temp_str != "\\end_bullet") {
670 // this element isn't really necessary for
671 // parsing but is easier for humans
672 // to understand bullets. Put it back and
673 // set a debug message?
674 lex.printError("\\end_bullet expected, got" + temp_str);
675 //how can I put it back?
677 } else if (token == "\\bulletLaTeX") {
679 int const index = lex.GetInteger();
681 string temp_str = lex.GetString();
683 while (temp_str != "\\end_bullet") {
684 // this loop structure is needed when user
685 // enters an empty string since the first
686 // thing returned will be the \\end_bullet
688 // if the LaTeX entry has spaces. Each element
689 // therefore needs to be read in turn
692 temp_str = lex.GetString();
694 params.user_defined_bullets[index].setText(sum_str);
695 params.temp_bullets[index].setText(sum_str);
696 } else if (token == "\\secnumdepth") {
698 params.secnumdepth = lex.GetInteger();
699 } else if (token == "\\tocdepth") {
701 params.tocdepth = lex.GetInteger();
702 } else if (token == "\\spacing") {
704 string const tmp = strip(lex.GetString());
705 Spacing::Space tmp_space = Spacing::Default;
707 if (tmp == "single") {
708 tmp_space = Spacing::Single;
709 } else if (tmp == "onehalf") {
710 tmp_space = Spacing::Onehalf;
711 } else if (tmp == "double") {
712 tmp_space = Spacing::Double;
713 } else if (tmp == "other") {
715 tmp_space = Spacing::Other;
716 tmp_val = lex.GetFloat();
718 lex.printError("Unknown spacing token: '$$Token'");
720 // Small hack so that files written with klyx will be
723 par->spacing.set(tmp_space, tmp_val);
725 params.spacing.set(tmp_space, tmp_val);
727 } else if (token == "\\paragraph_spacing") {
729 string const tmp = strip(lex.GetString());
730 if (tmp == "single") {
731 par->spacing.set(Spacing::Single);
732 } else if (tmp == "onehalf") {
733 par->spacing.set(Spacing::Onehalf);
734 } else if (tmp == "double") {
735 par->spacing.set(Spacing::Double);
736 } else if (tmp == "other") {
738 par->spacing.set(Spacing::Other,
741 lex.printError("Unknown spacing token: '$$Token'");
743 } else if (token == "\\float_placement") {
745 params.float_placement = lex.GetString();
746 } else if (token == "\\family") {
748 font.setLyXFamily(lex.GetString());
749 } else if (token == "\\series") {
751 font.setLyXSeries(lex.GetString());
752 } else if (token == "\\shape") {
754 font.setLyXShape(lex.GetString());
755 } else if (token == "\\size") {
757 font.setLyXSize(lex.GetString());
758 } else if (token == "\\latex") {
760 string const tok = lex.GetString();
761 // This is dirty, but gone with LyX3. (Asger)
762 if (tok == "no_latex")
763 font.setLatex(LyXFont::OFF);
764 else if (tok == "latex")
765 font.setLatex(LyXFont::ON);
766 else if (tok == "default")
767 font.setLatex(LyXFont::INHERIT);
769 lex.printError("Unknown LaTeX font flag "
771 } else if (token == "\\lang") {
773 string const tok = lex.GetString();
774 Languages::iterator lit = languages.find(tok);
775 if (lit != languages.end()) {
776 font.setLanguage(&(*lit).second);
778 font.setLanguage(params.language_info);
779 lex.printError("Unknown language `$$Token'");
781 } else if (token == "\\emph") {
783 font.setEmph(font.setLyXMisc(lex.GetString()));
784 } else if (token == "\\bar") {
786 string const tok = lex.GetString();
787 // This is dirty, but gone with LyX3. (Asger)
789 font.setUnderbar(LyXFont::ON);
790 else if (tok == "no")
791 font.setUnderbar(LyXFont::OFF);
792 else if (tok == "default")
793 font.setUnderbar(LyXFont::INHERIT);
795 lex.printError("Unknown bar font flag "
797 } else if (token == "\\noun") {
799 font.setNoun(font.setLyXMisc(lex.GetString()));
800 } else if (token == "\\color") {
802 font.setLyXColor(lex.GetString());
803 } else if (token == "\\align") {
804 int tmpret = lex.FindToken(string_align);
805 if (tmpret == -1) ++tmpret;
806 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
808 for (; tmpret > 0; --tmpret)
809 tmpret2 = tmpret2 * 2;
810 par->align = LyXAlignment(tmpret2);
812 } else if (token == "\\added_space_top") {
814 par->added_space_top = VSpace(lex.GetString());
815 } else if (token == "\\added_space_bottom") {
817 par->added_space_bottom = VSpace(lex.GetString());
818 } else if (token == "\\pextra_type") {
820 par->pextra_type = lex.GetInteger();
821 } else if (token == "\\pextra_width") {
823 par->pextra_width = lex.GetString();
824 } else if (token == "\\pextra_widthp") {
826 par->pextra_widthp = lex.GetString();
827 } else if (token == "\\pextra_alignment") {
829 par->pextra_alignment = lex.GetInteger();
830 } else if (token == "\\pextra_hfill") {
832 par->pextra_hfill = lex.GetInteger();
833 } else if (token == "\\pextra_start_minipage") {
835 par->pextra_start_minipage = lex.GetInteger();
836 } else if (token == "\\labelwidthstring") {
838 par->labelwidthstring = lex.GetString();
839 // do not delete this token, it is still needed!
840 } else if (token == "\\end_inset") {
841 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
842 << "Last inset read was: " << last_inset_read
844 // Simply ignore this. The insets do not have
846 // But insets should read it, it is a part of
847 // the inset isn't it? Lgb.
848 } else if (token == "\\begin_inset") {
849 readInset(lex, par, pos, font);
850 } else if (token == "\\SpecialChar") {
851 LyXLayout const & layout =
852 textclasslist.Style(params.textclass,
855 // Insets don't make sense in a free-spacing context! ---Kayvan
856 if (layout.free_spacing) {
859 string next_token = lex.GetString();
860 if (next_token == "\\-") {
861 par->InsertChar(pos, '-', font);
862 } else if (next_token == "\\protected_separator"
863 || next_token == "~") {
864 par->InsertChar(pos, ' ', font);
866 lex.printError("Token `$$Token' "
868 "paragraph layout!");
873 Inset * inset = new InsetSpecialChar;
874 inset->Read(this, lex);
875 par->InsertInset(pos, inset, font);
878 } else if (token == "\\newline") {
879 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
881 } else if (token == "\\LyXTable") {
882 Inset * inset = new InsetTabular(this);
883 inset->Read(this, lex);
884 par->InsertInset(pos, inset, font);
886 } else if (token == "\\hfill") {
887 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
889 } else if (token == "\\protected_separator") { // obsolete
890 // This is a backward compability thingie. (Lgb)
891 // Remove it later some time...introduced with fileformat
893 LyXLayout const & layout =
894 textclasslist.Style(params.textclass,
897 if (layout.free_spacing) {
898 par->InsertChar(pos, ' ', font);
900 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
901 par->InsertInset(pos, inset, font);
904 } else if (token == "\\bibitem") { // ale970302
906 InsetCommandParams p( "bibitem" );
907 par->bibkey = new InsetBibKey(p);
909 par->bibkey->Read(this, lex);
910 } else if (token == "\\backslash") {
911 par->InsertChar(pos, '\\', font);
913 } else if (token == "\\the_end") {
916 // This should be insurance for the future: (Asger)
917 lex.printError("Unknown token `$$Token'. "
918 "Inserting as text.");
919 string::const_iterator cit = token.begin();
920 string::const_iterator end = token.end();
921 for(; cit != end; ++cit) {
922 par->InsertChar(pos, (*cit), font);
930 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
931 int & pos, LyXFont & font)
934 if (lex.GetString() != "\\begin_inset") {
935 lyxerr << "Buffer::readInset: Consistency check failed."
940 string const tmptok = lex.GetString();
941 last_inset_read = tmptok;
942 // test the different insets
943 if (tmptok == "Quotes") {
944 Inset * inset = new InsetQuotes;
945 inset->Read(this, lex);
946 par->InsertInset(pos, inset, font);
948 } else if (tmptok == "External") {
949 Inset * inset = new InsetExternal;
950 inset->Read(this, lex);
951 par->InsertInset(pos, inset, font);
953 } else if (tmptok == "FormulaMacro") {
954 Inset * inset = new InsetFormulaMacro;
955 inset->Read(this, lex);
956 par->InsertInset(pos, inset, font);
958 } else if (tmptok == "Formula") {
959 Inset * inset = new InsetFormula;
960 inset->Read(this, lex);
961 par->InsertInset(pos, inset, font);
963 } else if (tmptok == "Figure") {
964 Inset * inset = new InsetFig(100, 100, this);
965 inset->Read(this, lex);
966 par->InsertInset(pos, inset, font);
968 } else if (tmptok == "Info") {
969 Inset * inset = new InsetInfo;
970 inset->Read(this, lex);
971 par->InsertInset(pos, inset, font);
973 } else if (tmptok == "Include") {
974 InsetCommandParams p( "Include" );
975 Inset * inset = new InsetInclude(p, this);
976 inset->Read(this, lex);
977 par->InsertInset(pos, inset, font);
979 } else if (tmptok == "ERT") {
980 Inset * inset = new InsetERT;
981 inset->Read(this, lex);
982 par->InsertInset(pos, inset, font);
984 } else if (tmptok == "Tabular") {
985 Inset * inset = new InsetTabular(this);
986 inset->Read(this, lex);
987 par->InsertInset(pos, inset, font);
989 } else if (tmptok == "Text") {
990 Inset * inset = new InsetText;
991 inset->Read(this, lex);
992 par->InsertInset(pos, inset, font);
994 } else if (tmptok == "Foot") {
995 Inset * inset = new InsetFoot;
996 inset->Read(this, lex);
997 par->InsertInset(pos, inset, font);
999 } else if (tmptok == "Marginal") {
1000 Inset * inset = new InsetMarginal;
1001 inset->Read(this, lex);
1002 par->InsertInset(pos, inset, font);
1004 } else if (tmptok == "Minipage") {
1005 Inset * inset = new InsetMinipage;
1006 inset->Read(this, lex);
1007 par->InsertInset(pos, inset, font);
1009 } else if (tmptok == "Float") {
1011 string const tmptok = lex.GetString();
1012 Inset * inset = new InsetFloat(tmptok);
1013 inset->Read(this, lex);
1014 par->InsertInset(pos, inset, font);
1016 } else if (tmptok == "List") {
1017 Inset * inset = new InsetList;
1018 inset->Read(this, lex);
1019 par->InsertInset(pos, inset, font);
1021 } else if (tmptok == "Theorem") {
1022 Inset * inset = new InsetList;
1023 inset->Read(this, lex);
1024 par->InsertInset(pos, inset, font);
1026 } else if (tmptok == "Caption") {
1027 Inset * inset = new InsetCaption;
1028 inset->Read(this, lex);
1029 par->InsertInset(pos, inset, font);
1031 } else if (tmptok == "GRAPHICS") {
1032 Inset * inset = new InsetGraphics;
1033 inset->Read(this, lex);
1034 par->InsertInset(pos, inset, font);
1036 } else if (tmptok == "LatexCommand") {
1037 InsetCommandParams inscmd;
1040 if (inscmd.getCmdName() == "cite") {
1041 inset = new InsetCitation(inscmd);
1042 } else if (inscmd.getCmdName() == "bibitem") {
1043 lex.printError("Wrong place for bibitem");
1044 inset = new InsetBibKey(inscmd);
1045 } else if (inscmd.getCmdName() == "BibTeX") {
1046 inset = new InsetBibtex(inscmd, this);
1047 } else if (inscmd.getCmdName() == "index") {
1048 inset = new InsetIndex(inscmd);
1049 } else if (inscmd.getCmdName() == "include") {
1050 inset = new InsetInclude(inscmd, this);
1051 } else if (inscmd.getCmdName() == "label") {
1052 inset = new InsetLabel(inscmd);
1053 } else if (inscmd.getCmdName() == "url"
1054 || inscmd.getCmdName() == "htmlurl") {
1055 inset = new InsetUrl(inscmd);
1056 } else if (inscmd.getCmdName() == "ref"
1057 || inscmd.getCmdName() == "pageref"
1058 || inscmd.getCmdName() == "vref"
1059 || inscmd.getCmdName() == "vpageref"
1060 || inscmd.getCmdName() == "prettyref") {
1061 if (!inscmd.getOptions().empty()
1062 || !inscmd.getContents().empty()) {
1063 inset = new InsetRef(inscmd);
1065 } else if (inscmd.getCmdName() == "tableofcontents"
1066 || inscmd.getCmdName() == "listofalgorithms"
1067 || inscmd.getCmdName() == "listoffigures"
1068 || inscmd.getCmdName() == "listoftables") {
1069 inset = new InsetTOC(inscmd);
1070 } else if (inscmd.getCmdName() == "printindex") {
1071 inset = new InsetPrintIndex(inscmd);
1072 } else if (inscmd.getCmdName() == "lyxparent") {
1073 inset = new InsetParent(inscmd, this);
1077 par->InsertInset(pos, inset, font);
1084 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1088 string const token(lex.GetString());
1089 if (token == "\\lyxformat") { // the first token _must_ be...
1091 format = lex.GetFloat();
1093 if (LYX_FORMAT - format > 0.05) {
1095 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1096 LYX_FORMAT, format);
1098 if (format - LYX_FORMAT > 0.05) {
1099 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1100 LYX_FORMAT, format);
1102 bool the_end = readLyXformat2(lex, par);
1103 // Formats >= 2.13 support "\the_end" marker
1110 WriteAlert(_("Warning!"),
1111 _("Reading of document is not complete"),
1112 _("Maybe the document is truncated"));
1113 // We simulate a safe reading anyways to allow
1114 // users to take the chance... (Asger)
1118 WriteAlert(_("ERROR!"),
1119 _("Old LyX file format found. "
1120 "Use LyX 0.10.x to read this!"));
1124 } else { // "\\lyxformat" not found
1125 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1128 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1134 // Should probably be moved to somewhere else: BufferView? LyXView?
1135 bool Buffer::save() const
1137 // We don't need autosaves in the immediate future. (Asger)
1138 resetAutosaveTimers();
1142 if (lyxrc.make_backup) {
1143 s = fileName() + '~';
1144 if (!lyxrc.backupdir_path.empty())
1145 s = AddName(lyxrc.backupdir_path,
1146 subst(CleanupPath(s),'/','!'));
1148 // Rename is the wrong way of making a backup,
1149 // this is the correct way.
1150 /* truss cp fil fil2:
1151 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1152 stat("LyXVC.lyx", 0xEFFFF688) = 0
1153 open("LyXVC.lyx", O_RDONLY) = 3
1154 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1155 fstat(4, 0xEFFFF508) = 0
1156 fstat(3, 0xEFFFF508) = 0
1157 read(3, " # T h i s f i l e w".., 8192) = 5579
1158 write(4, " # T h i s f i l e w".., 5579) = 5579
1159 read(3, 0xEFFFD4A0, 8192) = 0
1162 chmod("LyXVC3.lyx", 0100644) = 0
1163 lseek(0, 0, SEEK_CUR) = 46440
1167 // Should proabaly have some more error checking here.
1168 // Should be cleaned up in 0.13, at least a bit.
1169 // Doing it this way, also makes the inodes stay the same.
1170 // This is still not a very good solution, in particular we
1171 // might loose the owner of the backup.
1172 FileInfo finfo(fileName());
1173 if (finfo.exist()) {
1174 mode_t fmode = finfo.getMode();
1175 struct utimbuf times = {
1176 finfo.getAccessTime(),
1177 finfo.getModificationTime() };
1179 ifstream ifs(fileName().c_str());
1180 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1185 ::chmod(s.c_str(), fmode);
1187 if (::utime(s.c_str(), ×)) {
1188 lyxerr << "utime error." << endl;
1191 lyxerr << "LyX was not able to make "
1192 "backupcopy. Beware." << endl;
1197 if (writeFile(fileName(), false)) {
1199 removeAutosaveFile(fileName());
1201 // Saving failed, so backup is not backup
1202 if (lyxrc.make_backup) {
1203 lyx::rename(s, fileName());
1211 // Returns false if unsuccesful
1212 bool Buffer::writeFile(string const & fname, bool flag) const
1214 // if flag is false writeFile will not create any GUI
1215 // warnings, only cerr.
1216 // Needed for autosave in background or panic save (Matthias 120496)
1218 if (read_only && (fname == filename)) {
1219 // Here we should come with a question if we should
1220 // perform the write anyway.
1222 lyxerr << _("Error! Document is read-only: ")
1225 WriteAlert(_("Error! Document is read-only: "),
1230 FileInfo finfo(fname);
1231 if (finfo.exist() && !finfo.writable()) {
1232 // Here we should come with a question if we should
1233 // try to do the save anyway. (i.e. do a chmod first)
1235 lyxerr << _("Error! Cannot write file: ")
1238 WriteFSAlert(_("Error! Cannot write file: "),
1243 ofstream ofs(fname.c_str());
1246 lyxerr << _("Error! Cannot open file: ")
1249 WriteFSAlert(_("Error! Cannot open file: "),
1255 // Use the standard "C" locale for file output.
1256 ofs.imbue(std::locale::classic());
1259 // The top of the file should not be written by params.
1261 // write out a comment in the top of the file
1262 ofs << '#' << LYX_DOCVERSION
1263 << " created this file. For more info see http://www.lyx.org/\n";
1264 ofs.setf(ios::showpoint|ios::fixed);
1267 char dummy_format[512];
1268 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1269 ofs << "\\lyxformat " << dummy_format << "\n";
1271 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1273 // now write out the buffer paramters.
1274 params.writeFile(ofs);
1276 char footnoteflag = 0;
1279 // this will write out all the paragraphs
1280 // using recursive descent.
1281 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1283 // Write marker that shows file is complete
1284 ofs << "\n\\the_end" << endl;
1286 // how to check if close went ok?
1291 void Buffer::writeFileAscii(string const & fname, int linelen)
1295 char footnoteflag = 0;
1298 LyXParagraph::size_type i;
1301 int ltype_depth = 0;
1304 int currlinelen = 0;
1306 bool ref_printed = false;
1308 ofstream ofs(fname.c_str());
1310 WriteFSAlert(_("Error: Cannot write file:"), fname);
1314 string const fname1 = TmpFileName();
1315 LyXParagraph * par = paragraph;
1321 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1325 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1330 /* begins a footnote environment ? */
1331 if (footnoteflag != par->footnoteflag) {
1332 footnoteflag = par->footnoteflag;
1334 j = strlen(string_footnotekinds[par->footnotekind])+4;
1335 if (currlinelen + j > linelen)
1338 << string_footnotekinds[par->footnotekind] << "] ";
1344 /* begins or ends a deeper area ?*/
1345 if (depth != par->depth) {
1346 if (par->depth > depth) {
1347 while (par->depth > depth) {
1352 while (par->depth < depth) {
1358 /* First write the layout */
1359 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1360 if (tmp == "Itemize") {
1362 ltype_depth = depth+1;
1363 } else if (tmp == "Enumerate") {
1365 ltype_depth = depth+1;
1366 } else if (contains(tmp, "ection")) {
1368 ltype_depth = depth+1;
1369 } else if (contains(tmp, "aragraph")) {
1371 ltype_depth = depth+1;
1372 } else if (tmp == "Description") {
1374 ltype_depth = depth+1;
1375 } else if (tmp == "Abstract") {
1378 } else if (tmp == "Bibliography") {
1386 /* maybe some vertical spaces */
1388 /* the labelwidthstring used in lists */
1392 /* some pagebreaks? */
1396 /* what about the alignment */
1399 /* dummy layout, that means a footnote ended */
1400 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1404 lyxerr << "Should this ever happen?" << endl;
1409 LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1411 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1412 if (!i && !footnoteflag && !noparbreak){
1414 for(j = 0; j < depth; ++j)
1416 currlinelen = depth * 2;
1418 case 0: /* Standard */
1419 case 4: /* (Sub)Paragraph */
1420 case 5: /* Description */
1422 case 6: /* Abstract */
1423 ofs << "Abstract\n\n";
1425 case 7: /* Bibliography */
1427 ofs << "References\n\n";
1432 ofs << par->labelstring << " ";
1435 if (ltype_depth > depth) {
1436 for(j = ltype_depth - 1; j > depth; --j)
1438 currlinelen += (ltype_depth-depth)*2;
1441 LyXFont font2 = par->GetFontSettings(params, i);
1442 if (font1.latex() != font2.latex()) {
1443 if (font2.latex() == LyXFont::OFF)
1450 c = par->GetChar(i);
1454 case LyXParagraph::META_INSET:
1455 if ((inset = par->GetInset(i))) {
1457 inset->Ascii(this, ofs);
1458 currlinelen += (ofs.tellp() - fpos);
1459 actpos += (ofs.tellp() - fpos) - 1;
1462 case LyXParagraph::META_NEWLINE:
1464 for(j = 0; j < depth; ++j)
1466 currlinelen = depth * 2;
1467 if (ltype_depth > depth) {
1468 for(j = ltype_depth;
1471 currlinelen += (ltype_depth - depth) * 2;
1474 case LyXParagraph::META_HFILL:
1481 if (currlinelen > linelen - 10
1482 && c == ' ' && i + 2 < par->size()) {
1484 for(j = 0; j < depth; ++j)
1486 currlinelen = depth * 2;
1487 if (ltype_depth > depth) {
1488 for(j = ltype_depth;
1491 currlinelen += (ltype_depth-depth)*2;
1493 } else if (c != '\0')
1496 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1508 void Buffer::makeLaTeXFile(string const & fname,
1509 string const & original_path,
1510 bool nice, bool only_body)
1512 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1514 niceFile = nice; // this will be used by Insetincludes.
1516 tex_code_break_column = lyxrc.ascii_linelen;
1518 LyXTextClass const & tclass =
1519 textclasslist.TextClass(params.textclass);
1521 ofstream ofs(fname.c_str());
1523 WriteFSAlert(_("Error: Cannot open file: "), fname);
1527 // validate the buffer.
1528 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1529 LaTeXFeatures features(params, tclass.numLayouts());
1531 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1534 // The starting paragraph of the coming rows is the
1535 // first paragraph of the document. (Asger)
1536 texrow.start(paragraph, 0);
1538 if (!only_body && nice) {
1539 ofs << "%% " LYX_DOCVERSION " created this file. "
1540 "For more info, see http://www.lyx.org/.\n"
1541 "%% Do not edit unless you really know what "
1546 lyxerr.debug() << "lyx header finished" << endl;
1547 // There are a few differences between nice LaTeX and usual files:
1548 // usual is \batchmode and has a
1549 // special input@path to allow the including of figures
1550 // with either \input or \includegraphics (what figinsets do).
1551 // batchmode is not set if there is a tex_code_break_column.
1552 // In this case somebody is interested in the generated LaTeX,
1553 // so this is OK. input@path is set when the actual parameter
1554 // original_path is set. This is done for usual tex-file, but not
1555 // for nice-latex-file. (Matthias 250696)
1558 // code for usual, NOT nice-latex-file
1559 ofs << "\\batchmode\n"; // changed
1560 // from \nonstopmode
1563 if (!original_path.empty()) {
1564 ofs << "\\makeatletter\n"
1565 << "\\def\\input@path{{"
1566 << original_path << "/}}\n"
1567 << "\\makeatother\n";
1573 ofs << "\\documentclass";
1575 string options; // the document class options.
1577 if (tokenPos(tclass.opt_fontsize(),
1578 '|', params.fontsize) >= 0) {
1579 // only write if existing in list (and not default)
1580 options += params.fontsize;
1585 if (!params.use_geometry &&
1586 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1587 switch (params.papersize) {
1588 case BufferParams::PAPER_A4PAPER:
1589 options += "a4paper,";
1591 case BufferParams::PAPER_USLETTER:
1592 options += "letterpaper,";
1594 case BufferParams::PAPER_A5PAPER:
1595 options += "a5paper,";
1597 case BufferParams::PAPER_B5PAPER:
1598 options += "b5paper,";
1600 case BufferParams::PAPER_EXECUTIVEPAPER:
1601 options += "executivepaper,";
1603 case BufferParams::PAPER_LEGALPAPER:
1604 options += "legalpaper,";
1610 if (params.sides != tclass.sides()) {
1611 switch (params.sides) {
1612 case LyXTextClass::OneSide:
1613 options += "oneside,";
1615 case LyXTextClass::TwoSides:
1616 options += "twoside,";
1623 if (params.columns != tclass.columns()) {
1624 if (params.columns == 2)
1625 options += "twocolumn,";
1627 options += "onecolumn,";
1630 if (!params.use_geometry
1631 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1632 options += "landscape,";
1634 // language should be a parameter to \documentclass
1635 bool use_babel = false;
1636 if (params.language_info->lang() == "hebrew") // This seems necessary
1637 features.UsedLanguages.insert(default_language);
1638 if (params.language != "default" ||
1639 !features.UsedLanguages.empty() ) {
1641 for (LaTeXFeatures::LanguageList::const_iterator cit =
1642 features.UsedLanguages.begin();
1643 cit != features.UsedLanguages.end(); ++cit)
1644 options += (*cit)->lang() + ",";
1645 options += params.language_info->lang() + ',';
1648 // the user-defined options
1649 if (!params.options.empty()) {
1650 options += params.options + ',';
1653 if (!options.empty()){
1654 options = strip(options, ',');
1655 ofs << '[' << options << ']';
1659 << textclasslist.LatexnameOfClass(params.textclass)
1662 // end of \documentclass defs
1664 // font selection must be done before loading fontenc.sty
1665 if (params.fonts != "default") {
1666 ofs << "\\usepackage{" << params.fonts << "}\n";
1669 // this one is not per buffer
1670 if (lyxrc.fontenc != "default") {
1671 ofs << "\\usepackage[" << lyxrc.fontenc
1676 if (params.inputenc == "auto") {
1677 string const doc_encoding =
1678 params.language_info->encoding()->LatexName();
1680 // Create a list with all the input encodings used
1682 set<string> encodings;
1683 for (LaTeXFeatures::LanguageList::const_iterator it =
1684 features.UsedLanguages.begin();
1685 it != features.UsedLanguages.end(); ++it)
1686 if ((*it)->encoding()->LatexName() != doc_encoding)
1687 encodings.insert((*it)->encoding()->LatexName());
1689 ofs << "\\usepackage[";
1690 for (set<string>::const_iterator it = encodings.begin();
1691 it != encodings.end(); ++it)
1693 ofs << doc_encoding << "]{inputenc}\n";
1695 } else if (params.inputenc != "default") {
1696 ofs << "\\usepackage[" << params.inputenc
1701 // At the very beginning the text parameters.
1702 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1703 switch (params.paperpackage) {
1704 case BufferParams::PACKAGE_A4:
1705 ofs << "\\usepackage{a4}\n";
1708 case BufferParams::PACKAGE_A4WIDE:
1709 ofs << "\\usepackage{a4wide}\n";
1712 case BufferParams::PACKAGE_WIDEMARGINSA4:
1713 ofs << "\\usepackage[widemargins]{a4}\n";
1718 if (params.use_geometry) {
1719 ofs << "\\usepackage{geometry}\n";
1721 ofs << "\\geometry{verbose";
1722 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1723 ofs << ",landscape";
1724 switch (params.papersize2) {
1725 case BufferParams::VM_PAPER_CUSTOM:
1726 if (!params.paperwidth.empty())
1727 ofs << ",paperwidth="
1728 << params.paperwidth;
1729 if (!params.paperheight.empty())
1730 ofs << ",paperheight="
1731 << params.paperheight;
1733 case BufferParams::VM_PAPER_USLETTER:
1734 ofs << ",letterpaper";
1736 case BufferParams::VM_PAPER_USLEGAL:
1737 ofs << ",legalpaper";
1739 case BufferParams::VM_PAPER_USEXECUTIVE:
1740 ofs << ",executivepaper";
1742 case BufferParams::VM_PAPER_A3:
1745 case BufferParams::VM_PAPER_A4:
1748 case BufferParams::VM_PAPER_A5:
1751 case BufferParams::VM_PAPER_B3:
1754 case BufferParams::VM_PAPER_B4:
1757 case BufferParams::VM_PAPER_B5:
1761 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1762 switch (lyxrc.default_papersize) {
1763 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1764 case BufferParams::PAPER_USLETTER:
1765 ofs << ",letterpaper";
1767 case BufferParams::PAPER_LEGALPAPER:
1768 ofs << ",legalpaper";
1770 case BufferParams::PAPER_EXECUTIVEPAPER:
1771 ofs << ",executivepaper";
1773 case BufferParams::PAPER_A3PAPER:
1776 case BufferParams::PAPER_A4PAPER:
1779 case BufferParams::PAPER_A5PAPER:
1782 case BufferParams::PAPER_B5PAPER:
1787 if (!params.topmargin.empty())
1788 ofs << ",tmargin=" << params.topmargin;
1789 if (!params.bottommargin.empty())
1790 ofs << ",bmargin=" << params.bottommargin;
1791 if (!params.leftmargin.empty())
1792 ofs << ",lmargin=" << params.leftmargin;
1793 if (!params.rightmargin.empty())
1794 ofs << ",rmargin=" << params.rightmargin;
1795 if (!params.headheight.empty())
1796 ofs << ",headheight=" << params.headheight;
1797 if (!params.headsep.empty())
1798 ofs << ",headsep=" << params.headsep;
1799 if (!params.footskip.empty())
1800 ofs << ",footskip=" << params.footskip;
1804 if (params.use_amsmath
1805 && !tclass.provides(LyXTextClass::amsmath)) {
1806 ofs << "\\usepackage{amsmath}\n";
1810 if (tokenPos(tclass.opt_pagestyle(),
1811 '|', params.pagestyle) >= 0) {
1812 if (params.pagestyle == "fancy") {
1813 ofs << "\\usepackage{fancyhdr}\n";
1816 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1820 // We try to load babel late, in case it interferes
1821 // with other packages.
1823 ofs << lyxrc.language_package << endl;
1827 if (params.secnumdepth != tclass.secnumdepth()) {
1828 ofs << "\\setcounter{secnumdepth}{"
1829 << params.secnumdepth
1833 if (params.tocdepth != tclass.tocdepth()) {
1834 ofs << "\\setcounter{tocdepth}{"
1840 if (params.paragraph_separation) {
1841 switch (params.defskip.kind()) {
1842 case VSpace::SMALLSKIP:
1843 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1845 case VSpace::MEDSKIP:
1846 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1848 case VSpace::BIGSKIP:
1849 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1851 case VSpace::LENGTH:
1852 ofs << "\\setlength\\parskip{"
1853 << params.defskip.length().asLatexString()
1856 default: // should never happen // Then delete it.
1857 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1862 ofs << "\\setlength\\parindent{0pt}\n";
1866 // Now insert the LyX specific LaTeX commands...
1868 // The optional packages;
1869 string preamble(features.getPackages());
1871 // this might be useful...
1872 preamble += "\n\\makeatletter\n";
1874 // Some macros LyX will need
1875 string tmppreamble(features.getMacros());
1877 if (!tmppreamble.empty()) {
1878 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1879 "LyX specific LaTeX commands.\n"
1880 + tmppreamble + '\n';
1883 // the text class specific preamble
1884 tmppreamble = features.getTClassPreamble();
1885 if (!tmppreamble.empty()) {
1886 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1887 "Textclass specific LaTeX commands.\n"
1888 + tmppreamble + '\n';
1891 /* the user-defined preamble */
1892 if (!params.preamble.empty()) {
1893 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1894 "User specified LaTeX commands.\n"
1895 + params.preamble + '\n';
1898 preamble += "\\makeatother\n";
1900 // Itemize bullet settings need to be last in case the user
1901 // defines their own bullets that use a package included
1902 // in the user-defined preamble -- ARRae
1903 // Actually it has to be done much later than that
1904 // since some packages like frenchb make modifications
1905 // at \begin{document} time -- JMarc
1907 for (int i = 0; i < 4; ++i) {
1908 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1909 if (bullets_def.empty())
1910 bullets_def="\\AtBeginDocument{\n";
1911 bullets_def += " \\renewcommand{\\labelitemi";
1913 // `i' is one less than the item to modify
1920 bullets_def += "ii";
1926 bullets_def += "}{" +
1927 params.user_defined_bullets[i].getText()
1932 if (!bullets_def.empty())
1933 preamble += bullets_def + "}\n\n";
1935 for (int j = countChar(preamble, '\n'); j-- ;) {
1942 ofs << "\\begin{document}\n";
1945 lyxerr.debug() << "preamble finished, now the body." << endl;
1946 if (!lyxrc.language_auto_begin && params.language != "default") {
1947 ofs << subst(lyxrc.language_command_begin, "$$lang",
1953 latexParagraphs(ofs, paragraph, 0, texrow);
1955 // add this just in case after all the paragraphs
1959 if (!lyxrc.language_auto_end && params.language != "default") {
1960 ofs << subst(lyxrc.language_command_end, "$$lang",
1967 ofs << "\\end{document}\n";
1970 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1972 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1976 // Just to be sure. (Asger)
1979 // tex_code_break_column's value is used to decide
1980 // if we are in batchmode or not (within mathed_write()
1981 // in math_write.C) so we must set it to a non-zero
1982 // value when we leave otherwise we save incorrect .lyx files.
1983 tex_code_break_column = lyxrc.ascii_linelen;
1987 lyxerr << "File was not closed properly." << endl;
1990 lyxerr.debug() << "Finished making latex file." << endl;
1995 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
1997 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
1998 LyXParagraph * endpar, TexRow & texrow) const
2000 bool was_title = false;
2001 bool already_title = false;
2002 std::ostringstream ftnote;
2007 while (par != endpar) {
2010 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2013 LyXLayout const & layout =
2014 textclasslist.Style(params.textclass,
2017 if (layout.intitle) {
2018 if (already_title) {
2019 lyxerr <<"Error in latexParagraphs: You"
2020 " should not mix title layouts"
2021 " with normal ones." << endl;
2024 } else if (was_title && !already_title) {
2025 ofs << "\\maketitle\n";
2027 already_title = true;
2030 // We are at depth 0 so we can just use
2031 // ordinary \footnote{} generation
2032 // flag this with ftcount
2034 if (layout.isEnvironment()
2035 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2036 par = par->TeXEnvironment(this, params, ofs, texrow
2038 ,ftnote, ft_texrow, ftcount
2042 par = par->TeXOnePar(this, params, ofs, texrow, false
2045 ftnote, ft_texrow, ftcount
2050 // Write out what we've generated...
2053 ofs << "\\addtocounter{footnote}{-"
2057 ofs << ftnote.str();
2058 texrow += ft_texrow;
2060 // The extra .c_str() is needed when we use
2061 // lyxstring instead of the STL string class.
2062 ftnote.str(string().c_str());
2067 // It might be that we only have a title in this document
2068 if (was_title && !already_title) {
2069 ofs << "\\maketitle\n";
2075 bool Buffer::isLatex() const
2077 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2081 bool Buffer::isLinuxDoc() const
2083 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2087 bool Buffer::isLiterate() const
2089 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2093 bool Buffer::isDocBook() const
2095 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2099 bool Buffer::isSGML() const
2101 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2102 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2106 void Buffer::sgmlOpenTag(ostream & os, int depth,
2107 string const & latexname) const
2109 os << string(depth, ' ') << "<" << latexname << ">\n";
2113 void Buffer::sgmlCloseTag(ostream & os, int depth,
2114 string const & latexname) const
2116 os << string(depth, ' ') << "</" << latexname << ">\n";
2120 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2122 LyXParagraph * par = paragraph;
2124 niceFile = nice; // this will be used by Insetincludes.
2126 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2127 string environment_stack[10];
2130 int depth = 0; // paragraph depth
2132 ofstream ofs(fname.c_str());
2135 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2139 LyXTextClass const & tclass =
2140 textclasslist.TextClass(params.textclass);
2142 LaTeXFeatures features(params, tclass.numLayouts());
2146 tex_code_break_column = lyxrc.ascii_linelen;
2148 //tex_code_break_column = 0;
2153 string sgml_includedfiles=features.getIncludedFiles();
2155 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2156 ofs << "<!doctype linuxdoc system>\n\n";
2158 ofs << "<!doctype linuxdoc system [ "
2159 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2162 if(params.options.empty())
2163 sgmlOpenTag(ofs, 0, top_element);
2165 string top = top_element;
2167 top += params.options;
2168 sgmlOpenTag(ofs, 0, top);
2172 ofs << "<!-- " << LYX_DOCVERSION
2173 << " created this file. For more info see http://www.lyx.org/"
2177 int desc_on = 0; // description mode
2178 LyXLayout const & style =
2179 textclasslist.Style(params.textclass,
2182 // treat <toc> as a special case for compatibility with old code
2183 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2184 Inset * inset = par->GetInset(0);
2185 Inset::Code lyx_code = inset->LyxCode();
2186 if (lyx_code == Inset::TOC_CODE){
2187 string const temp = "toc";
2188 sgmlOpenTag(ofs, depth, temp);
2192 linuxDocHandleFootnote(ofs, par, depth);
2198 // environment tag closing
2199 for (; depth > par->depth; --depth) {
2200 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2201 environment_stack[depth].erase();
2204 // write opening SGML tags
2205 switch (style.latextype) {
2206 case LATEX_PARAGRAPH:
2207 if(depth == par->depth
2208 && !environment_stack[depth].empty()) {
2209 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2210 environment_stack[depth].erase();
2216 sgmlOpenTag(ofs, depth, style.latexname());
2221 LinuxDocError(par, 0,
2222 _("Error : Wrong depth for"
2223 " LatexType Command.\n"));
2225 if (!environment_stack[depth].empty()){
2226 sgmlCloseTag(ofs, depth,
2227 environment_stack[depth]);
2231 environment_stack[depth].erase();
2232 sgmlOpenTag(ofs, depth, style.latexname());
2235 case LATEX_ENVIRONMENT:
2236 case LATEX_ITEM_ENVIRONMENT:
2237 if (depth == par->depth
2238 && environment_stack[depth] != style.latexname()
2239 && !environment_stack[depth].empty()) {
2241 sgmlCloseTag(ofs, depth,
2242 environment_stack[depth]);
2243 environment_stack[depth].erase();
2245 if (depth < par->depth) {
2247 environment_stack[depth].erase();
2249 if (environment_stack[depth] != style.latexname()) {
2251 string const temp = "p";
2252 sgmlOpenTag(ofs, depth, temp);
2254 environment_stack[depth] = style.latexname();
2255 sgmlOpenTag(ofs, depth,
2256 environment_stack[depth]);
2258 if(style.latextype == LATEX_ENVIRONMENT) break;
2260 desc_on = (style.labeltype == LABEL_MANUAL);
2267 sgmlOpenTag(ofs, depth + 1, item_name);
2270 sgmlOpenTag(ofs, depth, style.latexname());
2277 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2281 linuxDocHandleFootnote(ofs, par, depth);
2283 while(par && par->IsDummy());
2287 // write closing SGML tags
2288 switch(style.latextype) {
2290 case LATEX_ENVIRONMENT:
2291 case LATEX_ITEM_ENVIRONMENT:
2294 sgmlCloseTag(ofs, depth, style.latexname());
2300 for(; depth > 0; --depth)
2301 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2303 if(!environment_stack[depth].empty())
2304 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2308 sgmlCloseTag(ofs, 0, top_element);
2312 // How to check for successful close
2317 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2320 string const tag = "footnote";
2322 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2323 sgmlOpenTag(os, depth + 1, tag);
2324 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2325 sgmlCloseTag(os, depth + 1, tag);
2332 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2333 int const depth, int desc_on,
2334 LyXParagraph * & par)
2336 LyXParagraph * tpar = par;
2339 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2341 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2345 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2346 "Caption").second) {
2347 sgmlOpenTag(os, depth + 1, inner_tag);
2349 SimpleDocBookOnePar(os, extra_par, tpar,
2350 desc_on, depth + 2);
2351 sgmlCloseTag(os, depth+1, inner_tag);
2352 if(!extra_par.empty())
2359 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2362 string tag, inner_tag;
2363 string tmp_par, extra_par;
2364 bool inner_span = false;
2367 // Someone should give this enum a proper name (Lgb)
2375 SOME_ENUM last = NO_ONE;
2376 SOME_ENUM present = FOOTNOTE_LIKE;
2378 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2379 if (last == present) {
2381 if (!tmp_par.empty()) {
2384 sgmlCloseTag(os, depth + 1, inner_tag);
2385 sgmlOpenTag(os, depth + 1, inner_tag);
2392 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2394 if (!extra_par.empty()) os << extra_par;
2395 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2398 switch (par->footnotekind) {
2399 case LyXParagraph::FOOTNOTE:
2400 case LyXParagraph::ALGORITHM:
2403 present = FOOTNOTE_LIKE;
2406 case LyXParagraph::MARGIN:
2409 present = MARGIN_LIKE;
2412 case LyXParagraph::FIG:
2413 case LyXParagraph::WIDE_FIG:
2415 inner_tag = "title";
2419 case LyXParagraph::TAB:
2420 case LyXParagraph::WIDE_TAB:
2422 inner_tag = "title";
2427 sgmlOpenTag(os, depth, tag);
2428 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2429 DocBookHandleCaption(os, inner_tag, depth,
2433 sgmlOpenTag(os, depth + 1, inner_tag);
2436 // ignore all caption here, we processed them above!!!
2437 if (par->layout != textclasslist
2438 .NumberOfLayout(params.textclass,
2439 "Caption").second) {
2440 std::ostringstream ost;
2441 SimpleDocBookOnePar(ost, extra_par, par,
2442 desc_on, depth + 2);
2443 tmp_par += ost.str().c_str();
2445 tmp_par = frontStrip(strip(tmp_par));
2451 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2452 if(!extra_par.empty()) os << extra_par;
2453 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2458 // push a tag in a style stack
2459 void Buffer::push_tag(ostream & os, string const & tag,
2460 int & pos, char stack[5][3])
2462 #warning Use a real stack! (Lgb)
2463 // pop all previous tags
2464 for (int j = pos; j >= 0; --j)
2465 os << "</" << stack[j] << ">";
2468 sprintf(stack[++pos], "%s", tag.c_str());
2471 for (int i = 0; i <= pos; ++i)
2472 os << "<" << stack[i] << ">";
2476 void Buffer::pop_tag(ostream & os, string const & tag,
2477 int & pos, char stack[5][3])
2479 #ifdef WITH_WARNINGS
2480 #warning Use a real stack! (Lgb)
2482 // Please, Lars, do not remove the global variable. I already
2483 // had to reintroduce it twice! (JMarc)
2486 // pop all tags till specified one
2487 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2488 os << "</" << stack[j] << ">";
2491 os << "</" << tag << ">";
2493 // push all tags, but the specified one
2494 for (j = j + 1; j <= pos; ++j) {
2495 os << "<" << stack[j] << ">";
2496 strcpy(stack[j-1], stack[j]);
2502 // Handle internal paragraph parsing -- layout already processed.
2504 // checks, if newcol chars should be put into this line
2505 // writes newline, if necessary.
2507 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2508 const unsigned int newcol)
2511 if (colcount > lyxrc.ascii_linelen) {
2513 colcount = newcol; // assume write after this call
2518 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2519 int desc_on, int const /*depth*/)
2524 LyXParagraph::size_type main_body;
2526 LyXLayout const & style = textclasslist.Style(params.textclass,
2529 char family_type = 0; // family font flag
2530 bool is_bold = false; // series font flag
2531 char shape_type = 0; // shape font flag
2532 bool is_em = false; // emphasis (italic) font flag
2534 int stack_num = -1; // style stack position
2535 // Can this be rewritten to use a std::stack, please. (Lgb)
2536 char stack[5][3]; // style stack
2537 unsigned int char_line_count = 5; // Heuristic choice ;-)
2539 if (style.labeltype != LABEL_MANUAL)
2542 main_body = par->BeginningOfMainBody();
2544 // gets paragraph main font
2546 font1 = style.labelfont;
2551 // parsing main loop
2552 for (LyXParagraph::size_type i = 0;
2553 i < par->size(); ++i) {
2565 LyXFont const font2 = par->getFont(params, i);
2567 if (font1.family() != font2.family()) {
2568 switch(family_type) {
2570 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2571 push_tag(os, "tt", stack_num, stack);
2574 else if (font2.family() == LyXFont::SANS_FAMILY) {
2575 push_tag(os, "sf", stack_num, stack);
2580 pop_tag(os, "tt", stack_num, stack);
2581 if (font2.family() == LyXFont::SANS_FAMILY) {
2582 push_tag(os, "sf", stack_num, stack);
2589 pop_tag(os, "sf", stack_num, stack);
2590 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2591 push_tag(os, "tt", stack_num, stack);
2600 if (font1.series() != font2.series()) {
2601 if (font2.series() == LyXFont::BOLD_SERIES) {
2602 push_tag(os, "bf", stack_num, stack);
2604 } else if (is_bold) {
2605 pop_tag(os, "bf", stack_num, stack);
2610 // handle italic and slanted fonts
2611 if (font1.shape() != font2.shape()) {
2612 switch(shape_type) {
2614 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2615 push_tag(os, "it", stack_num, stack);
2617 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2618 push_tag(os, "sl", stack_num, stack);
2623 pop_tag(os, "it", stack_num, stack);
2624 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2625 push_tag(os, "sl", stack_num, stack);
2632 pop_tag(os, "sl", stack_num, stack);
2633 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2634 push_tag(os, "it", stack_num, stack);
2642 if (font1.emph() != font2.emph()) {
2643 if (font2.emph() == LyXFont::ON) {
2644 push_tag(os, "em", stack_num, stack);
2647 pop_tag(os, "em", stack_num, stack);
2652 c = par->GetChar(i);
2654 if (c == LyXParagraph::META_INSET) {
2655 inset = par->GetInset(i);
2656 inset->Linuxdoc(this, os);
2659 if (font2.latex() == LyXFont::ON) {
2660 // "TeX"-Mode on == > SGML-Mode on.
2662 os << c; // see LaTeX-Generation...
2666 if (par->linuxDocConvertChar(c, sgml_string)
2667 && !style.free_spacing) { // in freespacing
2669 // non-breaking characters
2673 linux_doc_line_break(os, char_line_count, 6);
2677 linux_doc_line_break(os, char_line_count, 1);
2682 char_line_count += sgml_string.length();
2688 // needed if there is an optional argument but no contents
2689 if (main_body > 0 && main_body == par->size()) {
2693 // pop all defined Styles
2694 for (j = stack_num; j >= 0; --j) {
2695 linux_doc_line_break(os,
2697 3 + strlen(stack[j]));
2698 os << "</" << stack[j] << ">";
2701 // resets description flag correctly
2704 // <tag> not closed...
2705 linux_doc_line_break(os, char_line_count, 6);
2709 // fprintf(file, "</p>");
2715 // Print an error message.
2716 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2717 string const & message)
2719 // insert an error marker in text
2720 InsetError * new_inset = new InsetError(message);
2721 par->InsertInset(pos, new_inset);
2724 // This constant defines the maximum number of
2725 // environment layouts that can be nesteded.
2726 // The same applies for command layouts.
2727 // These values should be more than enough.
2728 // José Matos (1999/07/22)
2730 enum { MAX_NEST_LEVEL = 25};
2732 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2734 LyXParagraph * par = paragraph;
2736 niceFile = nice; // this will be used by Insetincludes.
2738 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2739 // Please use a real stack.
2740 string environment_stack[MAX_NEST_LEVEL];
2741 string environment_inner[MAX_NEST_LEVEL];
2742 // Please use a real stack.
2743 string command_stack[MAX_NEST_LEVEL];
2744 bool command_flag= false;
2745 int command_depth= 0, command_base= 0, cmd_depth= 0;
2747 string item_name, command_name;
2748 string c_depth, c_params, tmps;
2750 int depth = 0; // paragraph depth
2751 LyXTextClass const & tclass =
2752 textclasslist.TextClass(params.textclass);
2754 LaTeXFeatures features(params, tclass.numLayouts());
2758 tex_code_break_column = lyxrc.ascii_linelen;
2760 //tex_code_break_column = 0;
2762 ofstream ofs(fname.c_str());
2764 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2771 string sgml_includedfiles=features.getIncludedFiles();
2773 ofs << "<!doctype " << top_element
2774 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2776 if (params.preamble.empty() && sgml_includedfiles.empty())
2779 ofs << "\n [ " << params.preamble
2780 << sgml_includedfiles << " \n]>\n\n";
2782 if(params.options.empty())
2783 sgmlOpenTag(ofs, 0, top_element);
2785 string top = top_element;
2787 top += params.options;
2788 sgmlOpenTag(ofs, 0, top);
2792 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2793 << "\n See http://www.lyx.org/ for more information -->\n";
2796 int desc_on = 0; // description mode
2797 LyXLayout const & style =
2798 textclasslist.Style(params.textclass,
2801 // environment tag closing
2802 for( ; depth > par->depth; --depth) {
2803 if(environment_inner[depth] != "!-- --") {
2804 item_name= "listitem";
2805 sgmlCloseTag(ofs, command_depth + depth,
2807 if( environment_inner[depth] == "varlistentry")
2808 sgmlCloseTag(ofs, depth+command_depth,
2809 environment_inner[depth]);
2811 sgmlCloseTag(ofs, depth + command_depth,
2812 environment_stack[depth]);
2813 environment_stack[depth].erase();
2814 environment_inner[depth].erase();
2817 if(depth == par->depth
2818 && environment_stack[depth] != style.latexname()
2819 && !environment_stack[depth].empty()) {
2820 if(environment_inner[depth] != "!-- --") {
2821 item_name= "listitem";
2822 sgmlCloseTag(ofs, command_depth+depth,
2824 if( environment_inner[depth] == "varlistentry")
2826 depth + command_depth,
2827 environment_inner[depth]);
2830 sgmlCloseTag(ofs, depth + command_depth,
2831 environment_stack[depth]);
2833 environment_stack[depth].erase();
2834 environment_inner[depth].erase();
2837 // Write opening SGML tags.
2838 switch(style.latextype) {
2839 case LATEX_PARAGRAPH:
2840 if(style.latexname() != "dummy")
2841 sgmlOpenTag(ofs, depth+command_depth,
2847 LinuxDocError(par, 0,
2848 _("Error : Wrong depth for "
2849 "LatexType Command.\n"));
2851 command_name = style.latexname();
2853 tmps = style.latexparam();
2854 c_params = split(tmps, c_depth,'|');
2856 cmd_depth= lyx::atoi(c_depth);
2859 if(cmd_depth<command_base) {
2860 for(int j = command_depth;
2861 j >= command_base; --j)
2862 if(!command_stack[j].empty())
2863 sgmlCloseTag(ofs, j, command_stack[j]);
2864 command_depth= command_base= cmd_depth;
2865 } else if(cmd_depth <= command_depth) {
2866 for(int j = command_depth;
2867 j >= cmd_depth; --j)
2869 if(!command_stack[j].empty())
2870 sgmlCloseTag(ofs, j, command_stack[j]);
2871 command_depth= cmd_depth;
2873 command_depth= cmd_depth;
2875 command_depth = command_base = cmd_depth;
2876 command_flag = true;
2878 command_stack[command_depth]= command_name;
2880 // treat label as a special case for
2881 // more WYSIWYM handling.
2882 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2883 Inset * inset = par->GetInset(0);
2884 Inset::Code lyx_code = inset->LyxCode();
2885 if (lyx_code == Inset::LABEL_CODE){
2886 command_name += " id=\"";
2887 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2888 command_name += "\"";
2893 sgmlOpenTag(ofs, depth + command_depth, command_name);
2894 item_name = "title";
2895 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2898 case LATEX_ENVIRONMENT:
2899 case LATEX_ITEM_ENVIRONMENT:
2900 if (depth < par->depth) {
2902 environment_stack[depth].erase();
2905 if (environment_stack[depth] != style.latexname()) {
2906 environment_stack[depth] = style.latexname();
2907 environment_inner[depth] = "!-- --";
2908 sgmlOpenTag(ofs, depth + command_depth,
2909 environment_stack[depth]);
2911 if(environment_inner[depth] != "!-- --") {
2912 item_name= "listitem";
2914 command_depth + depth,
2916 if (environment_inner[depth] == "varlistentry")
2918 depth + command_depth,
2919 environment_inner[depth]);
2923 if(style.latextype == LATEX_ENVIRONMENT) {
2924 if(!style.latexparam().empty())
2925 sgmlOpenTag(ofs, depth + command_depth,
2926 style.latexparam());
2930 desc_on = (style.labeltype == LABEL_MANUAL);
2933 environment_inner[depth]= "varlistentry";
2935 environment_inner[depth]= "listitem";
2937 sgmlOpenTag(ofs, depth + 1 + command_depth,
2938 environment_inner[depth]);
2942 sgmlOpenTag(ofs, depth + 1 + command_depth,
2946 sgmlOpenTag(ofs, depth + 1 + command_depth,
2951 sgmlOpenTag(ofs, depth + command_depth,
2960 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
2961 depth + 1 + command_depth);
2964 DocBookHandleFootnote(ofs, par,
2965 depth + 1 + command_depth);
2967 while(par && par->IsDummy());
2970 // write closing SGML tags
2971 switch(style.latextype) {
2974 sgmlCloseTag(ofs, depth + command_depth, end_tag);
2976 case LATEX_ENVIRONMENT:
2977 if(!style.latexparam().empty())
2978 sgmlCloseTag(ofs, depth + command_depth,
2979 style.latexparam());
2981 case LATEX_ITEM_ENVIRONMENT:
2982 if(desc_on == 1) break;
2984 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2986 case LATEX_PARAGRAPH:
2987 if(style.latexname() != "dummy")
2988 sgmlCloseTag(ofs, depth + command_depth,
2992 sgmlCloseTag(ofs, depth + command_depth,
2999 for(; depth >= 0; --depth) {
3000 if(!environment_stack[depth].empty()) {
3001 if(environment_inner[depth] != "!-- --") {
3002 item_name= "listitem";
3003 sgmlCloseTag(ofs, command_depth + depth,
3005 if( environment_inner[depth] == "varlistentry")
3006 sgmlCloseTag(ofs, depth + command_depth,
3007 environment_inner[depth]);
3010 sgmlCloseTag(ofs, depth + command_depth,
3011 environment_stack[depth]);
3015 for(int j = command_depth; j >= command_base; --j)
3016 if(!command_stack[j].empty())
3017 sgmlCloseTag(ofs, j, command_stack[j]);
3021 sgmlCloseTag(ofs, 0, top_element);
3025 // How to check for successful close
3029 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3030 LyXParagraph * par, int & desc_on,
3033 bool emph_flag = false;
3035 LyXLayout const & style = textclasslist.Style(params.textclass,
3038 LyXParagraph::size_type main_body;
3039 if (style.labeltype != LABEL_MANUAL)
3042 main_body = par->BeginningOfMainBody();
3044 // gets paragraph main font
3045 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3047 int char_line_count = depth;
3048 if(!style.free_spacing)
3049 for (int j = 0; j < depth; ++j)
3052 // parsing main loop
3053 for (LyXParagraph::size_type i = 0;
3054 i < par->size(); ++i) {
3055 LyXFont font2 = par->getFont(params, i);
3057 // handle <emphasis> tag
3058 if (font1.emph() != font2.emph() && i) {
3059 if (font2.emph() == LyXFont::ON) {
3063 os << "</emphasis>";
3068 char c = par->GetChar(i);
3070 if (c == LyXParagraph::META_INSET) {
3071 Inset * inset = par->GetInset(i);
3072 std::ostringstream ost;
3073 inset->DocBook(this, ost);
3074 string tmp_out = ost.str().c_str();
3077 // This code needs some explanation:
3078 // Two insets are treated specially
3079 // label if it is the first element in a command paragraph
3081 // graphics inside tables or figure floats can't go on
3082 // title (the equivalente in latex for this case is caption
3083 // and title should come first
3086 if(desc_on!= 3 || i!= 0) {
3087 if(!tmp_out.empty() && tmp_out[0] == '@') {
3089 extra += frontStrip(tmp_out, '@');
3091 os << frontStrip(tmp_out, '@');
3096 } else if (font2.latex() == LyXFont::ON) {
3097 // "TeX"-Mode on ==> SGML-Mode on.
3103 if (par->linuxDocConvertChar(c, sgml_string)
3104 && !style.free_spacing) { // in freespacing
3106 // non-breaking characters
3110 os << "\n</term><listitem><para>";
3122 // needed if there is an optional argument but no contents
3123 if (main_body > 0 && main_body == par->size()) {
3127 os << "</emphasis>";
3130 // resets description flag correctly
3133 // <term> not closed...
3141 int Buffer::runLiterate()
3143 if (!users->text) return 0;
3145 ProhibitInput(users);
3147 // get LaTeX-Filename
3148 string name = getLatexName();
3149 // get Literate-Filename
3150 string lit_name = OnlyFilename(ChangeExtension (getLatexName(),
3151 lyxrc.literate_extension));
3153 string path = OnlyPath(filename);
3155 string org_path = path;
3156 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3160 Path p(path); // path to Literate file
3161 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3163 // Remove all error insets
3164 bool removedErrorInsets = users->removeAutoInsets();
3166 // generate the Literate file if necessary
3167 makeLaTeXFile(lit_name, org_path, false);
3169 string latex_command = lyxrc.pdf_mode ?
3170 lyxrc.pdflatex_command : lyxrc.latex_command;
3171 Literate literate(latex_command, name, filepath,
3173 lyxrc.literate_command, lyxrc.literate_error_filter,
3174 lyxrc.build_command, lyxrc.build_error_filter);
3176 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3178 // check return value from literate.weave().
3179 if ((res & Literate::NO_LOGFILE)) {
3180 WriteAlert(_("Literate command did not work!"),
3181 _("Missing log file:"), name);
3182 } else if ((res & Literate::ERRORS)) {
3183 users->owner()->getMiniBuffer()->Set(_("Done"));
3184 // Insert all errors as errors boxes
3185 users->insertErrors(terr);
3187 // Dvi should also be kept dirty if the latex run
3188 // ends up with errors. However it should be possible
3189 // to view a dirty dvi too.
3191 //no errors or any other things to think about so:
3192 users->owner()->getMiniBuffer()->Set(_("Done"));
3195 // if we removed error insets before we ran LaTeX or if we inserted
3196 // error insets after we ran LaTeX this must be run:
3197 if (removedErrorInsets || (res & Literate::ERRORS)){
3200 //users->updateScrollbar();
3204 return literate.getNumErrors();
3208 int Buffer::buildProgram()
3210 if (!users->text) return 0;
3212 ProhibitInput(users);
3214 // get LaTeX-Filename
3215 string name = getLatexName();
3216 // get Literate-Filename
3217 string lit_name = OnlyFilename(ChangeExtension(getLatexName(),
3218 lyxrc.literate_extension));
3220 string path = OnlyPath(filename);
3222 string org_path = path;
3223 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3227 Path p(path); // path to Literate file
3228 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3230 // Remove all error insets
3231 bool removedErrorInsets = users->removeAutoInsets();
3233 // generate the LaTeX file if necessary
3234 if (!isNwClean() || removedErrorInsets) {
3235 makeLaTeXFile(lit_name, org_path, false);
3239 string latex_command = lyxrc.pdf_mode ?
3240 lyxrc.pdflatex_command : lyxrc.latex_command;
3241 Literate literate(latex_command, name, filepath,
3243 lyxrc.literate_command, lyxrc.literate_error_filter,
3244 lyxrc.build_command, lyxrc.build_error_filter);
3246 int const res = literate.build(terr, users->owner()->getMiniBuffer());
3248 // check return value from literate.build().
3249 if ((res & Literate::NO_LOGFILE)) {
3250 WriteAlert(_("Build did not work!"),
3251 _("Missing log file:"), name);
3252 } else if ((res & Literate::ERRORS)) {
3253 users->owner()->getMiniBuffer()->Set(_("Done"));
3254 // Insert all errors as errors boxes
3255 users->insertErrors(terr);
3257 // Literate files should also be kept dirty if the literate
3258 // command run ends up with errors.
3260 //no errors or any other things to think about so:
3261 users->owner()->getMiniBuffer()->Set(_("Done"));
3265 // if we removed error insets before we ran Literate/Build or
3266 // if we inserted error insets after we ran Literate/Build this
3268 if (removedErrorInsets || (res & Literate::ERRORS)){
3271 //users->updateScrollbar();
3275 return literate.getNumErrors();
3279 // This should be enabled when the Chktex class is implemented. (Asger)
3280 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3281 // Other flags: -wall -v0 -x
3282 int Buffer::runChktex()
3284 if (!users->text) return 0;
3286 ProhibitInput(users);
3288 // get LaTeX-Filename
3289 string const name = getLatexName();
3290 string path = OnlyPath(filename);
3292 string const org_path = path;
3293 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3297 Path p(path); // path to LaTeX file
3298 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3300 // Remove all error insets
3301 bool const removedErrorInsets = users->removeAutoInsets();
3303 // Generate the LaTeX file if neccessary
3304 makeLaTeXFile(name, org_path, false);
3307 Chktex chktex(lyxrc.chktex_command, name, filepath);
3308 int res = chktex.run(terr); // run chktex
3311 WriteAlert(_("chktex did not work!"),
3312 _("Could not run with file:"), name);
3313 } else if (res > 0) {
3314 // Insert all errors as errors boxes
3315 users->insertErrors(terr);
3318 // if we removed error insets before we ran chktex or if we inserted
3319 // error insets after we ran chktex, this must be run:
3320 if (removedErrorInsets || res){
3323 //users->updateScrollbar();
3331 void Buffer::validate(LaTeXFeatures & features) const
3333 LyXParagraph * par = paragraph;
3334 LyXTextClass const & tclass =
3335 textclasslist.TextClass(params.textclass);
3337 // AMS Style is at document level
3339 features.amsstyle = (params.use_amsmath ||
3340 tclass.provides(LyXTextClass::amsmath));
3343 // We don't use "lyxerr.debug" because of speed. (Asger)
3344 if (lyxerr.debugging(Debug::LATEX))
3345 lyxerr << "Paragraph: " << par << endl;
3347 // Now just follow the list of paragraphs and run
3348 // validate on each of them.
3349 par->validate(features);
3351 // and then the next paragraph
3355 // the bullet shapes are buffer level not paragraph level
3356 // so they are tested here
3357 for (int i = 0; i < 4; ++i) {
3358 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3359 int const font = params.user_defined_bullets[i].getFont();
3361 int const c = params
3362 .user_defined_bullets[i]
3369 features.latexsym = true;
3371 } else if (font == 1) {
3372 features.amssymb = true;
3373 } else if ((font >= 2 && font <= 5)) {
3374 features.pifont = true;
3379 if (lyxerr.debugging(Debug::LATEX)) {
3380 features.showStruct();
3385 void Buffer::setPaperStuff()
3387 params.papersize = BufferParams::PAPER_DEFAULT;
3388 char const c1 = params.paperpackage;
3389 if (c1 == BufferParams::PACKAGE_NONE) {
3390 char const c2 = params.papersize2;
3391 if (c2 == BufferParams::VM_PAPER_USLETTER)
3392 params.papersize = BufferParams::PAPER_USLETTER;
3393 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3394 params.papersize = BufferParams::PAPER_LEGALPAPER;
3395 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3396 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3397 else if (c2 == BufferParams::VM_PAPER_A3)
3398 params.papersize = BufferParams::PAPER_A3PAPER;
3399 else if (c2 == BufferParams::VM_PAPER_A4)
3400 params.papersize = BufferParams::PAPER_A4PAPER;
3401 else if (c2 == BufferParams::VM_PAPER_A5)
3402 params.papersize = BufferParams::PAPER_A5PAPER;
3403 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3404 (c2 == BufferParams::VM_PAPER_B5))
3405 params.papersize = BufferParams::PAPER_B5PAPER;
3406 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3407 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3408 params.papersize = BufferParams::PAPER_A4PAPER;
3412 // This function should be in Buffer because it's a buffer's property (ale)
3413 string const Buffer::getIncludeonlyList(char delim)
3416 for (inset_iterator it = inset_iterator_begin();
3417 it != inset_iterator_end(); ++it) {
3418 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3419 InsetInclude * insetinc =
3420 static_cast<InsetInclude *>(*it);
3421 if (insetinc->isInclude()
3422 && insetinc->isNoLoad()) {
3425 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3429 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3434 vector<string> const Buffer::getLabelList()
3436 /// if this is a child document and the parent is already loaded
3437 /// Use the parent's list instead [ale990407]
3438 if (!params.parentname.empty()
3439 && bufferlist.exists(params.parentname)) {
3440 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3442 return tmp->getLabelList();
3445 vector<string> label_list;
3446 for (inset_iterator it = inset_iterator_begin();
3447 it != inset_iterator_end(); ++it) {
3448 vector<string> const l = (*it)->getLabelList();
3449 label_list.insert(label_list.end(), l.begin(), l.end());
3455 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3457 vector<vector<TocItem> > l(4);
3458 LyXParagraph * par = paragraph;
3461 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3462 if (textclasslist.Style(params.textclass,
3463 par->GetLayout()).labeltype
3464 == LABEL_SENSITIVE) {
3468 tmp.str = par->String(this, false);
3469 switch (par->footnotekind) {
3470 case LyXParagraph::FIG:
3471 case LyXParagraph::WIDE_FIG:
3472 l[TOC_LOF].push_back(tmp);
3474 case LyXParagraph::TAB:
3475 case LyXParagraph::WIDE_TAB:
3476 l[TOC_LOT].push_back(tmp);
3478 case LyXParagraph::ALGORITHM:
3479 l[TOC_LOA].push_back(tmp);
3481 case LyXParagraph::FOOTNOTE:
3482 case LyXParagraph::MARGIN:
3486 } else if (!par->IsDummy()) {
3488 char const labeltype =
3489 textclasslist.Style(params.textclass,
3490 par->GetLayout()).labeltype;
3492 if (labeltype >= LABEL_COUNTER_CHAPTER
3493 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3494 // insert this into the table of contents
3499 textclasslist.TextClass(params.textclass).maxcounter());
3500 tmp.str = par->String(this, true);
3501 l[TOC_TOC].push_back(tmp);
3512 // This is also a buffer property (ale)
3513 vector<pair<string,string> > const Buffer::getBibkeyList()
3515 /// if this is a child document and the parent is already loaded
3516 /// Use the parent's list instead [ale990412]
3517 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3518 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3520 return tmp->getBibkeyList();
3523 vector<pair<string, string> > keys;
3524 LyXParagraph * par = paragraph;
3527 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3528 par->String(this, false)));
3532 // Might be either using bibtex or a child has bibliography
3534 for (inset_iterator it = inset_iterator_begin();
3535 it != inset_iterator_end(); ++it) {
3536 // Search for Bibtex or Include inset
3537 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3538 vector<pair<string,string> > tmp =
3539 static_cast<InsetBibtex*>(*it)->getKeys();
3540 keys.insert(keys.end(), tmp.begin(), tmp.end());
3541 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3542 vector<pair<string,string> > const tmp =
3543 static_cast<InsetInclude*>(*it)->getKeys();
3544 keys.insert(keys.end(), tmp.begin(), tmp.end());
3553 bool Buffer::isDepClean(string const & name) const
3555 DEPCLEAN * item = dep_clean;
3556 while (item && item->master != name)
3558 if (!item) return true;
3563 void Buffer::markDepClean(string const & name)
3566 dep_clean = new DEPCLEAN;
3567 dep_clean->clean = true;
3568 dep_clean->master = name;
3569 dep_clean->next = 0;
3571 DEPCLEAN * item = dep_clean;
3572 while (item && item->master != name)
3577 item = new DEPCLEAN;
3579 item->master = name;
3586 bool Buffer::Dispatch(string const & command)
3588 // Split command string into command and argument
3590 string line = frontStrip(command);
3591 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3593 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3597 bool Buffer::Dispatch(int action, string const & argument)
3599 bool dispatched = true;
3602 Exporter::Export(this, argument, false);
3612 void Buffer::resize()
3614 /// resize the BufferViews!
3620 void Buffer::resizeInsets(BufferView * bv)
3622 /// then remove all LyXText in text-insets
3623 LyXParagraph * par = paragraph;
3624 for(; par; par = par->next) {
3625 par->resizeInsetsLyXText(bv);
3629 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3632 LyXParagraph * par = paragraph;
3634 par->ChangeLanguage(params, from, to);
3640 bool Buffer::isMultiLingual()
3642 LyXParagraph * par = paragraph;
3644 if (par->isMultiLingual(params))
3652 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3653 LyXParagraph::size_type pos)
3656 it = par->InsetIterator(pos);
3657 if (it == par->inset_iterator_end()) {
3664 void Buffer::inset_iterator::SetParagraph()
3667 it = par->inset_iterator_begin();
3668 if (it != par->inset_iterator_end())
3673 // We maintain an invariant that whenever par = 0 then it = 0