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>
28 #pragma implementation "buffer.h"
32 #include "bufferlist.h"
34 #include "lyx_gui_misc.h"
35 #include "LyXAction.h"
38 #include "tex-strings.h"
40 #include "bufferview_funcs.h"
41 #include "minibuffer.h"
44 #include "mathed/formulamacro.h"
45 #include "insets/lyxinset.h"
46 #include "insets/inseterror.h"
47 #include "insets/insetlabel.h"
48 #include "insets/insetref.h"
49 #include "insets/inseturl.h"
50 #include "insets/insetinfo.h"
51 #include "insets/insetquotes.h"
52 #include "insets/insetlatexaccent.h"
53 #include "insets/insetbib.h"
54 #include "insets/insetcite.h"
55 #include "insets/insetexternal.h"
56 #include "insets/insetindex.h"
57 #include "insets/insetinclude.h"
58 #include "insets/insettoc.h"
59 #include "insets/insetlof.h"
60 #include "insets/insetlot.h"
61 #include "insets/insetloa.h"
62 #include "insets/insetparent.h"
63 #include "insets/insetspecialchar.h"
64 #include "insets/figinset.h"
65 #include "insets/insettext.h"
66 #include "insets/insetert.h"
67 #include "insets/insetgraphics.h"
68 #include "insets/insetfoot.h"
69 #include "insets/insetmarginal.h"
70 #include "insets/insetminipage.h"
71 #include "insets/insetfloat.h"
72 #include "insets/insetlist.h"
73 #include "insets/insettabular.h"
74 #include "insets/insettheorem.h"
75 #include "support/filetools.h"
76 #include "support/path.h"
82 #include "LaTeXFeatures.h"
83 #include "support/syscall.h"
84 #include "support/lyxlib.h"
85 #include "support/FileInfo.h"
89 #include "lyx_gui_misc.h" // WarnReadonly()
90 #include "frontends/Dialogs.h"
103 // all these externs should eventually be removed.
104 extern BufferList bufferlist;
106 extern void MenuExport(Buffer *, string const &);
107 extern LyXAction lyxaction;
110 static const float LYX_FORMAT = 2.16;
112 extern int tex_code_break_column;
115 Buffer::Buffer(string const & file, bool ronly)
117 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
119 filepath = OnlyPath(file);
127 if (read_only || (lyxrc.use_tempdir)) {
128 tmppath = CreateBufferTmpDir();
129 } else tmppath.erase();
135 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
136 // here the buffer should take care that it is
137 // saved properly, before it goes into the void.
139 // make sure that views using this buffer
144 if (!tmppath.empty()) {
145 DestroyBufferTmpDir(tmppath);
148 LyXParagraph * par = paragraph;
149 LyXParagraph * tmppar;
159 string Buffer::getLatexName(bool no_path) const
162 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
165 return ChangeExtension(MakeLatexName(filename),
170 void Buffer::setReadonly(bool flag)
172 if (read_only != flag) {
175 users->owner()->getDialogs()->updateBufferDependent();
178 WarnReadonly(filename);
183 bool Buffer::saveParamsAsDefaults()
185 string fname = AddName(AddPath(user_lyxdir, "templates/"),
187 Buffer defaults = Buffer(fname);
189 // Use the current buffer's parameters as default
190 defaults.params = params;
192 // add an empty paragraph. Is this enough?
193 defaults.paragraph = new LyXParagraph;
195 return defaults.writeFile(defaults.filename, false);
199 /// Update window titles of all users
200 // Should work on a list
201 void Buffer::updateTitles() const
203 if (users) users->owner()->updateWindowTitle();
207 /// Reset autosave timer of all users
208 // Should work on a list
209 void Buffer::resetAutosaveTimers() const
211 if (users) users->owner()->resetAutosaveTimer();
215 void Buffer::fileName(string const & newfile)
217 filename = MakeAbsPath(newfile);
218 filepath = OnlyPath(filename);
219 setReadonly(IsFileWriteable(filename) == 0);
224 // candidate for move to BufferView
225 // (at least some parts in the beginning of the func)
228 // changed to be public and have one parameter
229 // if par = 0 normal behavior
230 // else insert behavior
231 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
232 #define USE_PARSE_FUNCTION 1
233 //#define USE_TABULAR_INSETS 1
234 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
238 char depth = 0; // signed or unsigned?
239 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
240 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
241 bool the_end_read = false;
243 LyXParagraph * return_par = 0;
244 LyXFont font(LyXFont::ALL_INHERIT, params.language_info);
245 if (format < 2.16 && params.language == "hebrew")
246 font.setLanguage(default_language);
248 // If we are inserting, we cheat and get a token in advance
249 bool has_token = false;
253 par = new LyXParagraph;
255 users->text->BreakParagraph(users);
256 return_par = users->text->FirstParagraph();
259 // We don't want to adopt the parameters from the
260 // document we insert, so we skip until the text begins:
263 pretoken = lex.GetString();
264 if (pretoken == "\\layout") {
276 pretoken = lex.GetString();
279 // Profiling show this should give a lot: (Asger)
280 string const token = pretoken;
284 the_end_read = parseSingleLyXformat2Token(lex, par, return_par,
293 paragraph = return_par;
300 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
301 LyXParagraph *& return_par,
302 string const & token, int & pos,
303 char & depth, LyXFont & font,
304 LyXParagraph::footnote_flag & footnoteflag,
305 LyXParagraph::footnote_kind & footnotekind)
307 bool the_end_read = false;
309 if (token[0] != '\\') {
310 for (string::const_iterator cit = token.begin();
311 cit != token.end(); ++cit) {
312 par->InsertChar(pos, (*cit), font);
315 } else if (token == "\\i") {
316 Inset * inset = new InsetLatexAccent;
317 inset->Read(this, lex);
318 par->InsertInset(pos, inset, font);
320 } else if (token == "\\layout") {
325 par = new LyXParagraph(par);
329 string layoutname = lex.GetString();
330 pair<bool, LyXTextClass::LayoutList::size_type> pp
331 = textclasslist.NumberOfLayout(params.textclass,
334 par->layout = pp.second;
335 } else { // layout not found
336 // use default layout "Standard" (0)
339 // Test whether the layout is obsolete.
340 LyXLayout const & layout =
341 textclasslist.Style(params.textclass,
343 if (!layout.obsoleted_by().empty())
345 textclasslist.NumberOfLayout(params.textclass,
346 layout.obsoleted_by()).second;
347 par->footnoteflag = footnoteflag;
348 par->footnotekind = footnotekind;
350 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
351 if (format < 2.16 && params.language == "hebrew")
352 font.setLanguage(default_language);
354 } else if (token == "\\end_float") {
359 par = new LyXParagraph(par);
361 footnotekind = LyXParagraph::FOOTNOTE;
362 footnoteflag = LyXParagraph::NO_FOOTNOTE;
365 par->layout = LYX_DUMMY_LAYOUT;
366 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
367 if (format < 2.16 && params.language == "hebrew")
368 font.setLanguage(default_language);
369 } else if (token == "\\begin_float") {
370 int tmpret = lex.FindToken(string_footnotekinds);
371 if (tmpret == -1) ++tmpret;
372 if (tmpret != LYX_LAYOUT_DEFAULT)
373 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
374 if (footnotekind == LyXParagraph::FOOTNOTE
375 || footnotekind == LyXParagraph::MARGIN)
376 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
378 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
380 } else if (token == "\\begin_float") {
381 // This is the compability reader, unfinished but tested.
384 string tmptok = lex.GetString();
385 //lyxerr << "old float: " << tmptok << endl;
389 if (tmptok == "footnote") {
390 inset = new InsetFoot;
391 } else if (tmptok == "margin") {
392 inset = new InsetMarginal;
393 } else if (tmptok == "fig") {
394 //inset = new InsetFigure;
395 } else if (tmptok == "tab") {
396 //inset = new InsetTable;
397 } else if (tmptok == "alg") {
398 //inset = new InsetAlgorithm;
399 } else if (tmptok == "wide-fig") {
400 //inset = new InsetFigure(true);
401 } else if (tmptok == "wide-tab") {
402 //inset = new InsetTable(true);
405 if (!inset) return false; // no end read yet
407 string old_float = "\ncollapsed true\n";
408 old_float += lex.getLongString("\\end_float");
409 old_float += "\n\\end_inset\n";
410 lyxerr << "float body: " << old_float << endl;
412 istrstream istr(old_float.c_str());
414 nylex.setStream(istr);
416 inset->Read(this, nylex);
417 par->InsertInset(pos, inset, font);
420 } else if (token == "\\begin_deeper") {
422 } else if (token == "\\end_deeper") {
424 lex.printError("\\end_deeper: "
425 "depth is already null");
429 } else if (token == "\\begin_preamble") {
430 params.readPreamble(lex);
431 } else if (token == "\\textclass") {
433 pair<bool, LyXTextClassList::size_type> pp =
434 textclasslist.NumberOfClass(lex.GetString());
436 params.textclass = pp.second;
438 lex.printError("Unknown textclass `$$Token'");
439 params.textclass = 0;
441 if (!textclasslist.Load(params.textclass)) {
442 // if the textclass wasn't loaded properly
443 // we need to either substitute another
444 // or stop loading the file.
445 // I can substitute but I don't see how I can
446 // stop loading... ideas?? ARRae980418
447 WriteAlert(_("Textclass Loading Error!"),
448 string(_("Can't load textclass ")) +
449 textclasslist.NameOfClass(params.textclass),
450 _("-- substituting default"));
451 params.textclass = 0;
453 } else if (token == "\\options") {
455 params.options = lex.GetString();
456 } else if (token == "\\language") {
457 params.readLanguage(lex);
458 } else if (token == "\\fontencoding") {
460 } else if (token == "\\inputencoding") {
462 params.inputenc = lex.GetString();
463 } else if (token == "\\graphics") {
464 params.readGraphicsDriver(lex);
465 } else if (token == "\\fontscheme") {
467 params.fonts = lex.GetString();
468 } else if (token == "\\noindent") {
469 par->noindent = true;
470 } else if (token == "\\fill_top") {
471 par->added_space_top = VSpace(VSpace::VFILL);
472 } else if (token == "\\fill_bottom") {
473 par->added_space_bottom = VSpace(VSpace::VFILL);
474 } else if (token == "\\line_top") {
475 par->line_top = true;
476 } else if (token == "\\line_bottom") {
477 par->line_bottom = true;
478 } else if (token == "\\pagebreak_top") {
479 par->pagebreak_top = true;
480 } else if (token == "\\pagebreak_bottom") {
481 par->pagebreak_bottom = true;
482 } else if (token == "\\start_of_appendix") {
483 par->start_of_appendix = true;
484 } else if (token == "\\paragraph_separation") {
485 int tmpret = lex.FindToken(string_paragraph_separation);
486 if (tmpret == -1) ++tmpret;
487 if (tmpret != LYX_LAYOUT_DEFAULT)
488 params.paragraph_separation =
489 static_cast<BufferParams::PARSEP>(tmpret);
490 } else if (token == "\\defskip") {
492 params.defskip = VSpace(lex.GetString());
493 } else if (token == "\\epsfig") { // obsolete
494 // Indeed it is obsolete, but we HAVE to be backwards
495 // compatible until 0.14, because otherwise all figures
496 // in existing documents are irretrivably lost. (Asger)
497 params.readGraphicsDriver(lex);
498 } else if (token == "\\quotes_language") {
499 int tmpret = lex.FindToken(string_quotes_language);
500 if (tmpret == -1) ++tmpret;
501 if (tmpret != LYX_LAYOUT_DEFAULT) {
502 InsetQuotes::quote_language tmpl =
503 InsetQuotes::EnglishQ;
506 tmpl = InsetQuotes::EnglishQ;
509 tmpl = InsetQuotes::SwedishQ;
512 tmpl = InsetQuotes::GermanQ;
515 tmpl = InsetQuotes::PolishQ;
518 tmpl = InsetQuotes::FrenchQ;
521 tmpl = InsetQuotes::DanishQ;
524 params.quotes_language = tmpl;
526 } else if (token == "\\quotes_times") {
528 switch(lex.GetInteger()) {
530 params.quotes_times = InsetQuotes::SingleQ;
533 params.quotes_times = InsetQuotes::DoubleQ;
536 } else if (token == "\\papersize") {
537 int tmpret = lex.FindToken(string_papersize);
541 params.papersize2 = tmpret;
542 } else if (token == "\\paperpackage") {
543 int tmpret = lex.FindToken(string_paperpackages);
546 params.paperpackage = BufferParams::PACKAGE_NONE;
548 params.paperpackage = tmpret;
549 } else if (token == "\\use_geometry") {
551 params.use_geometry = lex.GetInteger();
552 } else if (token == "\\use_amsmath") {
554 params.use_amsmath = lex.GetInteger();
555 } else if (token == "\\paperorientation") {
556 int tmpret = lex.FindToken(string_orientation);
557 if (tmpret == -1) ++tmpret;
558 if (tmpret != LYX_LAYOUT_DEFAULT)
559 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
560 } else if (token == "\\paperwidth") {
562 params.paperwidth = lex.GetString();
563 } else if (token == "\\paperheight") {
565 params.paperheight = lex.GetString();
566 } else if (token == "\\leftmargin") {
568 params.leftmargin = lex.GetString();
569 } else if (token == "\\topmargin") {
571 params.topmargin = lex.GetString();
572 } else if (token == "\\rightmargin") {
574 params.rightmargin = lex.GetString();
575 } else if (token == "\\bottommargin") {
577 params.bottommargin = lex.GetString();
578 } else if (token == "\\headheight") {
580 params.headheight = lex.GetString();
581 } else if (token == "\\headsep") {
583 params.headsep = lex.GetString();
584 } else if (token == "\\footskip") {
586 params.footskip = lex.GetString();
587 } else if (token == "\\paperfontsize") {
589 params.fontsize = strip(lex.GetString());
590 } else if (token == "\\papercolumns") {
592 params.columns = lex.GetInteger();
593 } else if (token == "\\papersides") {
595 switch(lex.GetInteger()) {
597 case 1: params.sides = LyXTextClass::OneSide; break;
598 case 2: params.sides = LyXTextClass::TwoSides; break;
600 } else if (token == "\\paperpagestyle") {
602 params.pagestyle = strip(lex.GetString());
603 } else if (token == "\\bullet") {
605 int index = lex.GetInteger();
607 int temp_int = lex.GetInteger();
608 params.user_defined_bullets[index].setFont(temp_int);
609 params.temp_bullets[index].setFont(temp_int);
611 temp_int = lex.GetInteger();
612 params.user_defined_bullets[index].setCharacter(temp_int);
613 params.temp_bullets[index].setCharacter(temp_int);
615 temp_int = lex.GetInteger();
616 params.user_defined_bullets[index].setSize(temp_int);
617 params.temp_bullets[index].setSize(temp_int);
619 string temp_str = lex.GetString();
620 if (temp_str != "\\end_bullet") {
621 // this element isn't really necessary for
622 // parsing but is easier for humans
623 // to understand bullets. Put it back and
624 // set a debug message?
625 lex.printError("\\end_bullet expected, got" + temp_str);
626 //how can I put it back?
628 } else if (token == "\\bulletLaTeX") {
630 int index = lex.GetInteger();
632 string temp_str = lex.GetString(), sum_str;
633 while (temp_str != "\\end_bullet") {
634 // this loop structure is needed when user
635 // enters an empty string since the first
636 // thing returned will be the \\end_bullet
638 // if the LaTeX entry has spaces. Each element
639 // therefore needs to be read in turn
642 temp_str = lex.GetString();
644 params.user_defined_bullets[index].setText(sum_str);
645 params.temp_bullets[index].setText(sum_str);
646 } else if (token == "\\secnumdepth") {
648 params.secnumdepth = lex.GetInteger();
649 } else if (token == "\\tocdepth") {
651 params.tocdepth = lex.GetInteger();
652 } else if (token == "\\spacing") {
654 string tmp = strip(lex.GetString());
655 Spacing::Space tmp_space = Spacing::Default;
657 if (tmp == "single") {
658 tmp_space = Spacing::Single;
659 } else if (tmp == "onehalf") {
660 tmp_space = Spacing::Onehalf;
661 } else if (tmp == "double") {
662 tmp_space = Spacing::Double;
663 } else if (tmp == "other") {
665 tmp_space = Spacing::Other;
666 tmp_val = lex.GetFloat();
668 lex.printError("Unknown spacing token: '$$Token'");
670 // Small hack so that files written with klyx will be
673 par->spacing.set(tmp_space, tmp_val);
675 params.spacing.set(tmp_space, tmp_val);
677 } else if (token == "\\paragraph_spacing") {
679 string tmp = strip(lex.GetString());
680 if (tmp == "single") {
681 par->spacing.set(Spacing::Single);
682 } else if (tmp == "onehalf") {
683 par->spacing.set(Spacing::Onehalf);
684 } else if (tmp == "double") {
685 par->spacing.set(Spacing::Double);
686 } else if (tmp == "other") {
688 par->spacing.set(Spacing::Other,
691 lex.printError("Unknown spacing token: '$$Token'");
693 } else if (token == "\\float_placement") {
695 params.float_placement = lex.GetString();
696 } else if (token == "\\family") {
698 font.setLyXFamily(lex.GetString());
699 } else if (token == "\\series") {
701 font.setLyXSeries(lex.GetString());
702 } else if (token == "\\shape") {
704 font.setLyXShape(lex.GetString());
705 } else if (token == "\\size") {
707 font.setLyXSize(lex.GetString());
708 } else if (token == "\\latex") {
710 string tok = lex.GetString();
711 // This is dirty, but gone with LyX3. (Asger)
712 if (tok == "no_latex")
713 font.setLatex(LyXFont::OFF);
714 else if (tok == "latex")
715 font.setLatex(LyXFont::ON);
716 else if (tok == "default")
717 font.setLatex(LyXFont::INHERIT);
719 lex.printError("Unknown LaTeX font flag "
721 } else if (token == "\\lang") {
723 string tok = lex.GetString();
724 Languages::iterator lit = languages.find(tok);
725 if (lit != languages.end()) {
726 font.setLanguage(&(*lit).second);
728 font.setLanguage(params.language_info);
729 lex.printError("Unknown language `$$Token'");
731 } else if (token == "\\emph") {
733 font.setEmph(font.setLyXMisc(lex.GetString()));
734 } else if (token == "\\bar") {
736 string tok = lex.GetString();
737 // This is dirty, but gone with LyX3. (Asger)
739 font.setUnderbar(LyXFont::ON);
740 else if (tok == "no")
741 font.setUnderbar(LyXFont::OFF);
742 else if (tok == "default")
743 font.setUnderbar(LyXFont::INHERIT);
745 lex.printError("Unknown bar font flag "
747 } else if (token == "\\noun") {
749 font.setNoun(font.setLyXMisc(lex.GetString()));
750 } else if (token == "\\color") {
752 font.setLyXColor(lex.GetString());
753 } else if (token == "\\align") {
754 int tmpret = lex.FindToken(string_align);
755 if (tmpret == -1) ++tmpret;
756 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
758 for (; tmpret > 0; --tmpret)
759 tmpret2 = tmpret2 * 2;
760 par->align = LyXAlignment(tmpret2);
762 } else if (token == "\\added_space_top") {
764 par->added_space_top = VSpace(lex.GetString());
765 } else if (token == "\\added_space_bottom") {
767 par->added_space_bottom = VSpace(lex.GetString());
768 } else if (token == "\\pextra_type") {
770 par->pextra_type = lex.GetInteger();
771 } else if (token == "\\pextra_width") {
773 par->pextra_width = lex.GetString();
774 } else if (token == "\\pextra_widthp") {
776 par->pextra_widthp = lex.GetString();
777 } else if (token == "\\pextra_alignment") {
779 par->pextra_alignment = lex.GetInteger();
780 } else if (token == "\\pextra_hfill") {
782 par->pextra_hfill = lex.GetInteger();
783 } else if (token == "\\pextra_start_minipage") {
785 par->pextra_start_minipage = lex.GetInteger();
786 } else if (token == "\\labelwidthstring") {
788 par->labelwidthstring = lex.GetString();
789 // do not delete this token, it is still needed!
790 } else if (token == "\\end_inset") {
791 // Simply ignore this. The insets do not have
793 // But insets should read it, it is a part of
794 // the inset isn't it? Lgb.
795 } else if (token == "\\begin_inset") {
796 // Should be moved out into its own function/method. (Lgb)
798 string tmptok = lex.GetString();
799 // test the different insets
800 if (tmptok == "Quotes") {
801 Inset * inset = new InsetQuotes;
802 inset->Read(this, lex);
803 par->InsertInset(pos, inset, font);
805 } else if (tmptok == "External") {
806 Inset * inset = new InsetExternal;
807 inset->Read(this, lex);
808 par->InsertInset(pos, inset, font);
810 } else if (tmptok == "FormulaMacro") {
811 Inset * inset = new InsetFormulaMacro;
812 inset->Read(this, lex);
813 par->InsertInset(pos, inset, font);
815 } else if (tmptok == "Formula") {
816 Inset * inset = new InsetFormula;
817 inset->Read(this, lex);
818 par->InsertInset(pos, inset, font);
820 } else if (tmptok == "Figure") {
821 Inset * inset = new InsetFig(100, 100, this);
822 inset->Read(this, lex);
823 par->InsertInset(pos, inset, font);
825 } else if (tmptok == "Info") {
826 Inset * inset = new InsetInfo;
827 inset->Read(this, lex);
828 par->InsertInset(pos, inset, font);
830 } else if (tmptok == "Include") {
831 Inset * inset = new InsetInclude(string(), this);
832 inset->Read(this, lex);
833 par->InsertInset(pos, inset, font);
835 } else if (tmptok == "ERT") {
836 Inset * inset = new InsetERT;
837 inset->Read(this, lex);
838 par->InsertInset(pos, inset, font);
840 } else if (tmptok == "Tabular") {
841 Inset * inset = new InsetTabular(this);
842 inset->Read(this, lex);
843 par->InsertInset(pos, inset, font);
845 } else if (tmptok == "Text") {
846 Inset * inset = new InsetText;
847 inset->Read(this, lex);
848 par->InsertInset(pos, inset, font);
850 } else if (tmptok == "Foot") {
851 Inset * inset = new InsetFoot;
852 inset->Read(this, lex);
853 par->InsertInset(pos, inset, font);
855 } else if (tmptok == "Marginal") {
856 Inset * inset = new InsetMarginal;
857 inset->Read(this, lex);
858 par->InsertInset(pos, inset, font);
860 } else if (tmptok == "Minipage") {
861 Inset * inset = new InsetMinipage;
862 inset->Read(this, lex);
863 par->InsertInset(pos, inset, font);
865 } else if (tmptok == "Float") {
866 Inset * inset = new InsetFloat;
867 inset->Read(this, lex);
868 par->InsertInset(pos, inset, font);
870 } else if (tmptok == "List") {
871 Inset * inset = new InsetList;
872 inset->Read(this, lex);
873 par->InsertInset(pos, inset, font);
875 } else if (tmptok == "Theorem") {
876 Inset * inset = new InsetList;
877 inset->Read(this, lex);
878 par->InsertInset(pos, inset, font);
880 } else if (tmptok == "GRAPHICS") {
881 Inset * inset = new InsetGraphics;
882 //inset->Read(this, lex);
883 par->InsertInset(pos, inset, font);
884 } else if (tmptok == "LatexCommand") {
886 inscmd.Read(this, lex);
888 if (inscmd.getCmdName() == "cite") {
889 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
890 } else if (inscmd.getCmdName() == "bibitem") {
891 lex.printError("Wrong place for bibitem");
892 inset = inscmd.Clone();
893 } else if (inscmd.getCmdName() == "BibTeX") {
894 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
895 } else if (inscmd.getCmdName() == "index") {
896 inset = new InsetIndex(inscmd.getContents());
897 } else if (inscmd.getCmdName() == "include") {
898 inset = new InsetInclude(inscmd.getContents(), this);
899 } else if (inscmd.getCmdName() == "label") {
900 inset = new InsetLabel(inscmd.getCommand());
901 } else if (inscmd.getCmdName() == "url"
902 || inscmd.getCmdName() == "htmlurl") {
903 inset = new InsetUrl(inscmd.getCommand());
904 } else if (inscmd.getCmdName() == "ref"
905 || inscmd.getCmdName() == "pageref"
906 || inscmd.getCmdName() == "vref"
907 || inscmd.getCmdName() == "vpageref"
908 || inscmd.getCmdName() == "prettyref") {
909 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
910 inset = new InsetRef(inscmd, this);
912 } else if (inscmd.getCmdName() == "tableofcontents") {
913 inset = new InsetTOC(this);
914 } else if (inscmd.getCmdName() == "listoffigures") {
915 inset = new InsetLOF(this);
916 } else if (inscmd.getCmdName() == "listofalgorithms") {
917 inset = new InsetLOA(this);
918 } else if (inscmd.getCmdName() == "listoftables") {
919 inset = new InsetLOT(this);
920 } else if (inscmd.getCmdName() == "printindex") {
921 inset = new InsetPrintIndex(this);
922 } else if (inscmd.getCmdName() == "lyxparent") {
923 inset = new InsetParent(inscmd.getContents(), this);
927 par->InsertInset(pos, inset, font);
931 } else if (token == "\\SpecialChar") {
932 LyXLayout const & layout =
933 textclasslist.Style(params.textclass,
936 // Insets don't make sense in a free-spacing context! ---Kayvan
937 if (layout.free_spacing) {
941 next_token = lex.GetString();
942 if (next_token == "\\-") {
943 par->InsertChar(pos, '-', font);
944 } else if (next_token == "\\protected_separator"
945 || next_token == "~") {
946 par->InsertChar(pos, ' ', font);
948 lex.printError("Token `$$Token' "
950 "paragraph layout!");
955 Inset * inset = new InsetSpecialChar;
956 inset->Read(this, lex);
957 par->InsertInset(pos, inset, font);
960 } else if (token == "\\newline") {
961 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
963 } else if (token == "\\LyXTable") {
964 #ifdef USE_TABULAR_INSETS
965 Inset * inset = new InsetTabular(this);
966 inset->Read(this, lex);
967 par->InsertInset(pos, inset, font);
970 par->table = new LyXTable(lex);
972 } else if (token == "\\hfill") {
973 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
975 } else if (token == "\\protected_separator") { // obsolete
976 // This is a backward compability thingie. (Lgb)
977 // Remove it later some time...introduced with fileformat
979 LyXLayout const & layout =
980 textclasslist.Style(params.textclass,
983 if (layout.free_spacing) {
984 par->InsertChar(pos, ' ', font);
986 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
987 par->InsertInset(pos, inset, font);
990 } else if (token == "\\bibitem") { // ale970302
992 par->bibkey = new InsetBibKey;
993 par->bibkey->Read(this, lex);
994 }else if (token == "\\backslash") {
995 par->InsertChar(pos, '\\', font);
997 }else if (token == "\\the_end") {
1000 // This should be insurance for the future: (Asger)
1001 lex.printError("Unknown token `$$Token'. "
1002 "Inserting as text.");
1003 for(string::const_iterator cit = token.begin();
1004 cit != token.end(); ++cit) {
1005 par->InsertChar(pos, (*cit), font);
1009 return the_end_read;
1012 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1018 token = lex.GetString();
1019 if (token == "\\lyxformat") { // the first token _must_ be...
1021 format = lex.GetFloat();
1023 if (LYX_FORMAT - format > 0.05) {
1024 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1025 LYX_FORMAT, format);
1027 if (format - LYX_FORMAT > 0.05) {
1028 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1029 LYX_FORMAT, format);
1031 bool the_end = readLyXformat2(lex, par);
1032 // Formats >= 2.13 support "\the_end" marker
1039 WriteAlert(_("Warning!"),
1040 _("Reading of document is not complete"),
1041 _("Maybe the document is truncated"));
1042 // We simulate a safe reading anyways to allow
1043 // users to take the chance... (Asger)
1047 WriteAlert(_("ERROR!"),
1048 _("Old LyX file format found. "
1049 "Use LyX 0.10.x to read this!"));
1053 } else { // "\\lyxformat" not found
1054 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1057 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1063 // Should probably be moved to somewhere else: BufferView? LyXView?
1064 bool Buffer::save() const
1066 // We don't need autosaves in the immediate future. (Asger)
1067 resetAutosaveTimers();
1071 if (lyxrc.make_backup) {
1072 s = fileName() + '~';
1073 if (!lyxrc.backupdir_path.empty())
1074 s = AddName(lyxrc.backupdir_path,
1075 subst(CleanupPath(s),'/','!'));
1077 // Rename is the wrong way of making a backup,
1078 // this is the correct way.
1079 /* truss cp fil fil2:
1080 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1081 stat("LyXVC.lyx", 0xEFFFF688) = 0
1082 open("LyXVC.lyx", O_RDONLY) = 3
1083 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1084 fstat(4, 0xEFFFF508) = 0
1085 fstat(3, 0xEFFFF508) = 0
1086 read(3, " # T h i s f i l e w".., 8192) = 5579
1087 write(4, " # T h i s f i l e w".., 5579) = 5579
1088 read(3, 0xEFFFD4A0, 8192) = 0
1091 chmod("LyXVC3.lyx", 0100644) = 0
1092 lseek(0, 0, SEEK_CUR) = 46440
1096 // Should proabaly have some more error checking here.
1097 // Should be cleaned up in 0.13, at least a bit.
1098 // Doing it this way, also makes the inodes stay the same.
1099 // This is still not a very good solution, in particular we
1100 // might loose the owner of the backup.
1101 FileInfo finfo(fileName());
1102 if (finfo.exist()) {
1103 mode_t fmode = finfo.getMode();
1104 struct utimbuf times = {
1105 finfo.getAccessTime(),
1106 finfo.getModificationTime() };
1108 ifstream ifs(fileName().c_str());
1109 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1114 ::chmod(s.c_str(), fmode);
1116 if (::utime(s.c_str(), ×)) {
1117 lyxerr << "utime error." << endl;
1120 lyxerr << "LyX was not able to make "
1121 "backupcopy. Beware." << endl;
1126 if (writeFile(fileName(), false)) {
1129 // now delete the autosavefile
1130 string a = OnlyPath(fileName());
1132 a += OnlyFilename(fileName());
1134 FileInfo fileinfo(a);
1135 if (fileinfo.exist()) {
1136 if (::remove(a.c_str()) != 0) {
1137 WriteFSAlert(_("Could not delete "
1138 "auto-save file!"), a);
1142 // Saving failed, so backup is not backup
1143 if (lyxrc.make_backup) {
1144 ::rename(s.c_str(), fileName().c_str());
1152 // Returns false if unsuccesful
1153 bool Buffer::writeFile(string const & fname, bool flag) const
1155 // if flag is false writeFile will not create any GUI
1156 // warnings, only cerr.
1157 // Needed for autosave in background or panic save (Matthias 120496)
1159 if (read_only && (fname == filename)) {
1160 // Here we should come with a question if we should
1161 // perform the write anyway.
1163 lyxerr << _("Error! Document is read-only: ")
1166 WriteAlert(_("Error! Document is read-only: "),
1171 FileInfo finfo(fname);
1172 if (finfo.exist() && !finfo.writable()) {
1173 // Here we should come with a question if we should
1174 // try to do the save anyway. (i.e. do a chmod first)
1176 lyxerr << _("Error! Cannot write file: ")
1179 WriteFSAlert(_("Error! Cannot write file: "),
1184 ofstream ofs(fname.c_str());
1187 lyxerr << _("Error! Cannot open file: ")
1190 WriteFSAlert(_("Error! Cannot open file: "),
1194 // The top of the file should not be written by params.
1196 // write out a comment in the top of the file
1197 ofs << '#' << LYX_DOCVERSION
1198 << " created this file. For more info see http://www.lyx.org/\n";
1199 ofs.setf(ios::showpoint|ios::fixed);
1201 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1203 // now write out the buffer paramters.
1204 params.writeFile(ofs);
1206 char footnoteflag = 0;
1209 // this will write out all the paragraphs
1210 // using recursive descent.
1211 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1213 // Write marker that shows file is complete
1214 ofs << "\n\\the_end" << endl;
1216 // how to check if close went ok?
1221 void Buffer::writeFileAscii(string const & fname, int linelen)
1223 LyXFont font1, font2;
1225 char c, footnoteflag = 0, depth = 0;
1227 LyXParagraph::size_type i;
1228 int j, h, ltype = 0, ltype_depth = 0,
1229 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1232 bool ref_printed = false;
1234 ofstream ofs(fname.c_str());
1236 WriteFSAlert(_("Error: Cannot write file:"), fname);
1240 string fname1 = TmpFileName();
1241 LyXParagraph * par = paragraph;
1245 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1247 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1249 /* begins a footnote environment ? */
1250 if (footnoteflag != par->footnoteflag) {
1251 footnoteflag = par->footnoteflag;
1253 j = strlen(string_footnotekinds[par->footnotekind])+4;
1254 if (currlinelen + j > linelen)
1257 << string_footnotekinds[par->footnotekind] << "] ";
1262 /* begins or ends a deeper area ?*/
1263 if (depth != par->depth) {
1264 if (par->depth > depth) {
1265 while (par->depth > depth) {
1270 while (par->depth < depth) {
1276 /* First write the layout */
1277 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1278 if (tmp == "Itemize") {
1280 ltype_depth = depth+1;
1281 } else if (tmp == "Enumerate") {
1283 ltype_depth = depth+1;
1284 } else if (strstr(tmp.c_str(), "ection")) {
1286 ltype_depth = depth+1;
1287 } else if (strstr(tmp.c_str(), "aragraph")) {
1289 ltype_depth = depth+1;
1290 } else if (tmp == "Description") {
1292 ltype_depth = depth+1;
1293 } else if (tmp == "Abstract") {
1296 } else if (tmp == "Bibliography") {
1304 /* maybe some vertical spaces */
1306 /* the labelwidthstring used in lists */
1310 /* some pagebreaks? */
1314 /* what about the alignment */
1316 /* dummy layout, that means a footnote ended */
1317 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1322 //LyXLayout const & layout =
1323 // textclasslist.Style(params.textclass,
1324 // par->GetLayout()); // unused
1325 //bool free_spc = layout.free_spacing; //unused
1328 /* It might be a table */
1332 cells = par->table->columns;
1333 clen = new int [cells];
1334 memset(clen, 0, sizeof(int) * cells);
1336 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1337 c = par->GetChar(i);
1338 if (c == LyXParagraph::META_INSET) {
1339 if ((inset = par->GetInset(i))) {
1341 std::ostringstream ost;
1342 inset->Ascii(this, ost);
1343 h += ost.str().length();
1346 inset->Ascii(this, ost);
1348 char * tmp = ost.str();
1354 } else if (c == LyXParagraph::META_NEWLINE) {
1358 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1366 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1368 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1369 if (!i && !footnoteflag && !noparbreak){
1371 for(j = 0; j < depth; ++j)
1373 currlinelen = depth * 2;
1375 case 0: /* Standard */
1376 case 4: /* (Sub)Paragraph */
1377 case 5: /* Description */
1379 case 6: /* Abstract */
1380 ofs << "Abstract\n\n";
1382 case 7: /* Bibliography */
1384 ofs << "References\n\n";
1389 ofs << par->labelstring << " ";
1392 if (ltype_depth > depth) {
1393 for(j = ltype_depth - 1; j > depth; --j)
1395 currlinelen += (ltype_depth-depth)*2;
1399 for(j = 0; j < cells; ++j) {
1401 for(h = 0; h < (clen[j] + 1);
1406 for(j = 0; j < depth; ++j)
1408 currlinelen = depth * 2;
1409 if (ltype_depth > depth) {
1410 for(j = ltype_depth;
1413 currlinelen += (ltype_depth-depth)*2;
1419 font2 = par->GetFontSettings(params, i);
1420 if (font1.latex() != font2.latex()) {
1421 if (font2.latex() == LyXFont::OFF)
1428 c = par->GetChar(i);
1432 case LyXParagraph::META_INSET:
1433 if ((inset = par->GetInset(i))) {
1435 inset->Ascii(this, ofs);
1436 currlinelen += (ofs.tellp() - fpos);
1437 actpos += (ofs.tellp() - fpos) - 1;
1440 case LyXParagraph::META_NEWLINE:
1443 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1444 for(j = actpos; j < clen[cell - 1]; ++j)
1447 for(j = 0; j < depth; ++j)
1449 currlinelen = depth*2;
1450 if (ltype_depth > depth) {
1451 for(j = ltype_depth; j > depth; --j)
1453 currlinelen += (ltype_depth-depth) * 2;
1455 for(j = 0; j < cells; ++j) {
1457 for(h = 0; h < (clen[j] + 1); ++h)
1461 for(j = 0; j < depth; ++j)
1463 currlinelen = depth * 2;
1464 if (ltype_depth > depth) {
1465 for(j = ltype_depth;
1468 currlinelen += (ltype_depth-depth)*2;
1474 j < clen[cell - 1]; ++j)
1480 currlinelen = actpos = 0;
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;
1497 case LyXParagraph::META_HFILL:
1504 if (currlinelen > linelen - 10
1505 && c == ' ' && i + 2 < par->size()) {
1507 for(j = 0; j < depth; ++j)
1509 currlinelen = depth * 2;
1510 if (ltype_depth > depth) {
1511 for(j = ltype_depth;
1514 currlinelen += (ltype_depth-depth)*2;
1516 } else if (c != '\0')
1519 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1526 for(j = actpos; j < clen[cell - 1]; ++j)
1529 for(j = 0; j < depth; ++j)
1531 currlinelen = depth * 2;
1532 if (ltype_depth > depth) {
1533 for(j = ltype_depth; j > depth; --j)
1535 currlinelen += (ltype_depth - depth) * 2;
1537 for(j = 0; j < cells; ++j) {
1539 for(h = 0; h < (clen[j] + 1); ++h)
1553 void Buffer::makeLaTeXFile(string const & fname,
1554 string const & original_path,
1555 bool nice, bool only_body)
1557 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1559 niceFile = nice; // this will be used by Insetincludes.
1561 tex_code_break_column = lyxrc.ascii_linelen;
1563 LyXTextClass const & tclass =
1564 textclasslist.TextClass(params.textclass);
1566 ofstream ofs(fname.c_str());
1568 WriteFSAlert(_("Error: Cannot open file: "), fname);
1572 // validate the buffer.
1573 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1574 LaTeXFeatures features(params, tclass.numLayouts());
1576 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1579 // The starting paragraph of the coming rows is the
1580 // first paragraph of the document. (Asger)
1581 texrow.start(paragraph, 0);
1583 if (!only_body && nice) {
1584 ofs << "%% " LYX_DOCVERSION " created this file. "
1585 "For more info, see http://www.lyx.org/.\n"
1586 "%% Do not edit unless you really know what "
1591 lyxerr.debug() << "lyx header finished" << endl;
1592 // There are a few differences between nice LaTeX and usual files:
1593 // usual is \batchmode and has a
1594 // special input@path to allow the including of figures
1595 // with either \input or \includegraphics (what figinsets do).
1596 // batchmode is not set if there is a tex_code_break_column.
1597 // In this case somebody is interested in the generated LaTeX,
1598 // so this is OK. input@path is set when the actual parameter
1599 // original_path is set. This is done for usual tex-file, but not
1600 // for nice-latex-file. (Matthias 250696)
1603 // code for usual, NOT nice-latex-file
1604 ofs << "\\batchmode\n"; // changed
1605 // from \nonstopmode
1608 if (!original_path.empty()) {
1609 ofs << "\\makeatletter\n"
1610 << "\\def\\input@path{{"
1611 << original_path << "/}}\n"
1612 << "\\makeatother\n";
1618 ofs << "\\documentclass";
1620 string options; // the document class options.
1622 if (tokenPos(tclass.opt_fontsize(),
1623 '|', params.fontsize) >= 0) {
1624 // only write if existing in list (and not default)
1625 options += params.fontsize;
1630 if (!params.use_geometry &&
1631 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1632 switch (params.papersize) {
1633 case BufferParams::PAPER_A4PAPER:
1634 options += "a4paper,";
1636 case BufferParams::PAPER_USLETTER:
1637 options += "letterpaper,";
1639 case BufferParams::PAPER_A5PAPER:
1640 options += "a5paper,";
1642 case BufferParams::PAPER_B5PAPER:
1643 options += "b5paper,";
1645 case BufferParams::PAPER_EXECUTIVEPAPER:
1646 options += "executivepaper,";
1648 case BufferParams::PAPER_LEGALPAPER:
1649 options += "legalpaper,";
1655 if (params.sides != tclass.sides()) {
1656 switch (params.sides) {
1657 case LyXTextClass::OneSide:
1658 options += "oneside,";
1660 case LyXTextClass::TwoSides:
1661 options += "twoside,";
1668 if (params.columns != tclass.columns()) {
1669 if (params.columns == 2)
1670 options += "twocolumn,";
1672 options += "onecolumn,";
1675 if (!params.use_geometry
1676 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1677 options += "landscape,";
1679 // language should be a parameter to \documentclass
1680 bool use_babel = false;
1681 if (params.language_info->RightToLeft()) // This seems necessary
1682 features.UsedLanguages.insert(default_language);
1683 if (params.language != "default" ||
1684 !features.UsedLanguages.empty() ) {
1686 for (LaTeXFeatures::LanguageList::const_iterator cit =
1687 features.UsedLanguages.begin();
1688 cit != features.UsedLanguages.end(); ++cit)
1689 options += (*cit)->lang() + ",";
1690 options += params.language_info->lang() + ',';
1693 // the user-defined options
1694 if (!params.options.empty()) {
1695 options += params.options + ',';
1698 if (!options.empty()){
1699 options = strip(options, ',');
1700 ofs << '[' << options << ']';
1704 << textclasslist.LatexnameOfClass(params.textclass)
1707 // end of \documentclass defs
1709 // font selection must be done before loading fontenc.sty
1710 if (params.fonts != "default") {
1711 ofs << "\\usepackage{" << params.fonts << "}\n";
1714 // this one is not per buffer
1715 if (lyxrc.fontenc != "default") {
1716 ofs << "\\usepackage[" << lyxrc.fontenc
1720 if (params.inputenc != "default") {
1721 ofs << "\\usepackage[" << params.inputenc
1726 // At the very beginning the text parameters.
1727 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1728 switch (params.paperpackage) {
1729 case BufferParams::PACKAGE_A4:
1730 ofs << "\\usepackage{a4}\n";
1733 case BufferParams::PACKAGE_A4WIDE:
1734 ofs << "\\usepackage{a4wide}\n";
1737 case BufferParams::PACKAGE_WIDEMARGINSA4:
1738 ofs << "\\usepackage[widemargins]{a4}\n";
1743 if (params.use_geometry) {
1744 ofs << "\\usepackage{geometry}\n";
1746 ofs << "\\geometry{verbose";
1747 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1748 ofs << ",landscape";
1749 switch (params.papersize2) {
1750 case BufferParams::VM_PAPER_CUSTOM:
1751 if (!params.paperwidth.empty())
1752 ofs << ",paperwidth="
1753 << params.paperwidth;
1754 if (!params.paperheight.empty())
1755 ofs << ",paperheight="
1756 << params.paperheight;
1758 case BufferParams::VM_PAPER_USLETTER:
1759 ofs << ",letterpaper";
1761 case BufferParams::VM_PAPER_USLEGAL:
1762 ofs << ",legalpaper";
1764 case BufferParams::VM_PAPER_USEXECUTIVE:
1765 ofs << ",executivepaper";
1767 case BufferParams::VM_PAPER_A3:
1770 case BufferParams::VM_PAPER_A4:
1773 case BufferParams::VM_PAPER_A5:
1776 case BufferParams::VM_PAPER_B3:
1779 case BufferParams::VM_PAPER_B4:
1782 case BufferParams::VM_PAPER_B5:
1786 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1787 switch (lyxrc.default_papersize) {
1788 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1789 case BufferParams::PAPER_USLETTER:
1790 ofs << ",letterpaper";
1792 case BufferParams::PAPER_LEGALPAPER:
1793 ofs << ",legalpaper";
1795 case BufferParams::PAPER_EXECUTIVEPAPER:
1796 ofs << ",executivepaper";
1798 case BufferParams::PAPER_A3PAPER:
1801 case BufferParams::PAPER_A4PAPER:
1804 case BufferParams::PAPER_A5PAPER:
1807 case BufferParams::PAPER_B5PAPER:
1812 if (!params.topmargin.empty())
1813 ofs << ",tmargin=" << params.topmargin;
1814 if (!params.bottommargin.empty())
1815 ofs << ",bmargin=" << params.bottommargin;
1816 if (!params.leftmargin.empty())
1817 ofs << ",lmargin=" << params.leftmargin;
1818 if (!params.rightmargin.empty())
1819 ofs << ",rmargin=" << params.rightmargin;
1820 if (!params.headheight.empty())
1821 ofs << ",headheight=" << params.headheight;
1822 if (!params.headsep.empty())
1823 ofs << ",headsep=" << params.headsep;
1824 if (!params.footskip.empty())
1825 ofs << ",footskip=" << params.footskip;
1829 if (params.use_amsmath
1830 && !tclass.provides(LyXTextClass::amsmath)) {
1831 ofs << "\\usepackage{amsmath}\n";
1835 if (tokenPos(tclass.opt_pagestyle(),
1836 '|', params.pagestyle) >= 0) {
1837 if (params.pagestyle == "fancy") {
1838 ofs << "\\usepackage{fancyhdr}\n";
1841 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1845 // We try to load babel late, in case it interferes
1846 // with other packages.
1848 ofs << lyxrc.language_package << endl;
1852 if (params.secnumdepth != tclass.secnumdepth()) {
1853 ofs << "\\setcounter{secnumdepth}{"
1854 << params.secnumdepth
1858 if (params.tocdepth != tclass.tocdepth()) {
1859 ofs << "\\setcounter{tocdepth}{"
1865 if (params.paragraph_separation) {
1866 switch (params.defskip.kind()) {
1867 case VSpace::SMALLSKIP:
1868 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1870 case VSpace::MEDSKIP:
1871 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1873 case VSpace::BIGSKIP:
1874 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1876 case VSpace::LENGTH:
1877 ofs << "\\setlength\\parskip{"
1878 << params.defskip.length().asLatexString()
1881 default: // should never happen // Then delete it.
1882 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1887 ofs << "\\setlength\\parindent{0pt}\n";
1891 // Now insert the LyX specific LaTeX commands...
1893 // The optional packages;
1894 string preamble(features.getPackages());
1896 // this might be useful...
1897 preamble += "\n\\makeatletter\n";
1899 // Some macros LyX will need
1900 string tmppreamble(features.getMacros());
1902 if (!tmppreamble.empty()) {
1903 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1904 "LyX specific LaTeX commands.\n"
1905 + tmppreamble + '\n';
1908 // the text class specific preamble
1909 tmppreamble = features.getTClassPreamble();
1910 if (!tmppreamble.empty()) {
1911 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1912 "Textclass specific LaTeX commands.\n"
1913 + tmppreamble + '\n';
1916 /* the user-defined preamble */
1917 if (!params.preamble.empty()) {
1918 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1919 "User specified LaTeX commands.\n"
1920 + params.preamble + '\n';
1923 preamble += "\\makeatother\n";
1925 // Itemize bullet settings need to be last in case the user
1926 // defines their own bullets that use a package included
1927 // in the user-defined preamble -- ARRae
1928 // Actually it has to be done much later than that
1929 // since some packages like frenchb make modifications
1930 // at \begin{document} time -- JMarc
1932 for (int i = 0; i < 4; ++i) {
1933 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1934 if (bullets_def.empty())
1935 bullets_def="\\AtBeginDocument{\n";
1936 bullets_def += " \\renewcommand{\\labelitemi";
1938 // `i' is one less than the item to modify
1945 bullets_def += "ii";
1951 bullets_def += "}{" +
1952 params.user_defined_bullets[i].getText()
1957 if (!bullets_def.empty())
1958 preamble += bullets_def + "}\n\n";
1960 for (int j = countChar(preamble, '\n'); j-- ;) {
1967 ofs << "\\begin{document}\n";
1970 lyxerr.debug() << "preamble finished, now the body." << endl;
1971 if (!lyxrc.language_auto_begin && params.language != "default") {
1972 ofs << subst(lyxrc.language_command_begin, "$$lang",
1978 latexParagraphs(ofs, paragraph, 0, texrow);
1980 // add this just in case after all the paragraphs
1984 if (!lyxrc.language_auto_end && params.language != "default") {
1985 ofs << subst(lyxrc.language_command_end, "$$lang",
1992 ofs << "\\end{document}\n";
1995 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1997 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2001 // Just to be sure. (Asger)
2004 // tex_code_break_column's value is used to decide
2005 // if we are in batchmode or not (within mathed_write()
2006 // in math_write.C) so we must set it to a non-zero
2007 // value when we leave otherwise we save incorrect .lyx files.
2008 tex_code_break_column = lyxrc.ascii_linelen;
2012 lyxerr << "File was not closed properly." << endl;
2015 lyxerr.debug() << "Finished making latex file." << endl;
2020 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2022 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2023 LyXParagraph * endpar, TexRow & texrow) const
2025 bool was_title = false;
2026 bool already_title = false;
2028 std::ostringstream ftnote;
2030 char * tmpholder = 0;
2036 while (par != endpar) {
2037 #ifndef HAVE_SSTREAM
2040 ftnote << tmpholder;
2041 delete [] tmpholder;
2046 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2048 LyXLayout const & layout =
2049 textclasslist.Style(params.textclass,
2052 if (layout.intitle) {
2053 if (already_title) {
2054 lyxerr <<"Error in latexParagraphs: You"
2055 " should not mix title layouts"
2056 " with normal ones." << endl;
2059 } else if (was_title && !already_title) {
2060 ofs << "\\maketitle\n";
2062 already_title = true;
2065 // We are at depth 0 so we can just use
2066 // ordinary \footnote{} generation
2067 // flag this with ftcount
2069 if (layout.isEnvironment()
2070 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2071 par = par->TeXEnvironment(this, params, ofs, texrow,
2072 ftnote, ft_texrow, ftcount);
2074 par = par->TeXOnePar(this, params, ofs, texrow, false,
2075 ftnote, ft_texrow, ftcount);
2078 // Write out what we've generated...
2081 ofs << "\\addtocounter{footnote}{-"
2085 ofs << ftnote.str();
2086 texrow += ft_texrow;
2088 // The extra .c_str() is needed when we use
2089 // lyxstring instead of the STL string class.
2090 ftnote.str(string().c_str());
2092 delete [] ftnote.str();
2097 #ifndef HAVE_SSTREAM
2099 // I hate strstreams
2100 tmpholder = ftnote.str();
2104 #ifndef HAVE_SSTREAM
2105 delete [] tmpholder;
2107 // It might be that we only have a title in this document
2108 if (was_title && !already_title) {
2109 ofs << "\\maketitle\n";
2115 bool Buffer::isLatex() const
2117 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2121 bool Buffer::isLinuxDoc() const
2123 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2127 bool Buffer::isLiterate() const
2129 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2133 bool Buffer::isDocBook() const
2135 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2139 bool Buffer::isSGML() const
2141 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2142 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2146 void Buffer::sgmlOpenTag(ostream & os, int depth,
2147 string const & latexname) const
2149 os << string(depth, ' ') << "<" << latexname << ">\n";
2153 void Buffer::sgmlCloseTag(ostream & os, int depth,
2154 string const & latexname) const
2156 os << string(depth, ' ') << "</" << latexname << ">\n";
2160 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2162 LyXParagraph * par = paragraph;
2164 niceFile = nice; // this will be used by Insetincludes.
2166 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2167 string environment_stack[10];
2170 int depth = 0; // paragraph depth
2172 ofstream ofs(fname.c_str());
2175 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2179 LyXTextClass const & tclass =
2180 textclasslist.TextClass(params.textclass);
2182 LaTeXFeatures features(params, tclass.numLayouts());
2186 tex_code_break_column = lyxrc.ascii_linelen;
2188 //tex_code_break_column = 0;
2193 string sgml_includedfiles=features.getIncludedFiles();
2195 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2196 ofs << "<!doctype linuxdoc system>\n\n";
2198 ofs << "<!doctype linuxdoc system [ "
2199 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2202 if(params.options.empty())
2203 sgmlOpenTag(ofs, 0, top_element);
2205 string top = top_element;
2207 top += params.options;
2208 sgmlOpenTag(ofs, 0, top);
2212 ofs << "<!-- " << LYX_DOCVERSION
2213 << " created this file. For more info see http://www.lyx.org/"
2217 int desc_on = 0; // description mode
2218 LyXLayout const & style =
2219 textclasslist.Style(params.textclass,
2222 // treat <toc> as a special case for compatibility with old code
2223 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2224 Inset * inset = par->GetInset(0);
2225 Inset::Code lyx_code = inset->LyxCode();
2226 if (lyx_code == Inset::TOC_CODE){
2227 string temp = "toc";
2228 sgmlOpenTag(ofs, depth, temp);
2231 linuxDocHandleFootnote(ofs, par, depth);
2236 // environment tag closing
2237 for( ; depth > par->depth; --depth) {
2238 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2239 environment_stack[depth].erase();
2242 // write opening SGML tags
2243 switch(style.latextype) {
2244 case LATEX_PARAGRAPH:
2245 if(depth == par->depth
2246 && !environment_stack[depth].empty()) {
2247 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2248 environment_stack[depth].erase();
2254 sgmlOpenTag(ofs, depth, style.latexname());
2259 LinuxDocError(par, 0,
2260 _("Error : Wrong depth for"
2261 " LatexType Command.\n"));
2263 if (!environment_stack[depth].empty()){
2264 sgmlCloseTag(ofs, depth,
2265 environment_stack[depth]);
2269 environment_stack[depth].erase();
2270 sgmlOpenTag(ofs, depth, style.latexname());
2273 case LATEX_ENVIRONMENT:
2274 case LATEX_ITEM_ENVIRONMENT:
2275 if(depth == par->depth
2276 && environment_stack[depth] != style.latexname()
2277 && !environment_stack[depth].empty()) {
2279 sgmlCloseTag(ofs, depth,
2280 environment_stack[depth]);
2281 environment_stack[depth].erase();
2283 if (depth < par->depth) {
2285 environment_stack[depth].erase();
2287 if (environment_stack[depth] != style.latexname()) {
2290 sgmlOpenTag(ofs, depth, temp);
2292 environment_stack[depth] = style.latexname();
2293 sgmlOpenTag(ofs, depth,
2294 environment_stack[depth]);
2296 if(style.latextype == LATEX_ENVIRONMENT) break;
2298 desc_on = (style.labeltype == LABEL_MANUAL);
2305 sgmlOpenTag(ofs, depth + 1, item_name);
2308 sgmlOpenTag(ofs, depth, style.latexname());
2313 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2316 linuxDocHandleFootnote(ofs, par, depth);
2318 while(par && par->IsDummy());
2321 // write closing SGML tags
2322 switch(style.latextype) {
2324 case LATEX_ENVIRONMENT:
2325 case LATEX_ITEM_ENVIRONMENT:
2328 sgmlCloseTag(ofs, depth, style.latexname());
2334 for(; depth > 0; --depth)
2335 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2337 if(!environment_stack[depth].empty())
2338 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2342 sgmlCloseTag(ofs, 0, top_element);
2346 // How to check for successful close
2350 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2353 string tag = "footnote";
2355 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2356 sgmlOpenTag(os, depth + 1, tag);
2357 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2358 sgmlCloseTag(os, depth + 1, tag);
2364 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2365 int const depth, int desc_on,
2366 LyXParagraph * & par)
2368 LyXParagraph * tpar = par;
2369 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2370 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2374 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2375 "Caption").second) {
2376 sgmlOpenTag(os, depth + 1, inner_tag);
2378 SimpleDocBookOnePar(os, extra_par, tpar,
2379 desc_on, depth + 2);
2380 sgmlCloseTag(os, depth+1, inner_tag);
2381 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) {
2469 std::ostringstream ost;
2473 SimpleDocBookOnePar(ost, extra_par, par,
2474 desc_on, depth + 2);
2476 tmp_par += ost.str().c_str();
2479 char * ctmp = ost.str();
2484 tmp_par = frontStrip(strip(tmp_par));
2490 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2491 if(!extra_par.empty()) os << extra_par;
2492 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2496 // push a tag in a style stack
2497 void Buffer::push_tag(ostream & os, char const * tag,
2498 int & pos, char stack[5][3])
2500 // pop all previous tags
2501 for (int j = pos; j >= 0; --j)
2502 os << "</" << stack[j] << ">";
2505 sprintf(stack[++pos], "%s", tag);
2508 for (int i = 0; i <= pos; ++i)
2509 os << "<" << stack[i] << ">";
2513 void Buffer::pop_tag(ostream & os, char const * tag,
2514 int & pos, char stack[5][3])
2518 // pop all tags till specified one
2519 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --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]);
2534 // Handle internal paragraph parsing -- layout already processed.
2536 // checks, if newcol chars should be put into this line
2537 // writes newline, if necessary.
2539 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2540 const unsigned int newcol)
2543 if (colcount > lyxrc.ascii_linelen) {
2545 colcount = newcol; // assume write after this call
2550 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2551 int desc_on, int const /*depth*/)
2553 LyXFont font1, font2;
2556 LyXParagraph::size_type main_body;
2558 LyXLayout const & style = textclasslist.Style(params.textclass,
2561 char family_type = 0; // family font flag
2562 bool is_bold = false; // series font flag
2563 char shape_type = 0; // shape font flag
2564 bool is_em = false; // emphasis (italic) font flag
2566 int stack_num = -1; // style stack position
2567 // Can this be rewritten to use a std::stack, please. (Lgb)
2568 char stack[5][3]; // style stack
2569 unsigned int char_line_count = 5; // Heuristic choice ;-)
2571 if (style.labeltype != LABEL_MANUAL)
2574 main_body = par->BeginningOfMainBody();
2576 // gets paragraph main font
2578 font1 = style.labelfont;
2583 // parsing main loop
2584 for (LyXParagraph::size_type i = 0;
2585 i < par->size(); ++i) {
2588 if (i == main_body && !par->IsDummy()) {
2593 font2 = par->getFont(params, i);
2595 if (font1.family() != font2.family()) {
2596 switch(family_type) {
2598 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2599 push_tag(os, "tt", stack_num, stack);
2602 else if (font2.family() == LyXFont::SANS_FAMILY) {
2603 push_tag(os, "sf", stack_num, stack);
2608 pop_tag(os, "tt", stack_num, stack);
2609 if (font2.family() == LyXFont::SANS_FAMILY) {
2610 push_tag(os, "sf", stack_num, stack);
2617 pop_tag(os, "sf", stack_num, stack);
2618 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2619 push_tag(os, "tt", stack_num, stack);
2628 if (font1.series() != font2.series()) {
2629 if (font2.series() == LyXFont::BOLD_SERIES) {
2630 push_tag(os, "bf", stack_num, stack);
2632 } else if (is_bold) {
2633 pop_tag(os, "bf", stack_num, stack);
2638 // handle italic and slanted fonts
2639 if (font1.shape() != font2.shape()) {
2640 switch(shape_type) {
2642 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2643 push_tag(os, "it", stack_num, stack);
2645 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2646 push_tag(os, "sl", stack_num, stack);
2651 pop_tag(os, "it", stack_num, stack);
2652 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2653 push_tag(os, "sl", stack_num, stack);
2660 pop_tag(os, "sl", stack_num, stack);
2661 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2662 push_tag(os, "it", stack_num, stack);
2670 if (font1.emph() != font2.emph()) {
2671 if (font2.emph() == LyXFont::ON) {
2672 push_tag(os, "em", stack_num, stack);
2675 pop_tag(os, "em", stack_num, stack);
2680 c = par->GetChar(i);
2682 if (c == LyXParagraph::META_INSET) {
2683 inset = par->GetInset(i);
2684 inset->Linuxdoc(this, os);
2687 if (font2.latex() == LyXFont::ON) {
2688 // "TeX"-Mode on == > SGML-Mode on.
2690 os << c; // see LaTeX-Generation...
2694 if (par->linuxDocConvertChar(c, sgml_string)
2695 && !style.free_spacing) { // in freespacing
2697 // non-breaking characters
2701 linux_doc_line_break(os, char_line_count, 6);
2705 linux_doc_line_break(os, char_line_count, 1);
2710 char_line_count += sgml_string.length();
2716 // needed if there is an optional argument but no contents
2717 if (main_body > 0 && main_body == par->size()) {
2721 // pop all defined Styles
2722 for (j = stack_num; j >= 0; --j) {
2723 linux_doc_line_break(os,
2725 3 + strlen(stack[j]));
2726 os << "</" << stack[j] << ">";
2729 // resets description flag correctly
2732 // <tag> not closed...
2733 linux_doc_line_break(os, char_line_count, 6);
2737 // fprintf(file, "</p>");
2743 // Print an error message.
2744 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2745 char const * message)
2747 // insert an error marker in text
2748 InsetError * new_inset = new InsetError(message);
2749 par->InsertInset(pos, new_inset);
2752 // This constant defines the maximum number of
2753 // environment layouts that can be nesteded.
2754 // The same applies for command layouts.
2755 // These values should be more than enough.
2756 // José Matos (1999/07/22)
2758 enum { MAX_NEST_LEVEL = 25};
2760 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2762 LyXParagraph * par = paragraph;
2764 niceFile = nice; // this will be used by Insetincludes.
2766 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2767 // Please use a real stack.
2768 string environment_stack[MAX_NEST_LEVEL];
2769 string environment_inner[MAX_NEST_LEVEL];
2770 // Please use a real stack.
2771 string command_stack[MAX_NEST_LEVEL];
2772 bool command_flag= false;
2773 int command_depth= 0, command_base= 0, cmd_depth= 0;
2775 string item_name, command_name;
2776 string c_depth, c_params, tmps;
2778 int depth = 0; // paragraph depth
2779 LyXTextClass const & tclass =
2780 textclasslist.TextClass(params.textclass);
2782 LaTeXFeatures features(params, tclass.numLayouts());
2786 tex_code_break_column = lyxrc.ascii_linelen;
2788 //tex_code_break_column = 0;
2790 ofstream ofs(fname.c_str());
2792 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2799 string sgml_includedfiles=features.getIncludedFiles();
2801 ofs << "<!doctype " << top_element
2802 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2804 if (params.preamble.empty() && sgml_includedfiles.empty())
2807 ofs << "\n [ " << params.preamble
2808 << sgml_includedfiles << " \n]>\n\n";
2810 if(params.options.empty())
2811 sgmlOpenTag(ofs, 0, top_element);
2813 string top = top_element;
2815 top += params.options;
2816 sgmlOpenTag(ofs, 0, top);
2820 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2821 << "\n See http://www.lyx.org/ for more information -->\n";
2824 int desc_on = 0; // description mode
2825 LyXLayout const & style =
2826 textclasslist.Style(params.textclass,
2829 // environment tag closing
2830 for( ; depth > par->depth; --depth) {
2831 if(environment_inner[depth] != "!-- --") {
2832 item_name= "listitem";
2833 sgmlCloseTag(ofs, command_depth + depth,
2835 if( environment_inner[depth] == "varlistentry")
2836 sgmlCloseTag(ofs, depth+command_depth,
2837 environment_inner[depth]);
2839 sgmlCloseTag(ofs, depth + command_depth,
2840 environment_stack[depth]);
2841 environment_stack[depth].erase();
2842 environment_inner[depth].erase();
2845 if(depth == par->depth
2846 && environment_stack[depth] != style.latexname()
2847 && !environment_stack[depth].empty()) {
2848 if(environment_inner[depth] != "!-- --") {
2849 item_name= "listitem";
2850 sgmlCloseTag(ofs, command_depth+depth,
2852 if( environment_inner[depth] == "varlistentry")
2854 depth + command_depth,
2855 environment_inner[depth]);
2858 sgmlCloseTag(ofs, depth + command_depth,
2859 environment_stack[depth]);
2861 environment_stack[depth].erase();
2862 environment_inner[depth].erase();
2865 // Write opening SGML tags.
2866 switch(style.latextype) {
2867 case LATEX_PARAGRAPH:
2868 if(style.latexname() != "dummy")
2869 sgmlOpenTag(ofs, depth+command_depth,
2875 LinuxDocError(par, 0,
2876 _("Error : Wrong depth for "
2877 "LatexType Command.\n"));
2879 command_name = style.latexname();
2881 tmps = style.latexparam();
2882 c_params = split(tmps, c_depth,'|');
2884 cmd_depth= atoi(c_depth.c_str());
2887 if(cmd_depth<command_base) {
2888 for(int j = command_depth;
2889 j >= command_base; --j)
2890 if(!command_stack[j].empty())
2891 sgmlCloseTag(ofs, j, command_stack[j]);
2892 command_depth= command_base= cmd_depth;
2893 } else if(cmd_depth <= command_depth) {
2894 for(int j = command_depth;
2895 j >= cmd_depth; --j)
2897 if(!command_stack[j].empty())
2898 sgmlCloseTag(ofs, j, command_stack[j]);
2899 command_depth= cmd_depth;
2901 command_depth= cmd_depth;
2903 command_depth = command_base = cmd_depth;
2904 command_flag = true;
2906 command_stack[command_depth]= command_name;
2908 // treat label as a special case for
2909 // more WYSIWYM handling.
2910 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2911 Inset * inset = par->GetInset(0);
2912 Inset::Code lyx_code = inset->LyxCode();
2913 if (lyx_code == Inset::LABEL_CODE){
2914 command_name += " id=\"";
2915 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2916 command_name += "\"";
2921 sgmlOpenTag(ofs, depth + command_depth, command_name);
2922 item_name = "title";
2923 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2926 case LATEX_ENVIRONMENT:
2927 case LATEX_ITEM_ENVIRONMENT:
2928 if (depth < par->depth) {
2930 environment_stack[depth].erase();
2933 if (environment_stack[depth] != style.latexname()) {
2934 environment_stack[depth] = style.latexname();
2935 environment_inner[depth] = "!-- --";
2936 sgmlOpenTag(ofs, depth + command_depth,
2937 environment_stack[depth]);
2939 if(environment_inner[depth] != "!-- --") {
2940 item_name= "listitem";
2942 command_depth + depth,
2944 if (environment_inner[depth] == "varlistentry")
2946 depth + command_depth,
2947 environment_inner[depth]);
2951 if(style.latextype == LATEX_ENVIRONMENT) {
2952 if(!style.latexparam().empty())
2953 sgmlOpenTag(ofs, depth + command_depth,
2954 style.latexparam());
2958 desc_on = (style.labeltype == LABEL_MANUAL);
2961 environment_inner[depth]= "varlistentry";
2963 environment_inner[depth]= "listitem";
2965 sgmlOpenTag(ofs, depth + 1 + command_depth,
2966 environment_inner[depth]);
2970 sgmlOpenTag(ofs, depth + 1 + command_depth,
2974 sgmlOpenTag(ofs, depth + 1 + command_depth,
2979 sgmlOpenTag(ofs, depth + command_depth,
2986 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
2987 depth + 1 + command_depth);
2989 DocBookHandleFootnote(ofs, par,
2990 depth + 1 + command_depth);
2992 while(par && par->IsDummy());
2995 // write closing SGML tags
2996 switch(style.latextype) {
2999 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3001 case LATEX_ENVIRONMENT:
3002 if(!style.latexparam().empty())
3003 sgmlCloseTag(ofs, depth + command_depth,
3004 style.latexparam());
3006 case LATEX_ITEM_ENVIRONMENT:
3007 if(desc_on == 1) break;
3009 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3011 case LATEX_PARAGRAPH:
3012 if(style.latexname() != "dummy")
3013 sgmlCloseTag(ofs, depth + command_depth,
3017 sgmlCloseTag(ofs, depth + command_depth,
3024 for(; depth >= 0; --depth) {
3025 if(!environment_stack[depth].empty()) {
3026 if(environment_inner[depth] != "!-- --") {
3027 item_name= "listitem";
3028 sgmlCloseTag(ofs, command_depth + depth,
3030 if( environment_inner[depth] == "varlistentry")
3031 sgmlCloseTag(ofs, depth + command_depth,
3032 environment_inner[depth]);
3035 sgmlCloseTag(ofs, depth + command_depth,
3036 environment_stack[depth]);
3040 for(int j = command_depth; j >= command_base; --j)
3041 if(!command_stack[j].empty())
3042 sgmlCloseTag(ofs, j, command_stack[j]);
3046 sgmlCloseTag(ofs, 0, top_element);
3050 // How to check for successful close
3054 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3055 LyXParagraph * par, int & desc_on,
3060 par->SimpleDocBookOneTablePar(this,
3061 os, extra, desc_on, depth);
3066 bool emph_flag = false;
3068 LyXLayout const & style = textclasslist.Style(params.textclass,
3071 LyXParagraph::size_type main_body;
3072 if (style.labeltype != LABEL_MANUAL)
3075 main_body = par->BeginningOfMainBody();
3077 // gets paragraph main font
3078 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3080 int char_line_count = depth;
3081 if(!style.free_spacing)
3082 for (int j = 0; j < depth; ++j)
3085 // parsing main loop
3086 for (LyXParagraph::size_type i = 0;
3087 i < par->size(); ++i) {
3088 LyXFont font2 = par->getFont(params, i);
3090 // handle <emphasis> tag
3091 if (font1.emph() != font2.emph() && i) {
3092 if (font2.emph() == LyXFont::ON) {
3096 os << "</emphasis>";
3101 char c = par->GetChar(i);
3103 if (c == LyXParagraph::META_INSET) {
3104 Inset * inset = par->GetInset(i);
3106 std::ostringstream ost;
3107 inset->DocBook(this, ost);
3108 string tmp_out = ost.str().c_str();
3111 inset->DocBook(this, ost);
3113 char * ctmp = ost.str();
3114 string tmp_out(ctmp);
3118 // This code needs some explanation:
3119 // Two insets are treated specially
3120 // label if it is the first element in a command paragraph
3122 // graphics inside tables or figure floats can't go on
3123 // title (the equivalente in latex for this case is caption
3124 // and title should come first
3127 if(desc_on!= 3 || i!= 0) {
3128 if(!tmp_out.empty() && tmp_out[0] == '@') {
3130 extra += frontStrip(tmp_out, '@');
3132 os << frontStrip(tmp_out, '@');
3137 } else if (font2.latex() == LyXFont::ON) {
3138 // "TeX"-Mode on ==> SGML-Mode on.
3144 if (par->linuxDocConvertChar(c, sgml_string)
3145 && !style.free_spacing) { // in freespacing
3147 // non-breaking characters
3151 os << "\n</term><listitem><para>";
3163 // needed if there is an optional argument but no contents
3164 if (main_body > 0 && main_body == par->size()) {
3168 os << "</emphasis>";
3171 // resets description flag correctly
3174 // <term> not closed...
3182 int Buffer::runLaTeX()
3184 if (!users->text) return 0;
3186 ProhibitInput(users);
3188 // get LaTeX-Filename
3189 string name = getLatexName();
3191 string path = OnlyPath(filename);
3193 string org_path = path;
3194 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3198 Path p(path); // path to LaTeX file
3199 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3201 // Remove all error insets
3202 bool a = users->removeAutoInsets();
3204 // Always generate the LaTeX file
3205 makeLaTeXFile(name, org_path, false);
3207 // do the LaTex run(s)
3209 string latex_command = lyxrc.pdf_mode ?
3210 lyxrc.pdflatex_command : lyxrc.latex_command;
3211 LaTeX latex(latex_command, name, filepath);
3212 int res = latex.run(terr,
3213 users->owner()->getMiniBuffer()); // running latex
3215 // check return value from latex.run().
3216 if ((res & LaTeX::NO_LOGFILE)) {
3217 WriteAlert(_("LaTeX did not work!"),
3218 _("Missing log file:"), name);
3219 } else if ((res & LaTeX::ERRORS)) {
3220 users->owner()->getMiniBuffer()->Set(_("Done"));
3221 // Insert all errors as errors boxes
3222 users->insertErrors(terr);
3224 // Dvi should also be kept dirty if the latex run
3225 // ends up with errors. However it should be possible
3226 // to view a dirty dvi too.
3228 //no errors or any other things to think about so:
3229 users->owner()->getMiniBuffer()->Set(_("Done"));
3232 // if we removed error insets before we ran LaTeX or if we inserted
3233 // error insets after we ran LaTeX this must be run:
3234 if (a || (res & LaTeX::ERRORS)){
3237 //users->updateScrollbar();
3241 return latex.getNumErrors();
3245 int Buffer::runLiterate()
3247 if (!users->text) return 0;
3249 ProhibitInput(users);
3251 // get LaTeX-Filename
3252 string name = getLatexName();
3253 // get Literate-Filename
3254 string lit_name = OnlyFilename(ChangeExtension (getLatexName(),
3255 lyxrc.literate_extension));
3257 string path = OnlyPath(filename);
3259 string org_path = path;
3260 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3264 Path p(path); // path to Literate file
3265 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3267 // Remove all error insets
3268 bool a = users->removeAutoInsets();
3270 // generate the Literate file if necessary
3271 makeLaTeXFile(lit_name, org_path, false);
3273 string latex_command = lyxrc.pdf_mode ?
3274 lyxrc.pdflatex_command : lyxrc.latex_command;
3275 Literate literate(latex_command, name, filepath,
3277 lyxrc.literate_command, lyxrc.literate_error_filter,
3278 lyxrc.build_command, lyxrc.build_error_filter);
3280 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3282 // check return value from literate.weave().
3283 if ((res & Literate::NO_LOGFILE)) {
3284 WriteAlert(_("Literate command did not work!"),
3285 _("Missing log file:"), name);
3286 } else if ((res & Literate::ERRORS)) {
3287 users->owner()->getMiniBuffer()->Set(_("Done"));
3288 // Insert all errors as errors boxes
3289 users->insertErrors(terr);
3291 // Dvi should also be kept dirty if the latex run
3292 // ends up with errors. However it should be possible
3293 // to view a dirty dvi too.
3295 //no errors or any other things to think about so:
3296 users->owner()->getMiniBuffer()->Set(_("Done"));
3299 // if we removed error insets before we ran LaTeX or if we inserted
3300 // error insets after we ran LaTeX this must be run:
3301 if (a || (res & Literate::ERRORS)){
3304 //users->updateScrollbar();
3308 return literate.getNumErrors();
3312 int Buffer::buildProgram()
3314 if (!users->text) return 0;
3316 ProhibitInput(users);
3318 // get LaTeX-Filename
3319 string name = getLatexName();
3320 // get Literate-Filename
3321 string lit_name = OnlyFilename(ChangeExtension(getLatexName(),
3322 lyxrc.literate_extension));
3324 string path = OnlyPath(filename);
3326 string org_path = path;
3327 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3331 Path p(path); // path to Literate file
3332 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3334 // Remove all error insets
3335 bool a = users->removeAutoInsets();
3337 // generate the LaTeX file if necessary
3338 if (!isNwClean() || a) {
3339 makeLaTeXFile(lit_name, org_path, false);
3343 string latex_command = lyxrc.pdf_mode ?
3344 lyxrc.pdflatex_command : lyxrc.latex_command;
3345 Literate literate(latex_command, name, filepath,
3347 lyxrc.literate_command, lyxrc.literate_error_filter,
3348 lyxrc.build_command, lyxrc.build_error_filter);
3350 int res = literate.build(terr, users->owner()->getMiniBuffer());
3352 // check return value from literate.build().
3353 if ((res & Literate::NO_LOGFILE)) {
3354 WriteAlert(_("Build did not work!"),
3355 _("Missing log file:"), name);
3356 } else if ((res & Literate::ERRORS)) {
3357 users->owner()->getMiniBuffer()->Set(_("Done"));
3358 // Insert all errors as errors boxes
3359 users->insertErrors(terr);
3361 // Literate files should also be kept dirty if the literate
3362 // command run ends up with errors.
3364 //no errors or any other things to think about so:
3365 users->owner()->getMiniBuffer()->Set(_("Done"));
3369 // if we removed error insets before we ran Literate/Build or
3370 // if we inserted error insets after we ran Literate/Build this
3372 if (a || (res & Literate::ERRORS)){
3375 //users->updateScrollbar();
3379 return literate.getNumErrors();
3383 // This should be enabled when the Chktex class is implemented. (Asger)
3384 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3385 // Other flags: -wall -v0 -x
3386 int Buffer::runChktex()
3388 if (!users->text) return 0;
3390 ProhibitInput(users);
3392 // get LaTeX-Filename
3393 string name = getLatexName();
3394 string path = OnlyPath(filename);
3396 string org_path = path;
3397 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3401 Path p(path); // path to LaTeX file
3402 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3404 // Remove all error insets
3405 bool removedErrorInsets = users->removeAutoInsets();
3407 // Generate the LaTeX file if neccessary
3408 makeLaTeXFile(name, org_path, false);
3411 Chktex chktex(lyxrc.chktex_command, name, filepath);
3412 int res = chktex.run(terr); // run chktex
3415 WriteAlert(_("chktex did not work!"),
3416 _("Could not run with file:"), name);
3417 } else if (res > 0) {
3418 // Insert all errors as errors boxes
3419 users->insertErrors(terr);
3422 // if we removed error insets before we ran chktex or if we inserted
3423 // error insets after we ran chktex, this must be run:
3424 if (removedErrorInsets || res){
3427 //users->updateScrollbar();
3435 void Buffer::validate(LaTeXFeatures & features) const
3437 LyXParagraph * par = paragraph;
3438 LyXTextClass const & tclass =
3439 textclasslist.TextClass(params.textclass);
3441 // AMS Style is at document level
3443 features.amsstyle = (params.use_amsmath ||
3444 tclass.provides(LyXTextClass::amsmath));
3447 // We don't use "lyxerr.debug" because of speed. (Asger)
3448 if (lyxerr.debugging(Debug::LATEX))
3449 lyxerr << "Paragraph: " << par << endl;
3451 // Now just follow the list of paragraphs and run
3452 // validate on each of them.
3453 par->validate(features);
3455 // and then the next paragraph
3459 // the bullet shapes are buffer level not paragraph level
3460 // so they are tested here
3461 for (int i = 0; i < 4; ++i) {
3462 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3463 int font = params.user_defined_bullets[i].getFont();
3466 .user_defined_bullets[i]
3473 features.latexsym = true;
3477 features.amssymb = true;
3479 else if ((font >= 2 && font <= 5)) {
3480 features.pifont = true;
3485 if (lyxerr.debugging(Debug::LATEX)) {
3486 features.showStruct();
3491 void Buffer::setPaperStuff()
3493 params.papersize = BufferParams::PAPER_DEFAULT;
3494 char c1 = params.paperpackage;
3495 if (c1 == BufferParams::PACKAGE_NONE) {
3496 char c2 = params.papersize2;
3497 if (c2 == BufferParams::VM_PAPER_USLETTER)
3498 params.papersize = BufferParams::PAPER_USLETTER;
3499 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3500 params.papersize = BufferParams::PAPER_LEGALPAPER;
3501 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3502 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3503 else if (c2 == BufferParams::VM_PAPER_A3)
3504 params.papersize = BufferParams::PAPER_A3PAPER;
3505 else if (c2 == BufferParams::VM_PAPER_A4)
3506 params.papersize = BufferParams::PAPER_A4PAPER;
3507 else if (c2 == BufferParams::VM_PAPER_A5)
3508 params.papersize = BufferParams::PAPER_A5PAPER;
3509 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3510 (c2 == BufferParams::VM_PAPER_B5))
3511 params.papersize = BufferParams::PAPER_B5PAPER;
3512 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3513 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3514 params.papersize = BufferParams::PAPER_A4PAPER;
3518 // This function should be in Buffer because it's a buffer's property (ale)
3519 string Buffer::getIncludeonlyList(char delim)
3522 for (inset_iterator it = inset_iterator_begin();
3523 it != inset_iterator_end(); ++it) {
3524 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3525 InsetInclude * insetinc =
3526 static_cast<InsetInclude *>(*it);
3527 if (insetinc->isInclude()
3528 && insetinc->isNoLoad()) {
3531 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3535 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3540 vector<string> Buffer::getLabelList()
3542 /// if this is a child document and the parent is already loaded
3543 /// Use the parent's list instead [ale990407]
3544 if (!params.parentname.empty()
3545 && bufferlist.exists(params.parentname)) {
3546 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3548 return tmp->getLabelList();
3551 vector<string> label_list;
3552 for (inset_iterator it = inset_iterator_begin();
3553 it != inset_iterator_end(); ++it) {
3554 vector<string> l = (*it)->getLabelList();
3555 label_list.insert(label_list.end(), l.begin(), l.end());
3561 vector<vector<Buffer::TocItem> > Buffer::getTocList()
3563 vector<vector<TocItem> > l(4);
3564 LyXParagraph * par = paragraph;
3566 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3567 if (textclasslist.Style(params.textclass,
3568 par->GetLayout()).labeltype
3569 == LABEL_SENSITIVE) {
3573 tmp.str = par->String(this, false);
3574 switch (par->footnotekind) {
3575 case LyXParagraph::FIG:
3576 case LyXParagraph::WIDE_FIG:
3577 l[TOC_LOF].push_back(tmp);
3579 case LyXParagraph::TAB:
3580 case LyXParagraph::WIDE_TAB:
3581 l[TOC_LOT].push_back(tmp);
3583 case LyXParagraph::ALGORITHM:
3584 l[TOC_LOA].push_back(tmp);
3586 case LyXParagraph::FOOTNOTE:
3587 case LyXParagraph::MARGIN:
3591 } else if (!par->IsDummy()) {
3592 char labeltype = textclasslist.Style(params.textclass,
3593 par->GetLayout()).labeltype;
3595 if (labeltype >= LABEL_COUNTER_CHAPTER
3596 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3597 // insert this into the table of contents
3602 textclasslist.TextClass(params.textclass).maxcounter());
3603 tmp.str = par->String(this, true);
3604 l[TOC_TOC].push_back(tmp);
3612 // This is also a buffer property (ale)
3613 vector<pair<string,string> > Buffer::getBibkeyList()
3615 /// if this is a child document and the parent is already loaded
3616 /// Use the parent's list instead [ale990412]
3617 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3618 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3620 return tmp->getBibkeyList();
3623 vector<pair<string, string> > keys;
3624 LyXParagraph * par = paragraph;
3627 keys.push_back(pair<string,string>(par->bibkey->getContents(),
3628 par->String(this, false)));
3632 // Might be either using bibtex or a child has bibliography
3634 for (inset_iterator it = inset_iterator_begin();
3635 it != inset_iterator_end(); ++it) {
3636 // Search for Bibtex or Include inset
3637 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3638 vector<pair<string,string> > tmp =
3639 static_cast<InsetBibtex*>(*it)->getKeys();
3640 keys.insert(keys.end(), tmp.begin(), tmp.end());
3641 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3642 vector<pair<string,string> > tmp =
3643 static_cast<InsetInclude*>(*it)->getKeys();
3644 keys.insert(keys.end(), tmp.begin(), tmp.end());
3653 bool Buffer::isDepClean(string const & name) const
3655 DEPCLEAN * item = dep_clean;
3656 while (item && item->master != name)
3658 if (!item) return true;
3663 void Buffer::markDepClean(string const & name)
3666 dep_clean = new DEPCLEAN;
3667 dep_clean->clean = true;
3668 dep_clean->master = name;
3669 dep_clean->next = 0;
3671 DEPCLEAN* item = dep_clean;
3672 while (item && item->master != name)
3677 item = new DEPCLEAN;
3679 item->master = name;
3686 bool Buffer::Dispatch(string const & command)
3688 // Split command string into command and argument
3689 string cmd, line = frontStrip(command);
3690 string arg = strip(frontStrip(split(line, cmd, ' ')));
3692 return Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3696 bool Buffer::Dispatch(int action, string const & argument)
3698 bool dispatched = true;
3701 MenuExport(this, argument);
3711 void Buffer::resize()
3713 /// first resize the BufferViews!
3717 /// then remove all LyXText in text-insets
3718 LyXParagraph * par = paragraph;
3719 for(;par;par = par->next) {
3720 par->deleteInsetsLyXText(users);
3725 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3728 LyXParagraph * par = paragraph;
3730 par->ChangeLanguage(params, from, to);
3736 bool Buffer::isMultiLingual()
3739 LyXParagraph * par = paragraph;
3741 if (par->isMultiLingual(params))
3749 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3750 LyXParagraph::size_type pos)
3752 it = par->InsetIterator(pos);
3753 if (it == par->inset_iterator_end()) {
3760 void Buffer::inset_iterator::SetParagraph() {
3762 it = par->inset_iterator_begin();
3763 if (it != par->inset_iterator_end())
3768 // We maintain an invariant that whenever par = 0 then it = 0