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 "support/filetools.h"
75 #include "support/path.h"
81 #include "LaTeXFeatures.h"
82 #include "support/syscall.h"
83 #include "support/lyxlib.h"
84 #include "support/FileInfo.h"
88 #include "lyx_gui_misc.h" // WarnReadonly()
89 #include "frontends/Dialogs.h"
102 // all these externs should eventually be removed.
103 extern BufferList bufferlist;
105 extern void MenuExport(Buffer *, string const &);
106 extern LyXAction lyxaction;
109 static const float LYX_FORMAT = 2.16;
111 extern int tex_code_break_column;
114 Buffer::Buffer(string const & file, bool ronly)
116 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
118 filepath = OnlyPath(file);
126 if (read_only || (lyxrc.use_tempdir)) {
127 tmppath = CreateBufferTmpDir();
128 } else tmppath.erase();
134 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
135 // here the buffer should take care that it is
136 // saved properly, before it goes into the void.
138 // make sure that views using this buffer
143 if (!tmppath.empty()) {
144 DestroyBufferTmpDir(tmppath);
147 LyXParagraph * par = paragraph;
148 LyXParagraph * tmppar;
158 string Buffer::getLatexName(bool no_path) const
161 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
164 return ChangeExtension(MakeLatexName(filename),
169 void Buffer::setReadonly(bool flag)
171 if (read_only != flag) {
174 users->owner()->getDialogs()->updateBufferDependent();
177 WarnReadonly(filename);
182 bool Buffer::saveParamsAsDefaults()
184 string fname = AddName(AddPath(user_lyxdir, "templates/"),
186 Buffer defaults = Buffer(fname);
188 // Use the current buffer's parameters as default
189 defaults.params = params;
191 // add an empty paragraph. Is this enough?
192 defaults.paragraph = new LyXParagraph;
194 return defaults.writeFile(defaults.filename, false);
198 /// Update window titles of all users
199 // Should work on a list
200 void Buffer::updateTitles() const
202 if (users) users->owner()->updateWindowTitle();
206 /// Reset autosave timer of all users
207 // Should work on a list
208 void Buffer::resetAutosaveTimers() const
210 if (users) users->owner()->resetAutosaveTimer();
214 void Buffer::fileName(string const & newfile)
216 filename = MakeAbsPath(newfile);
217 filepath = OnlyPath(filename);
218 setReadonly(IsFileWriteable(filename) == 0);
223 // candidate for move to BufferView
224 // (at least some parts in the beginning of the func)
227 // changed to be public and have one parameter
228 // if par = 0 normal behavior
229 // else insert behavior
230 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
231 #define USE_PARSE_FUNCTION 1
232 //#define USE_TABULAR_INSETS 1
233 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
237 char depth = 0; // signed or unsigned?
238 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
239 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
240 bool the_end_read = false;
242 LyXParagraph * return_par = 0;
243 LyXFont font(LyXFont::ALL_INHERIT, params.language_info);
244 if (format < 2.16 && params.language == "hebrew")
245 font.setLanguage(default_language);
247 // If we are inserting, we cheat and get a token in advance
248 bool has_token = false;
252 par = new LyXParagraph;
254 users->text->BreakParagraph(users);
255 return_par = users->text->FirstParagraph();
258 // We don't want to adopt the parameters from the
259 // document we insert, so we skip until the text begins:
262 pretoken = lex.GetString();
263 if (pretoken == "\\layout") {
275 pretoken = lex.GetString();
278 // Profiling show this should give a lot: (Asger)
279 string const token = pretoken;
283 the_end_read = parseSingleLyXformat2Token(lex, par, return_par,
292 paragraph = return_par;
299 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
300 LyXParagraph *& return_par,
301 string const & token, int & pos,
302 char & depth, LyXFont & font,
303 LyXParagraph::footnote_flag & footnoteflag,
304 LyXParagraph::footnote_kind & footnotekind)
306 bool the_end_read = false;
308 if (token[0] != '\\') {
309 for (string::const_iterator cit = token.begin();
310 cit != token.end(); ++cit) {
311 par->InsertChar(pos, (*cit), font);
314 } else if (token == "\\i") {
315 Inset * inset = new InsetLatexAccent;
316 inset->Read(this, lex);
317 par->InsertInset(pos, inset, font);
319 } else if (token == "\\layout") {
324 par = new LyXParagraph(par);
328 string layoutname = lex.GetString();
329 pair<bool, LyXTextClass::LayoutList::size_type> pp
330 = textclasslist.NumberOfLayout(params.textclass,
333 par->layout = pp.second;
334 } else { // layout not found
335 // use default layout "Standard" (0)
338 // Test whether the layout is obsolete.
339 LyXLayout const & layout =
340 textclasslist.Style(params.textclass,
342 if (!layout.obsoleted_by().empty())
344 textclasslist.NumberOfLayout(params.textclass,
345 layout.obsoleted_by()).second;
346 par->footnoteflag = footnoteflag;
347 par->footnotekind = footnotekind;
349 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
350 if (format < 2.16 && params.language == "hebrew")
351 font.setLanguage(default_language);
353 } else if (token == "\\end_float") {
358 par = new LyXParagraph(par);
360 footnotekind = LyXParagraph::FOOTNOTE;
361 footnoteflag = LyXParagraph::NO_FOOTNOTE;
364 par->layout = LYX_DUMMY_LAYOUT;
365 font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
366 if (format < 2.16 && params.language == "hebrew")
367 font.setLanguage(default_language);
368 } else if (token == "\\begin_float") {
369 int tmpret = lex.FindToken(string_footnotekinds);
370 if (tmpret == -1) ++tmpret;
371 if (tmpret != LYX_LAYOUT_DEFAULT)
372 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
373 if (footnotekind == LyXParagraph::FOOTNOTE
374 || footnotekind == LyXParagraph::MARGIN)
375 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
377 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
379 } else if (token == "\\begin_float") {
380 // This is the compability reader, unfinished but tested.
383 string tmptok = lex.GetString();
384 //lyxerr << "old float: " << tmptok << endl;
388 if (tmptok == "footnote") {
389 inset = new InsetFoot;
390 } else if (tmptok == "margin") {
391 inset = new InsetMarginal;
392 } else if (tmptok == "fig") {
393 //inset = new InsetFigure;
394 } else if (tmptok == "tab") {
395 //inset = new InsetTable;
396 } else if (tmptok == "alg") {
397 //inset = new InsetAlgorithm;
398 } else if (tmptok == "wide-fig") {
399 //inset = new InsetFigure(true);
400 } else if (tmptok == "wide-tab") {
401 //inset = new InsetTable(true);
404 if (!inset) return false; // no end read yet
406 string old_float = "\ncollapsed true\n";
407 old_float += lex.getLongString("\\end_float");
408 old_float += "\n\\end_inset\n";
409 lyxerr << "float body: " << old_float << endl;
411 istrstream istr(old_float.c_str());
413 nylex.setStream(istr);
415 inset->Read(this, nylex);
416 par->InsertInset(pos, inset, font);
419 } else if (token == "\\begin_deeper") {
421 } else if (token == "\\end_deeper") {
423 lex.printError("\\end_deeper: "
424 "depth is already null");
428 } else if (token == "\\begin_preamble") {
429 params.readPreamble(lex);
430 } else if (token == "\\textclass") {
432 pair<bool, LyXTextClassList::size_type> pp =
433 textclasslist.NumberOfClass(lex.GetString());
435 params.textclass = pp.second;
437 lex.printError("Unknown textclass `$$Token'");
438 params.textclass = 0;
440 if (!textclasslist.Load(params.textclass)) {
441 // if the textclass wasn't loaded properly
442 // we need to either substitute another
443 // or stop loading the file.
444 // I can substitute but I don't see how I can
445 // stop loading... ideas?? ARRae980418
446 WriteAlert(_("Textclass Loading Error!"),
447 string(_("Can't load textclass ")) +
448 textclasslist.NameOfClass(params.textclass),
449 _("-- substituting default"));
450 params.textclass = 0;
452 } else if (token == "\\options") {
454 params.options = lex.GetString();
455 } else if (token == "\\language") {
456 params.readLanguage(lex);
457 } else if (token == "\\fontencoding") {
459 } else if (token == "\\inputencoding") {
461 params.inputenc = lex.GetString();
462 } else if (token == "\\graphics") {
463 params.readGraphicsDriver(lex);
464 } else if (token == "\\fontscheme") {
466 params.fonts = lex.GetString();
467 } else if (token == "\\noindent") {
468 par->noindent = true;
469 } else if (token == "\\fill_top") {
470 par->added_space_top = VSpace(VSpace::VFILL);
471 } else if (token == "\\fill_bottom") {
472 par->added_space_bottom = VSpace(VSpace::VFILL);
473 } else if (token == "\\line_top") {
474 par->line_top = true;
475 } else if (token == "\\line_bottom") {
476 par->line_bottom = true;
477 } else if (token == "\\pagebreak_top") {
478 par->pagebreak_top = true;
479 } else if (token == "\\pagebreak_bottom") {
480 par->pagebreak_bottom = true;
481 } else if (token == "\\start_of_appendix") {
482 par->start_of_appendix = true;
483 } else if (token == "\\paragraph_separation") {
484 int tmpret = lex.FindToken(string_paragraph_separation);
485 if (tmpret == -1) ++tmpret;
486 if (tmpret != LYX_LAYOUT_DEFAULT)
487 params.paragraph_separation =
488 static_cast<BufferParams::PARSEP>(tmpret);
489 } else if (token == "\\defskip") {
491 params.defskip = VSpace(lex.GetString());
492 } else if (token == "\\epsfig") { // obsolete
493 // Indeed it is obsolete, but we HAVE to be backwards
494 // compatible until 0.14, because otherwise all figures
495 // in existing documents are irretrivably lost. (Asger)
496 params.readGraphicsDriver(lex);
497 } else if (token == "\\quotes_language") {
498 int tmpret = lex.FindToken(string_quotes_language);
499 if (tmpret == -1) ++tmpret;
500 if (tmpret != LYX_LAYOUT_DEFAULT) {
501 InsetQuotes::quote_language tmpl =
502 InsetQuotes::EnglishQ;
505 tmpl = InsetQuotes::EnglishQ;
508 tmpl = InsetQuotes::SwedishQ;
511 tmpl = InsetQuotes::GermanQ;
514 tmpl = InsetQuotes::PolishQ;
517 tmpl = InsetQuotes::FrenchQ;
520 tmpl = InsetQuotes::DanishQ;
523 params.quotes_language = tmpl;
525 } else if (token == "\\quotes_times") {
527 switch(lex.GetInteger()) {
529 params.quotes_times = InsetQuotes::SingleQ;
532 params.quotes_times = InsetQuotes::DoubleQ;
535 } else if (token == "\\papersize") {
536 int tmpret = lex.FindToken(string_papersize);
540 params.papersize2 = tmpret;
541 } else if (token == "\\paperpackage") {
542 int tmpret = lex.FindToken(string_paperpackages);
545 params.paperpackage = BufferParams::PACKAGE_NONE;
547 params.paperpackage = tmpret;
548 } else if (token == "\\use_geometry") {
550 params.use_geometry = lex.GetInteger();
551 } else if (token == "\\use_amsmath") {
553 params.use_amsmath = lex.GetInteger();
554 } else if (token == "\\paperorientation") {
555 int tmpret = lex.FindToken(string_orientation);
556 if (tmpret == -1) ++tmpret;
557 if (tmpret != LYX_LAYOUT_DEFAULT)
558 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
559 } else if (token == "\\paperwidth") {
561 params.paperwidth = lex.GetString();
562 } else if (token == "\\paperheight") {
564 params.paperheight = lex.GetString();
565 } else if (token == "\\leftmargin") {
567 params.leftmargin = lex.GetString();
568 } else if (token == "\\topmargin") {
570 params.topmargin = lex.GetString();
571 } else if (token == "\\rightmargin") {
573 params.rightmargin = lex.GetString();
574 } else if (token == "\\bottommargin") {
576 params.bottommargin = lex.GetString();
577 } else if (token == "\\headheight") {
579 params.headheight = lex.GetString();
580 } else if (token == "\\headsep") {
582 params.headsep = lex.GetString();
583 } else if (token == "\\footskip") {
585 params.footskip = lex.GetString();
586 } else if (token == "\\paperfontsize") {
588 params.fontsize = strip(lex.GetString());
589 } else if (token == "\\papercolumns") {
591 params.columns = lex.GetInteger();
592 } else if (token == "\\papersides") {
594 switch(lex.GetInteger()) {
596 case 1: params.sides = LyXTextClass::OneSide; break;
597 case 2: params.sides = LyXTextClass::TwoSides; break;
599 } else if (token == "\\paperpagestyle") {
601 params.pagestyle = strip(lex.GetString());
602 } else if (token == "\\bullet") {
604 int index = lex.GetInteger();
606 int temp_int = lex.GetInteger();
607 params.user_defined_bullets[index].setFont(temp_int);
608 params.temp_bullets[index].setFont(temp_int);
610 temp_int = lex.GetInteger();
611 params.user_defined_bullets[index].setCharacter(temp_int);
612 params.temp_bullets[index].setCharacter(temp_int);
614 temp_int = lex.GetInteger();
615 params.user_defined_bullets[index].setSize(temp_int);
616 params.temp_bullets[index].setSize(temp_int);
618 string temp_str = lex.GetString();
619 if (temp_str != "\\end_bullet") {
620 // this element isn't really necessary for
621 // parsing but is easier for humans
622 // to understand bullets. Put it back and
623 // set a debug message?
624 lex.printError("\\end_bullet expected, got" + temp_str);
625 //how can I put it back?
627 } else if (token == "\\bulletLaTeX") {
629 int index = lex.GetInteger();
631 string temp_str = lex.GetString(), sum_str;
632 while (temp_str != "\\end_bullet") {
633 // this loop structure is needed when user
634 // enters an empty string since the first
635 // thing returned will be the \\end_bullet
637 // if the LaTeX entry has spaces. Each element
638 // therefore needs to be read in turn
641 temp_str = lex.GetString();
643 params.user_defined_bullets[index].setText(sum_str);
644 params.temp_bullets[index].setText(sum_str);
645 } else if (token == "\\secnumdepth") {
647 params.secnumdepth = lex.GetInteger();
648 } else if (token == "\\tocdepth") {
650 params.tocdepth = lex.GetInteger();
651 } else if (token == "\\spacing") {
653 string tmp = strip(lex.GetString());
654 Spacing::Space tmp_space = Spacing::Default;
656 if (tmp == "single") {
657 tmp_space = Spacing::Single;
658 } else if (tmp == "onehalf") {
659 tmp_space = Spacing::Onehalf;
660 } else if (tmp == "double") {
661 tmp_space = Spacing::Double;
662 } else if (tmp == "other") {
664 tmp_space = Spacing::Other;
665 tmp_val = lex.GetFloat();
667 lex.printError("Unknown spacing token: '$$Token'");
669 // Small hack so that files written with klyx will be
672 par->spacing.set(tmp_space, tmp_val);
674 params.spacing.set(tmp_space, tmp_val);
676 } else if (token == "\\paragraph_spacing") {
678 string tmp = strip(lex.GetString());
679 if (tmp == "single") {
680 par->spacing.set(Spacing::Single);
681 } else if (tmp == "onehalf") {
682 par->spacing.set(Spacing::Onehalf);
683 } else if (tmp == "double") {
684 par->spacing.set(Spacing::Double);
685 } else if (tmp == "other") {
687 par->spacing.set(Spacing::Other,
690 lex.printError("Unknown spacing token: '$$Token'");
692 } else if (token == "\\float_placement") {
694 params.float_placement = lex.GetString();
695 } else if (token == "\\family") {
697 font.setLyXFamily(lex.GetString());
698 } else if (token == "\\series") {
700 font.setLyXSeries(lex.GetString());
701 } else if (token == "\\shape") {
703 font.setLyXShape(lex.GetString());
704 } else if (token == "\\size") {
706 font.setLyXSize(lex.GetString());
707 } else if (token == "\\latex") {
709 string tok = lex.GetString();
710 // This is dirty, but gone with LyX3. (Asger)
711 if (tok == "no_latex")
712 font.setLatex(LyXFont::OFF);
713 else if (tok == "latex")
714 font.setLatex(LyXFont::ON);
715 else if (tok == "default")
716 font.setLatex(LyXFont::INHERIT);
718 lex.printError("Unknown LaTeX font flag "
720 } else if (token == "\\lang") {
722 string tok = lex.GetString();
723 Languages::iterator lit = languages.find(tok);
724 if (lit != languages.end()) {
725 font.setLanguage(&(*lit).second);
727 font.setLanguage(params.language_info);
728 lex.printError("Unknown language `$$Token'");
730 } else if (token == "\\emph") {
732 font.setEmph(font.setLyXMisc(lex.GetString()));
733 } else if (token == "\\bar") {
735 string tok = lex.GetString();
736 // This is dirty, but gone with LyX3. (Asger)
738 font.setUnderbar(LyXFont::ON);
739 else if (tok == "no")
740 font.setUnderbar(LyXFont::OFF);
741 else if (tok == "default")
742 font.setUnderbar(LyXFont::INHERIT);
744 lex.printError("Unknown bar font flag "
746 } else if (token == "\\noun") {
748 font.setNoun(font.setLyXMisc(lex.GetString()));
749 } else if (token == "\\color") {
751 font.setLyXColor(lex.GetString());
752 } else if (token == "\\align") {
753 int tmpret = lex.FindToken(string_align);
754 if (tmpret == -1) ++tmpret;
755 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
757 for (; tmpret > 0; --tmpret)
758 tmpret2 = tmpret2 * 2;
759 par->align = LyXAlignment(tmpret2);
761 } else if (token == "\\added_space_top") {
763 par->added_space_top = VSpace(lex.GetString());
764 } else if (token == "\\added_space_bottom") {
766 par->added_space_bottom = VSpace(lex.GetString());
767 } else if (token == "\\pextra_type") {
769 par->pextra_type = lex.GetInteger();
770 } else if (token == "\\pextra_width") {
772 par->pextra_width = lex.GetString();
773 } else if (token == "\\pextra_widthp") {
775 par->pextra_widthp = lex.GetString();
776 } else if (token == "\\pextra_alignment") {
778 par->pextra_alignment = lex.GetInteger();
779 } else if (token == "\\pextra_hfill") {
781 par->pextra_hfill = lex.GetInteger();
782 } else if (token == "\\pextra_start_minipage") {
784 par->pextra_start_minipage = lex.GetInteger();
785 } else if (token == "\\labelwidthstring") {
787 par->labelwidthstring = lex.GetString();
788 // do not delete this token, it is still needed!
789 } else if (token == "\\end_inset") {
790 // Simply ignore this. The insets do not have
792 // But insets should read it, it is a part of
793 // the inset isn't it? Lgb.
794 } else if (token == "\\begin_inset") {
795 // Should be moved out into its own function/method. (Lgb)
797 string tmptok = lex.GetString();
798 // test the different insets
799 if (tmptok == "Quotes") {
800 Inset * inset = new InsetQuotes;
801 inset->Read(this, lex);
802 par->InsertInset(pos, inset, font);
804 } else if (tmptok == "External") {
805 Inset * inset = new InsetExternal;
806 inset->Read(this, lex);
807 par->InsertInset(pos, inset, font);
809 } else if (tmptok == "FormulaMacro") {
810 Inset * inset = new InsetFormulaMacro;
811 inset->Read(this, lex);
812 par->InsertInset(pos, inset, font);
814 } else if (tmptok == "Formula") {
815 Inset * inset = new InsetFormula;
816 inset->Read(this, lex);
817 par->InsertInset(pos, inset, font);
819 } else if (tmptok == "Figure") {
820 Inset * inset = new InsetFig(100, 100, this);
821 inset->Read(this, lex);
822 par->InsertInset(pos, inset, font);
824 } else if (tmptok == "Info") {
825 Inset * inset = new InsetInfo;
826 inset->Read(this, lex);
827 par->InsertInset(pos, inset, font);
829 } else if (tmptok == "Include") {
830 Inset * inset = new InsetInclude(string(), this);
831 inset->Read(this, lex);
832 par->InsertInset(pos, inset, font);
834 } else if (tmptok == "ERT") {
835 Inset * inset = new InsetERT;
836 inset->Read(this, lex);
837 par->InsertInset(pos, inset, font);
839 } else if (tmptok == "Tabular") {
840 Inset * inset = new InsetTabular(this);
841 inset->Read(this, lex);
842 par->InsertInset(pos, inset, font);
844 } else if (tmptok == "Text") {
845 Inset * inset = new InsetText;
846 inset->Read(this, lex);
847 par->InsertInset(pos, inset, font);
849 } else if (tmptok == "Foot") {
850 Inset * inset = new InsetFoot;
851 inset->Read(this, lex);
852 par->InsertInset(pos, inset, font);
854 } else if (tmptok == "Marginal") {
855 Inset * inset = new InsetMarginal;
856 inset->Read(this, lex);
857 par->InsertInset(pos, inset, font);
859 } else if (tmptok == "Minipage") {
860 Inset * inset = new InsetMinipage;
861 inset->Read(this, lex);
862 par->InsertInset(pos, inset, font);
864 } else if (tmptok == "Float") {
865 Inset * inset = new InsetFloat;
866 inset->Read(this, lex);
867 par->InsertInset(pos, inset, font);
869 } else if (tmptok == "List") {
870 Inset * inset = new InsetList;
871 inset->Read(this, lex);
872 par->InsertInset(pos, inset, font);
874 } else if (tmptok == "GRAPHICS") {
875 Inset * inset = new InsetGraphics;
876 //inset->Read(this, lex);
877 par->InsertInset(pos, inset, font);
878 } else if (tmptok == "LatexCommand") {
880 inscmd.Read(this, lex);
882 if (inscmd.getCmdName() == "cite") {
883 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
884 } else if (inscmd.getCmdName() == "bibitem") {
885 lex.printError("Wrong place for bibitem");
886 inset = inscmd.Clone();
887 } else if (inscmd.getCmdName() == "BibTeX") {
888 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
889 } else if (inscmd.getCmdName() == "index") {
890 inset = new InsetIndex(inscmd.getContents());
891 } else if (inscmd.getCmdName() == "include") {
892 inset = new InsetInclude(inscmd.getContents(), this);
893 } else if (inscmd.getCmdName() == "label") {
894 inset = new InsetLabel(inscmd.getCommand());
895 } else if (inscmd.getCmdName() == "url"
896 || inscmd.getCmdName() == "htmlurl") {
897 inset = new InsetUrl(inscmd.getCommand());
898 } else if (inscmd.getCmdName() == "ref"
899 || inscmd.getCmdName() == "pageref"
900 || inscmd.getCmdName() == "vref"
901 || inscmd.getCmdName() == "vpageref"
902 || inscmd.getCmdName() == "prettyref") {
903 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
904 inset = new InsetRef(inscmd, this);
906 } else if (inscmd.getCmdName() == "tableofcontents") {
907 inset = new InsetTOC(this);
908 } else if (inscmd.getCmdName() == "listoffigures") {
909 inset = new InsetLOF(this);
910 } else if (inscmd.getCmdName() == "listofalgorithms") {
911 inset = new InsetLOA(this);
912 } else if (inscmd.getCmdName() == "listoftables") {
913 inset = new InsetLOT(this);
914 } else if (inscmd.getCmdName() == "printindex") {
915 inset = new InsetPrintIndex(this);
916 } else if (inscmd.getCmdName() == "lyxparent") {
917 inset = new InsetParent(inscmd.getContents(), this);
921 par->InsertInset(pos, inset, font);
925 } else if (token == "\\SpecialChar") {
926 LyXLayout const & layout =
927 textclasslist.Style(params.textclass,
930 // Insets don't make sense in a free-spacing context! ---Kayvan
931 if (layout.free_spacing) {
935 next_token = lex.GetString();
936 if (next_token == "\\-") {
937 par->InsertChar(pos, '-', font);
938 } else if (next_token == "\\protected_separator"
939 || next_token == "~") {
940 par->InsertChar(pos, ' ', font);
942 lex.printError("Token `$$Token' "
944 "paragraph layout!");
949 Inset * inset = new InsetSpecialChar;
950 inset->Read(this, lex);
951 par->InsertInset(pos, inset, font);
954 } else if (token == "\\newline") {
955 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
957 } else if (token == "\\LyXTable") {
958 #ifdef USE_TABULAR_INSETS
959 Inset * inset = new InsetTabular(this);
960 inset->Read(this, lex);
961 par->InsertInset(pos, inset, font);
964 par->table = new LyXTable(lex);
966 } else if (token == "\\hfill") {
967 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
969 } else if (token == "\\protected_separator") { // obsolete
970 // This is a backward compability thingie. (Lgb)
971 // Remove it later some time...introduced with fileformat
973 LyXLayout const & layout =
974 textclasslist.Style(params.textclass,
977 if (layout.free_spacing) {
978 par->InsertChar(pos, ' ', font);
980 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
981 par->InsertInset(pos, inset, font);
984 } else if (token == "\\bibitem") { // ale970302
986 par->bibkey = new InsetBibKey;
987 par->bibkey->Read(this, lex);
988 }else if (token == "\\backslash") {
989 par->InsertChar(pos, '\\', font);
991 }else if (token == "\\the_end") {
994 // This should be insurance for the future: (Asger)
995 lex.printError("Unknown token `$$Token'. "
996 "Inserting as text.");
997 for(string::const_iterator cit = token.begin();
998 cit != token.end(); ++cit) {
999 par->InsertChar(pos, (*cit), font);
1003 return the_end_read;
1006 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1012 token = lex.GetString();
1013 if (token == "\\lyxformat") { // the first token _must_ be...
1015 format = lex.GetFloat();
1017 if (LYX_FORMAT - format > 0.05) {
1018 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1019 LYX_FORMAT, format);
1021 if (format - LYX_FORMAT > 0.05) {
1022 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1023 LYX_FORMAT, format);
1025 bool the_end = readLyXformat2(lex, par);
1026 // Formats >= 2.13 support "\the_end" marker
1033 WriteAlert(_("Warning!"),
1034 _("Reading of document is not complete"),
1035 _("Maybe the document is truncated"));
1036 // We simulate a safe reading anyways to allow
1037 // users to take the chance... (Asger)
1041 WriteAlert(_("ERROR!"),
1042 _("Old LyX file format found. "
1043 "Use LyX 0.10.x to read this!"));
1047 } else { // "\\lyxformat" not found
1048 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1051 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1057 // Should probably be moved to somewhere else: BufferView? LyXView?
1058 bool Buffer::save() const
1060 // We don't need autosaves in the immediate future. (Asger)
1061 resetAutosaveTimers();
1065 if (lyxrc.make_backup) {
1066 s = fileName() + '~';
1067 if (!lyxrc.backupdir_path.empty())
1068 s = AddName(lyxrc.backupdir_path,
1069 subst(CleanupPath(s),'/','!'));
1071 // Rename is the wrong way of making a backup,
1072 // this is the correct way.
1073 /* truss cp fil fil2:
1074 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1075 stat("LyXVC.lyx", 0xEFFFF688) = 0
1076 open("LyXVC.lyx", O_RDONLY) = 3
1077 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1078 fstat(4, 0xEFFFF508) = 0
1079 fstat(3, 0xEFFFF508) = 0
1080 read(3, " # T h i s f i l e w".., 8192) = 5579
1081 write(4, " # T h i s f i l e w".., 5579) = 5579
1082 read(3, 0xEFFFD4A0, 8192) = 0
1085 chmod("LyXVC3.lyx", 0100644) = 0
1086 lseek(0, 0, SEEK_CUR) = 46440
1090 // Should proabaly have some more error checking here.
1091 // Should be cleaned up in 0.13, at least a bit.
1092 // Doing it this way, also makes the inodes stay the same.
1093 // This is still not a very good solution, in particular we
1094 // might loose the owner of the backup.
1095 FileInfo finfo(fileName());
1096 if (finfo.exist()) {
1097 mode_t fmode = finfo.getMode();
1098 struct utimbuf times = {
1099 finfo.getAccessTime(),
1100 finfo.getModificationTime() };
1102 ifstream ifs(fileName().c_str());
1103 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1108 ::chmod(s.c_str(), fmode);
1110 if (::utime(s.c_str(), ×)) {
1111 lyxerr << "utime error." << endl;
1114 lyxerr << "LyX was not able to make "
1115 "backupcopy. Beware." << endl;
1120 if (writeFile(fileName(), false)) {
1123 // now delete the autosavefile
1124 string a = OnlyPath(fileName());
1126 a += OnlyFilename(fileName());
1128 FileInfo fileinfo(a);
1129 if (fileinfo.exist()) {
1130 if (::remove(a.c_str()) != 0) {
1131 WriteFSAlert(_("Could not delete "
1132 "auto-save file!"), a);
1136 // Saving failed, so backup is not backup
1137 if (lyxrc.make_backup) {
1138 ::rename(s.c_str(), fileName().c_str());
1146 // Returns false if unsuccesful
1147 bool Buffer::writeFile(string const & fname, bool flag) const
1149 // if flag is false writeFile will not create any GUI
1150 // warnings, only cerr.
1151 // Needed for autosave in background or panic save (Matthias 120496)
1153 if (read_only && (fname == filename)) {
1154 // Here we should come with a question if we should
1155 // perform the write anyway.
1157 lyxerr << _("Error! Document is read-only: ")
1160 WriteAlert(_("Error! Document is read-only: "),
1165 FileInfo finfo(fname);
1166 if (finfo.exist() && !finfo.writable()) {
1167 // Here we should come with a question if we should
1168 // try to do the save anyway. (i.e. do a chmod first)
1170 lyxerr << _("Error! Cannot write file: ")
1173 WriteFSAlert(_("Error! Cannot write file: "),
1178 ofstream ofs(fname.c_str());
1181 lyxerr << _("Error! Cannot open file: ")
1184 WriteFSAlert(_("Error! Cannot open file: "),
1188 // The top of the file should not be written by params.
1190 // write out a comment in the top of the file
1191 ofs << '#' << LYX_DOCVERSION
1192 << " created this file. For more info see http://www.lyx.org/\n";
1193 ofs.setf(ios::showpoint|ios::fixed);
1195 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1197 // now write out the buffer paramters.
1198 params.writeFile(ofs);
1200 char footnoteflag = 0;
1203 // this will write out all the paragraphs
1204 // using recursive descent.
1205 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1207 // Write marker that shows file is complete
1208 ofs << "\n\\the_end" << endl;
1210 // how to check if close went ok?
1215 void Buffer::writeFileAscii(string const & fname, int linelen)
1217 LyXFont font1, font2;
1219 char c, footnoteflag = 0, depth = 0;
1221 LyXParagraph::size_type i;
1222 int j, h, ltype = 0, ltype_depth = 0,
1223 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1226 bool ref_printed = false;
1228 ofstream ofs(fname.c_str());
1230 WriteFSAlert(_("Error: Cannot write file:"), fname);
1234 string fname1 = TmpFileName();
1235 LyXParagraph * par = paragraph;
1239 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1241 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1243 /* begins a footnote environment ? */
1244 if (footnoteflag != par->footnoteflag) {
1245 footnoteflag = par->footnoteflag;
1247 j = strlen(string_footnotekinds[par->footnotekind])+4;
1248 if (currlinelen + j > linelen)
1251 << string_footnotekinds[par->footnotekind] << "] ";
1256 /* begins or ends a deeper area ?*/
1257 if (depth != par->depth) {
1258 if (par->depth > depth) {
1259 while (par->depth > depth) {
1264 while (par->depth < depth) {
1270 /* First write the layout */
1271 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1272 if (tmp == "Itemize") {
1274 ltype_depth = depth+1;
1275 } else if (tmp == "Enumerate") {
1277 ltype_depth = depth+1;
1278 } else if (strstr(tmp.c_str(), "ection")) {
1280 ltype_depth = depth+1;
1281 } else if (strstr(tmp.c_str(), "aragraph")) {
1283 ltype_depth = depth+1;
1284 } else if (tmp == "Description") {
1286 ltype_depth = depth+1;
1287 } else if (tmp == "Abstract") {
1290 } else if (tmp == "Bibliography") {
1298 /* maybe some vertical spaces */
1300 /* the labelwidthstring used in lists */
1304 /* some pagebreaks? */
1308 /* what about the alignment */
1310 /* dummy layout, that means a footnote ended */
1311 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1316 //LyXLayout const & layout =
1317 // textclasslist.Style(params.textclass,
1318 // par->GetLayout()); // unused
1319 //bool free_spc = layout.free_spacing; //unused
1322 /* It might be a table */
1326 cells = par->table->columns;
1327 clen = new int [cells];
1328 memset(clen, 0, sizeof(int) * cells);
1330 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1331 c = par->GetChar(i);
1332 if (c == LyXParagraph::META_INSET) {
1333 if ((inset = par->GetInset(i))) {
1335 std::ostringstream ost;
1336 inset->Ascii(this, ost);
1337 h += ost.str().length();
1340 inset->Ascii(this, ost);
1342 char * tmp = ost.str();
1348 } else if (c == LyXParagraph::META_NEWLINE) {
1352 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1360 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1362 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1363 if (!i && !footnoteflag && !noparbreak){
1365 for(j = 0; j < depth; ++j)
1367 currlinelen = depth * 2;
1369 case 0: /* Standard */
1370 case 4: /* (Sub)Paragraph */
1371 case 5: /* Description */
1373 case 6: /* Abstract */
1374 ofs << "Abstract\n\n";
1376 case 7: /* Bibliography */
1378 ofs << "References\n\n";
1383 ofs << par->labelstring << " ";
1386 if (ltype_depth > depth) {
1387 for(j = ltype_depth - 1; j > depth; --j)
1389 currlinelen += (ltype_depth-depth)*2;
1393 for(j = 0; j < cells; ++j) {
1395 for(h = 0; h < (clen[j] + 1);
1400 for(j = 0; j < depth; ++j)
1402 currlinelen = depth * 2;
1403 if (ltype_depth > depth) {
1404 for(j = ltype_depth;
1407 currlinelen += (ltype_depth-depth)*2;
1413 font2 = par->GetFontSettings(params, i);
1414 if (font1.latex() != font2.latex()) {
1415 if (font2.latex() == LyXFont::OFF)
1422 c = par->GetChar(i);
1426 case LyXParagraph::META_INSET:
1427 if ((inset = par->GetInset(i))) {
1429 inset->Ascii(this, ofs);
1430 currlinelen += (ofs.tellp() - fpos);
1431 actpos += (ofs.tellp() - fpos) - 1;
1434 case LyXParagraph::META_NEWLINE:
1437 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1438 for(j = actpos; j < clen[cell - 1]; ++j)
1441 for(j = 0; j < depth; ++j)
1443 currlinelen = depth*2;
1444 if (ltype_depth > depth) {
1445 for(j = ltype_depth; j > depth; --j)
1447 currlinelen += (ltype_depth-depth) * 2;
1449 for(j = 0; j < cells; ++j) {
1451 for(h = 0; h < (clen[j] + 1); ++h)
1455 for(j = 0; j < depth; ++j)
1457 currlinelen = depth * 2;
1458 if (ltype_depth > depth) {
1459 for(j = ltype_depth;
1462 currlinelen += (ltype_depth-depth)*2;
1468 j < clen[cell - 1]; ++j)
1474 currlinelen = actpos = 0;
1478 for(j = 0; j < depth; ++j)
1480 currlinelen = depth * 2;
1481 if (ltype_depth > depth) {
1482 for(j = ltype_depth;
1485 currlinelen += (ltype_depth - depth) * 2;
1491 case LyXParagraph::META_HFILL:
1498 if (currlinelen > linelen - 10
1499 && c == ' ' && i + 2 < par->size()) {
1501 for(j = 0; j < depth; ++j)
1503 currlinelen = depth * 2;
1504 if (ltype_depth > depth) {
1505 for(j = ltype_depth;
1508 currlinelen += (ltype_depth-depth)*2;
1510 } else if (c != '\0')
1513 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1520 for(j = actpos; j < clen[cell - 1]; ++j)
1523 for(j = 0; j < depth; ++j)
1525 currlinelen = depth * 2;
1526 if (ltype_depth > depth) {
1527 for(j = ltype_depth; j > depth; --j)
1529 currlinelen += (ltype_depth - depth) * 2;
1531 for(j = 0; j < cells; ++j) {
1533 for(h = 0; h < (clen[j] + 1); ++h)
1547 void Buffer::makeLaTeXFile(string const & fname,
1548 string const & original_path,
1549 bool nice, bool only_body)
1551 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1553 niceFile = nice; // this will be used by Insetincludes.
1555 tex_code_break_column = lyxrc.ascii_linelen;
1557 LyXTextClass const & tclass =
1558 textclasslist.TextClass(params.textclass);
1560 ofstream ofs(fname.c_str());
1562 WriteFSAlert(_("Error: Cannot open file: "), fname);
1566 // validate the buffer.
1567 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1568 LaTeXFeatures features(params, tclass.numLayouts());
1570 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1573 // The starting paragraph of the coming rows is the
1574 // first paragraph of the document. (Asger)
1575 texrow.start(paragraph, 0);
1577 if (!only_body && nice) {
1578 ofs << "%% " LYX_DOCVERSION " created this file. "
1579 "For more info, see http://www.lyx.org/.\n"
1580 "%% Do not edit unless you really know what "
1585 lyxerr.debug() << "lyx header finished" << endl;
1586 // There are a few differences between nice LaTeX and usual files:
1587 // usual is \batchmode and has a
1588 // special input@path to allow the including of figures
1589 // with either \input or \includegraphics (what figinsets do).
1590 // batchmode is not set if there is a tex_code_break_column.
1591 // In this case somebody is interested in the generated LaTeX,
1592 // so this is OK. input@path is set when the actual parameter
1593 // original_path is set. This is done for usual tex-file, but not
1594 // for nice-latex-file. (Matthias 250696)
1597 // code for usual, NOT nice-latex-file
1598 ofs << "\\batchmode\n"; // changed
1599 // from \nonstopmode
1602 if (!original_path.empty()) {
1603 ofs << "\\makeatletter\n"
1604 << "\\def\\input@path{{"
1605 << original_path << "/}}\n"
1606 << "\\makeatother\n";
1612 ofs << "\\documentclass";
1614 string options; // the document class options.
1616 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1617 // only write if existing in list (and not default)
1618 options += params.fontsize;
1623 if (!params.use_geometry &&
1624 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1625 switch (params.papersize) {
1626 case BufferParams::PAPER_A4PAPER:
1627 options += "a4paper,";
1629 case BufferParams::PAPER_USLETTER:
1630 options += "letterpaper,";
1632 case BufferParams::PAPER_A5PAPER:
1633 options += "a5paper,";
1635 case BufferParams::PAPER_B5PAPER:
1636 options += "b5paper,";
1638 case BufferParams::PAPER_EXECUTIVEPAPER:
1639 options += "executivepaper,";
1641 case BufferParams::PAPER_LEGALPAPER:
1642 options += "legalpaper,";
1648 if (params.sides != tclass.sides()) {
1649 switch (params.sides) {
1650 case LyXTextClass::OneSide:
1651 options += "oneside,";
1653 case LyXTextClass::TwoSides:
1654 options += "twoside,";
1661 if (params.columns != tclass.columns()) {
1662 if (params.columns == 2)
1663 options += "twocolumn,";
1665 options += "onecolumn,";
1668 if (!params.use_geometry
1669 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1670 options += "landscape,";
1672 // language should be a parameter to \documentclass
1673 bool use_babel = false;
1674 if (params.language_info->RightToLeft()) // This seems necessary
1675 features.UsedLanguages.insert(default_language);
1676 if (params.language != "default" ||
1677 !features.UsedLanguages.empty() ) {
1679 for (LaTeXFeatures::LanguageList::const_iterator cit =
1680 features.UsedLanguages.begin();
1681 cit != features.UsedLanguages.end(); ++cit)
1682 options += (*cit)->lang() + ",";
1683 options += params.language_info->lang() + ',';
1686 // the user-defined options
1687 if (!params.options.empty()) {
1688 options += params.options + ',';
1691 if (!options.empty()){
1692 options = strip(options, ',');
1693 ofs << '[' << options << ']';
1697 << textclasslist.LatexnameOfClass(params.textclass)
1700 // end of \documentclass defs
1702 // font selection must be done before loading fontenc.sty
1703 if (params.fonts != "default") {
1704 ofs << "\\usepackage{" << params.fonts << "}\n";
1707 // this one is not per buffer
1708 if (lyxrc.fontenc != "default") {
1709 ofs << "\\usepackage[" << lyxrc.fontenc
1713 if (params.inputenc != "default") {
1714 ofs << "\\usepackage[" << params.inputenc
1719 // At the very beginning the text parameters.
1720 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1721 switch (params.paperpackage) {
1722 case BufferParams::PACKAGE_A4:
1723 ofs << "\\usepackage{a4}\n";
1726 case BufferParams::PACKAGE_A4WIDE:
1727 ofs << "\\usepackage{a4wide}\n";
1730 case BufferParams::PACKAGE_WIDEMARGINSA4:
1731 ofs << "\\usepackage[widemargins]{a4}\n";
1736 if (params.use_geometry) {
1737 ofs << "\\usepackage{geometry}\n";
1739 ofs << "\\geometry{verbose";
1740 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1741 ofs << ",landscape";
1742 switch (params.papersize2) {
1743 case BufferParams::VM_PAPER_CUSTOM:
1744 if (!params.paperwidth.empty())
1745 ofs << ",paperwidth="
1746 << params.paperwidth;
1747 if (!params.paperheight.empty())
1748 ofs << ",paperheight="
1749 << params.paperheight;
1751 case BufferParams::VM_PAPER_USLETTER:
1752 ofs << ",letterpaper";
1754 case BufferParams::VM_PAPER_USLEGAL:
1755 ofs << ",legalpaper";
1757 case BufferParams::VM_PAPER_USEXECUTIVE:
1758 ofs << ",executivepaper";
1760 case BufferParams::VM_PAPER_A3:
1763 case BufferParams::VM_PAPER_A4:
1766 case BufferParams::VM_PAPER_A5:
1769 case BufferParams::VM_PAPER_B3:
1772 case BufferParams::VM_PAPER_B4:
1775 case BufferParams::VM_PAPER_B5:
1779 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1780 switch (lyxrc.default_papersize) {
1781 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1782 case BufferParams::PAPER_USLETTER:
1783 ofs << ",letterpaper";
1785 case BufferParams::PAPER_LEGALPAPER:
1786 ofs << ",legalpaper";
1788 case BufferParams::PAPER_EXECUTIVEPAPER:
1789 ofs << ",executivepaper";
1791 case BufferParams::PAPER_A3PAPER:
1794 case BufferParams::PAPER_A4PAPER:
1797 case BufferParams::PAPER_A5PAPER:
1800 case BufferParams::PAPER_B5PAPER:
1805 if (!params.topmargin.empty())
1806 ofs << ",tmargin=" << params.topmargin;
1807 if (!params.bottommargin.empty())
1808 ofs << ",bmargin=" << params.bottommargin;
1809 if (!params.leftmargin.empty())
1810 ofs << ",lmargin=" << params.leftmargin;
1811 if (!params.rightmargin.empty())
1812 ofs << ",rmargin=" << params.rightmargin;
1813 if (!params.headheight.empty())
1814 ofs << ",headheight=" << params.headheight;
1815 if (!params.headsep.empty())
1816 ofs << ",headsep=" << params.headsep;
1817 if (!params.footskip.empty())
1818 ofs << ",footskip=" << params.footskip;
1822 if (params.use_amsmath
1823 && !tclass.provides(LyXTextClass::amsmath)) {
1824 ofs << "\\usepackage{amsmath}\n";
1828 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1829 if (params.pagestyle == "fancy") {
1830 ofs << "\\usepackage{fancyhdr}\n";
1833 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1837 // We try to load babel late, in case it interferes
1838 // with other packages.
1840 ofs << lyxrc.language_package << endl;
1844 if (params.secnumdepth != tclass.secnumdepth()) {
1845 ofs << "\\setcounter{secnumdepth}{"
1846 << params.secnumdepth
1850 if (params.tocdepth != tclass.tocdepth()) {
1851 ofs << "\\setcounter{tocdepth}{"
1857 if (params.paragraph_separation) {
1858 switch (params.defskip.kind()) {
1859 case VSpace::SMALLSKIP:
1860 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1862 case VSpace::MEDSKIP:
1863 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1865 case VSpace::BIGSKIP:
1866 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1868 case VSpace::LENGTH:
1869 ofs << "\\setlength\\parskip{"
1870 << params.defskip.length().asLatexString()
1873 default: // should never happen // Then delete it.
1874 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1879 ofs << "\\setlength\\parindent{0pt}\n";
1883 // Now insert the LyX specific LaTeX commands...
1884 string preamble, tmppreamble;
1886 // The optional packages;
1887 preamble = features.getPackages();
1889 // this might be useful...
1890 preamble += "\n\\makeatletter\n\n";
1892 // Some macros LyX will need
1893 tmppreamble = features.getMacros();
1895 if (!tmppreamble.empty()) {
1896 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1897 "LyX specific LaTeX commands.\n"
1898 + tmppreamble + '\n';
1901 // the text class specific preamble
1902 tmppreamble = features.getTClassPreamble();
1903 if (!tmppreamble.empty()) {
1904 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1905 "Textclass specific LaTeX commands.\n"
1906 + tmppreamble + '\n';
1909 /* the user-defined preamble */
1910 if (!params.preamble.empty()) {
1911 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1912 "User specified LaTeX commands.\n"
1913 + params.preamble + '\n';
1916 preamble += "\\makeatother\n\n";
1918 // Itemize bullet settings need to be last in case the user
1919 // defines their own bullets that use a package included
1920 // in the user-defined preamble -- ARRae
1921 // Actually it has to be done much later than that
1922 // since some packages like frenchb make modifications
1923 // at \begin{document} time -- JMarc
1925 for (int i = 0; i < 4; ++i) {
1926 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1927 if (bullets_def.empty())
1928 bullets_def="\\AtBeginDocument{\n";
1929 bullets_def += " \\renewcommand{\\labelitemi";
1931 // `i' is one less than the item to modify
1938 bullets_def += "ii";
1944 bullets_def += "}{" +
1945 params.user_defined_bullets[i].getText()
1950 if (!bullets_def.empty())
1951 preamble += bullets_def + "}\n\n";
1953 for (int j = countChar(preamble, '\n'); j-- ;) {
1960 ofs << "\\begin{document}\n\n";
1964 lyxerr.debug() << "preamble finished, now the body." << endl;
1965 if (!lyxrc.language_auto_begin && params.language != "default") {
1966 ofs << subst(lyxrc.language_command_begin, "$$lang",
1972 latexParagraphs(ofs, paragraph, 0, texrow);
1974 // add this just in case after all the paragraphs
1978 if (!lyxrc.language_auto_end && params.language != "default") {
1979 ofs << subst(lyxrc.language_command_end, "$$lang",
1986 ofs << "\\end{document}\n";
1989 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1991 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1995 // Just to be sure. (Asger)
1998 // tex_code_break_column's value is used to decide
1999 // if we are in batchmode or not (within mathed_write()
2000 // in math_write.C) so we must set it to a non-zero
2001 // value when we leave otherwise we save incorrect .lyx files.
2002 tex_code_break_column = lyxrc.ascii_linelen;
2006 lyxerr << "File was not closed properly." << endl;
2009 lyxerr.debug() << "Finished making latex file." << endl;
2013 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2015 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph *par,
2016 LyXParagraph *endpar, TexRow & texrow) const
2018 bool was_title = false;
2019 bool already_title = false;
2021 std::ostringstream ftnote;
2023 char * tmpholder = 0;
2029 while (par != endpar) {
2030 #ifndef HAVE_SSTREAM
2033 ftnote << tmpholder;
2034 delete [] tmpholder;
2039 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2041 LyXLayout const & layout =
2042 textclasslist.Style(params.textclass,
2045 if (layout.intitle) {
2046 if (already_title) {
2047 lyxerr <<"Error in latexParagraphs: You"
2048 " should not mix title layouts"
2049 " with normal ones." << endl;
2052 } else if (was_title && !already_title) {
2053 ofs << "\\maketitle\n";
2055 already_title = true;
2058 // We are at depth 0 so we can just use
2059 // ordinary \footnote{} generation
2060 // flag this with ftcount
2062 if (layout.isEnvironment()
2063 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2064 par = par->TeXEnvironment(this, params, ofs, texrow,
2065 ftnote, ft_texrow, ftcount);
2067 par = par->TeXOnePar(this, params, ofs, texrow, false,
2068 ftnote, ft_texrow, ftcount);
2071 // Write out what we've generated...
2074 ofs << "\\addtocounter{footnote}{-"
2078 ofs << ftnote.str();
2079 texrow += ft_texrow;
2081 // The extra .c_str() is needed when we use
2082 // lyxstring instead of the STL string class.
2083 ftnote.str(string().c_str());
2085 delete [] ftnote.str();
2090 #ifndef HAVE_SSTREAM
2092 // I hate strstreams
2093 tmpholder = ftnote.str();
2097 #ifndef HAVE_SSTREAM
2098 delete [] tmpholder;
2100 // It might be that we only have a title in this document
2101 if (was_title && !already_title) {
2102 ofs << "\\maketitle\n";
2107 bool Buffer::isLatex() const
2109 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2113 bool Buffer::isLinuxDoc() const
2115 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2119 bool Buffer::isLiterate() const
2121 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2125 bool Buffer::isDocBook() const
2127 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2131 bool Buffer::isSGML() const
2133 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2134 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2138 void Buffer::sgmlOpenTag(ostream & os, int depth,
2139 string const & latexname) const
2141 os << string(depth, ' ') << "<" << latexname << ">\n";
2145 void Buffer::sgmlCloseTag(ostream & os, int depth,
2146 string const & latexname) const
2148 os << string(depth, ' ') << "</" << latexname << ">\n";
2152 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2154 LyXParagraph * par = paragraph;
2156 niceFile = nice; // this will be used by Insetincludes.
2158 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2159 string environment_stack[10];
2162 int depth = 0; // paragraph depth
2164 ofstream ofs(fname.c_str());
2167 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2171 LyXTextClass const & tclass =
2172 textclasslist.TextClass(params.textclass);
2174 LaTeXFeatures features(params, tclass.numLayouts());
2178 tex_code_break_column = lyxrc.ascii_linelen;
2180 tex_code_break_column = 0;
2185 string sgml_includedfiles=features.getIncludedFiles();
2187 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2188 ofs << "<!doctype linuxdoc system>\n\n";
2191 ofs << "<!doctype linuxdoc system [ "
2192 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2195 if(params.options.empty())
2196 sgmlOpenTag(ofs, 0, top_element);
2198 string top = top_element;
2200 top += params.options;
2201 sgmlOpenTag(ofs, 0, top);
2205 ofs << "<!-- " << LYX_DOCVERSION
2206 << " created this file. For more info see http://www.lyx.org/"
2210 int desc_on = 0; // description mode
2211 LyXLayout const & style =
2212 textclasslist.Style(params.textclass,
2215 // treat <toc> as a special case for compatibility with old code
2216 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2217 Inset * inset = par->GetInset(0);
2218 Inset::Code lyx_code = inset->LyxCode();
2219 if (lyx_code == Inset::TOC_CODE){
2220 string temp = "toc";
2221 sgmlOpenTag(ofs, depth, temp);
2224 linuxDocHandleFootnote(ofs, par, depth);
2229 // environment tag closing
2230 for( ; depth > par->depth; --depth) {
2231 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2232 environment_stack[depth].erase();
2235 // write opening SGML tags
2236 switch(style.latextype) {
2237 case LATEX_PARAGRAPH:
2238 if(depth == par->depth
2239 && !environment_stack[depth].empty()) {
2240 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2241 environment_stack[depth].erase();
2247 sgmlOpenTag(ofs, depth, style.latexname());
2252 LinuxDocError(par, 0,
2253 _("Error : Wrong depth for"
2254 " LatexType Command.\n"));
2256 if (!environment_stack[depth].empty()){
2257 sgmlCloseTag(ofs, depth,
2258 environment_stack[depth]);
2262 environment_stack[depth].erase();
2263 sgmlOpenTag(ofs, depth, style.latexname());
2266 case LATEX_ENVIRONMENT:
2267 case LATEX_ITEM_ENVIRONMENT:
2268 if(depth == par->depth
2269 && environment_stack[depth] != style.latexname()
2270 && !environment_stack[depth].empty()) {
2272 sgmlCloseTag(ofs, depth,
2273 environment_stack[depth]);
2274 environment_stack[depth].erase();
2276 if (depth < par->depth) {
2278 environment_stack[depth].erase();
2280 if (environment_stack[depth] != style.latexname()) {
2283 sgmlOpenTag(ofs, depth, temp);
2285 environment_stack[depth] = style.latexname();
2286 sgmlOpenTag(ofs, depth,
2287 environment_stack[depth]);
2289 if(style.latextype == LATEX_ENVIRONMENT) break;
2291 desc_on = (style.labeltype == LABEL_MANUAL);
2298 sgmlOpenTag(ofs, depth + 1, item_name);
2301 sgmlOpenTag(ofs, depth, style.latexname());
2306 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2309 linuxDocHandleFootnote(ofs, par, depth);
2311 while(par && par->IsDummy());
2314 // write closing SGML tags
2315 switch(style.latextype) {
2317 case LATEX_ENVIRONMENT:
2318 case LATEX_ITEM_ENVIRONMENT:
2321 sgmlCloseTag(ofs, depth, style.latexname());
2327 for(; depth > 0; --depth)
2328 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2330 if(!environment_stack[depth].empty())
2331 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2335 sgmlCloseTag(ofs, 0, top_element);
2339 // How to check for successful close
2343 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2346 string tag = "footnote";
2348 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2349 sgmlOpenTag(os, depth + 1, tag);
2350 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2351 sgmlCloseTag(os, depth + 1, tag);
2357 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2358 int const depth, int desc_on,
2359 LyXParagraph * & par)
2361 LyXParagraph * tpar = par;
2362 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2363 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2367 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2368 "Caption").second) {
2369 sgmlOpenTag(os, depth + 1, inner_tag);
2371 SimpleDocBookOnePar(os, extra_par, tpar,
2372 desc_on, depth + 2);
2373 sgmlCloseTag(os, depth+1, inner_tag);
2374 if(!extra_par.empty())
2380 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2383 string tag, inner_tag;
2384 string tmp_par, extra_par;
2385 bool inner_span = false;
2388 // Someone should give this enum a proper name (Lgb)
2396 SOME_ENUM last = NO_ONE;
2397 SOME_ENUM present = FOOTNOTE_LIKE;
2399 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2400 if(last == present) {
2402 if(!tmp_par.empty()) {
2405 sgmlCloseTag(os, depth + 1, inner_tag);
2406 sgmlOpenTag(os, depth + 1, inner_tag);
2413 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2415 if(!extra_par.empty()) os << extra_par;
2416 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2419 switch (par->footnotekind) {
2420 case LyXParagraph::FOOTNOTE:
2421 case LyXParagraph::ALGORITHM:
2424 present = FOOTNOTE_LIKE;
2427 case LyXParagraph::MARGIN:
2430 present = MARGIN_LIKE;
2433 case LyXParagraph::FIG:
2434 case LyXParagraph::WIDE_FIG:
2436 inner_tag = "title";
2440 case LyXParagraph::TAB:
2441 case LyXParagraph::WIDE_TAB:
2443 inner_tag = "title";
2448 sgmlOpenTag(os, depth, tag);
2449 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2450 DocBookHandleCaption(os, inner_tag, depth,
2454 sgmlOpenTag(os, depth + 1, inner_tag);
2457 // ignore all caption here, we processed them above!!!
2458 if (par->layout != textclasslist
2459 .NumberOfLayout(params.textclass,
2460 "Caption").second) {
2462 std::ostringstream ost;
2466 SimpleDocBookOnePar(ost, extra_par, par,
2467 desc_on, depth + 2);
2469 tmp_par += ost.str().c_str();
2472 char * ctmp = ost.str();
2477 tmp_par = frontStrip(strip(tmp_par));
2483 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2484 if(!extra_par.empty()) os << extra_par;
2485 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2489 // push a tag in a style stack
2490 void Buffer::push_tag(ostream & os, char const * tag,
2491 int & pos, char stack[5][3])
2493 // pop all previous tags
2494 for (int j = pos; j >= 0; --j)
2495 os << "</" << stack[j] << ">";
2498 sprintf(stack[++pos], "%s", tag);
2501 for (int i = 0; i <= pos; ++i)
2502 os << "<" << stack[i] << ">";
2506 void Buffer::pop_tag(ostream & os, char const * tag,
2507 int & pos, char stack[5][3])
2511 // pop all tags till specified one
2512 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2513 os << "</" << stack[j] << ">";
2516 os << "</" << tag << ">";
2518 // push all tags, but the specified one
2519 for (j = j + 1; j <= pos; ++j) {
2520 os << "<" << stack[j] << ">";
2521 strcpy(stack[j-1], stack[j]);
2527 // Handle internal paragraph parsing -- layout already processed.
2529 // checks, if newcol chars should be put into this line
2530 // writes newline, if necessary.
2532 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2533 const unsigned int newcol)
2536 if (colcount > lyxrc.ascii_linelen) {
2538 colcount = newcol; // assume write after this call
2543 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2544 int desc_on, int const /*depth*/)
2546 LyXFont font1, font2;
2549 LyXParagraph::size_type main_body;
2551 LyXLayout const & style = textclasslist.Style(params.textclass,
2554 char family_type = 0; // family font flag
2555 bool is_bold = false; // series font flag
2556 char shape_type = 0; // shape font flag
2557 bool is_em = false; // emphasis (italic) font flag
2559 int stack_num = -1; // style stack position
2560 // Can this be rewritten to use a std::stack, please. (Lgb)
2561 char stack[5][3]; // style stack
2562 unsigned int char_line_count = 5; // Heuristic choice ;-)
2564 if (style.labeltype != LABEL_MANUAL)
2567 main_body = par->BeginningOfMainBody();
2569 // gets paragraph main font
2571 font1 = style.labelfont;
2576 // parsing main loop
2577 for (LyXParagraph::size_type i = 0;
2578 i < par->size(); ++i) {
2581 if (i == main_body && !par->IsDummy()) {
2586 font2 = par->getFont(params, i);
2588 if (font1.family() != font2.family()) {
2589 switch(family_type) {
2591 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2592 push_tag(os, "tt", stack_num, stack);
2595 else if (font2.family() == LyXFont::SANS_FAMILY) {
2596 push_tag(os, "sf", stack_num, stack);
2601 pop_tag(os, "tt", stack_num, stack);
2602 if (font2.family() == LyXFont::SANS_FAMILY) {
2603 push_tag(os, "sf", stack_num, stack);
2611 pop_tag(os, "sf", stack_num, stack);
2612 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2613 push_tag(os, "tt", stack_num, stack);
2623 if (font1.series() != font2.series()) {
2624 if (font2.series() == LyXFont::BOLD_SERIES) {
2625 push_tag(os, "bf", stack_num, stack);
2629 pop_tag(os, "bf", stack_num, stack);
2634 // handle italic and slanted fonts
2635 if (font1.shape() != font2.shape()) {
2636 switch(shape_type) {
2638 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2639 push_tag(os, "it", stack_num, stack);
2642 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2643 push_tag(os, "sl", stack_num, stack);
2648 pop_tag(os, "it", stack_num, stack);
2649 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2650 push_tag(os, "sl", stack_num, stack);
2658 pop_tag(os, "sl", stack_num, stack);
2659 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2660 push_tag(os, "it", stack_num, stack);
2669 if (font1.emph() != font2.emph()) {
2670 if (font2.emph() == LyXFont::ON) {
2671 push_tag(os, "em", stack_num, stack);
2674 pop_tag(os, "em", stack_num, stack);
2679 c = par->GetChar(i);
2681 if (c == LyXParagraph::META_INSET) {
2682 inset = par->GetInset(i);
2683 inset->Linuxdoc(this, os);
2686 if (font2.latex() == LyXFont::ON) {
2687 // "TeX"-Mode on == > SGML-Mode on.
2689 os << c; // see LaTeX-Generation...
2693 if (par->linuxDocConvertChar(c, sgml_string)
2694 && !style.free_spacing) { // in freespacing
2696 // non-breaking characters
2700 linux_doc_line_break(os, char_line_count, 6);
2705 linux_doc_line_break(os, char_line_count, 1);
2711 char_line_count += sgml_string.length();
2717 // needed if there is an optional argument but no contents
2718 if (main_body > 0 && main_body == par->size()) {
2722 // pop all defined Styles
2723 for (j = stack_num; j >= 0; --j) {
2724 linux_doc_line_break(os,
2726 3 + strlen(stack[j]));
2727 os << "</" << stack[j] << ">";
2730 // resets description flag correctly
2733 // <tag> not closed...
2734 linux_doc_line_break(os, char_line_count, 6);
2738 // fprintf(file, "</p>");
2744 // Print an error message.
2745 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2746 char const * message)
2748 // insert an error marker in text
2749 InsetError * new_inset = new InsetError(message);
2750 par->InsertInset(pos, new_inset);
2753 // This constant defines the maximum number of
2754 // environment layouts that can be nesteded.
2755 // The same applies for command layouts.
2756 // These values should be more than enough.
2757 // José Matos (1999/07/22)
2759 enum { MAX_NEST_LEVEL = 25};
2761 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2763 LyXParagraph * par = paragraph;
2765 niceFile = nice; // this will be used by Insetincludes.
2767 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2768 // Please use a real stack.
2769 string environment_stack[MAX_NEST_LEVEL];
2770 string environment_inner[MAX_NEST_LEVEL];
2771 // Please use a real stack.
2772 string command_stack[MAX_NEST_LEVEL];
2773 bool command_flag= false;
2774 int command_depth= 0, command_base= 0, cmd_depth= 0;
2776 string item_name, command_name;
2777 string c_depth, c_params, tmps;
2779 int depth = 0; // paragraph depth
2780 LyXTextClass const & tclass =
2781 textclasslist.TextClass(params.textclass);
2783 LaTeXFeatures features(params, tclass.numLayouts());
2787 tex_code_break_column = lyxrc.ascii_linelen;
2789 tex_code_break_column = 0;
2791 ofstream ofs(fname.c_str());
2793 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2800 string sgml_includedfiles=features.getIncludedFiles();
2802 ofs << "<!doctype " << top_element
2803 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2805 if (params.preamble.empty() && sgml_includedfiles.empty())
2808 ofs << "\n [ " << params.preamble
2809 << sgml_includedfiles << " \n]>\n\n";
2811 if(params.options.empty())
2812 sgmlOpenTag(ofs, 0, top_element);
2814 string top = top_element;
2816 top += params.options;
2817 sgmlOpenTag(ofs, 0, top);
2821 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2822 << "\n See http://www.lyx.org/ for more information -->\n";
2825 int desc_on = 0; // description mode
2826 LyXLayout const & style =
2827 textclasslist.Style(params.textclass,
2830 // environment tag closing
2831 for( ; depth > par->depth; --depth) {
2832 if(environment_inner[depth] != "!-- --") {
2833 item_name= "listitem";
2834 sgmlCloseTag(ofs, command_depth + depth,
2836 if( environment_inner[depth] == "varlistentry")
2837 sgmlCloseTag(ofs, depth+command_depth,
2838 environment_inner[depth]);
2840 sgmlCloseTag(ofs, depth + command_depth,
2841 environment_stack[depth]);
2842 environment_stack[depth].erase();
2843 environment_inner[depth].erase();
2846 if(depth == par->depth
2847 && environment_stack[depth] != style.latexname()
2848 && !environment_stack[depth].empty()) {
2849 if(environment_inner[depth] != "!-- --") {
2850 item_name= "listitem";
2851 sgmlCloseTag(ofs, command_depth+depth,
2853 if( environment_inner[depth] == "varlistentry")
2855 depth + command_depth,
2856 environment_inner[depth]);
2859 sgmlCloseTag(ofs, depth + command_depth,
2860 environment_stack[depth]);
2862 environment_stack[depth].erase();
2863 environment_inner[depth].erase();
2866 // Write opening SGML tags.
2867 switch(style.latextype) {
2868 case LATEX_PARAGRAPH:
2869 if(style.latexname() != "dummy")
2870 sgmlOpenTag(ofs, depth+command_depth,
2876 LinuxDocError(par, 0,
2877 _("Error : Wrong depth for "
2878 "LatexType Command.\n"));
2880 command_name = style.latexname();
2882 tmps = style.latexparam();
2883 c_params = split(tmps, c_depth,'|');
2885 cmd_depth= atoi(c_depth.c_str());
2888 if(cmd_depth<command_base) {
2889 for(int j = command_depth;
2890 j >= command_base; --j)
2891 if(!command_stack[j].empty())
2892 sgmlCloseTag(ofs, j, command_stack[j]);
2893 command_depth= command_base= cmd_depth;
2895 else if(cmd_depth <= command_depth) {
2896 for(int j = command_depth;
2897 j >= cmd_depth; --j)
2899 if(!command_stack[j].empty())
2900 sgmlCloseTag(ofs, j, command_stack[j]);
2901 command_depth= cmd_depth;
2904 command_depth= cmd_depth;
2907 command_depth = command_base = cmd_depth;
2908 command_flag = true;
2910 command_stack[command_depth]= command_name;
2912 // treat label as a special case for
2913 // more WYSIWYM handling.
2914 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2915 Inset * inset = par->GetInset(0);
2916 Inset::Code lyx_code = inset->LyxCode();
2917 if (lyx_code == Inset::LABEL_CODE){
2918 command_name += " id=\"";
2919 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2920 command_name += "\"";
2925 sgmlOpenTag(ofs, depth + command_depth, command_name);
2926 item_name = "title";
2927 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2930 case LATEX_ENVIRONMENT:
2931 case LATEX_ITEM_ENVIRONMENT:
2932 if (depth < par->depth) {
2934 environment_stack[depth].erase();
2937 if (environment_stack[depth] != style.latexname()) {
2938 environment_stack[depth] = style.latexname();
2939 environment_inner[depth] = "!-- --";
2940 sgmlOpenTag(ofs, depth + command_depth,
2941 environment_stack[depth]);
2943 if(environment_inner[depth] != "!-- --") {
2944 item_name= "listitem";
2946 command_depth + depth,
2948 if (environment_inner[depth] == "varlistentry")
2950 depth + command_depth,
2951 environment_inner[depth]);
2955 if(style.latextype == LATEX_ENVIRONMENT) {
2956 if(!style.latexparam().empty())
2957 sgmlOpenTag(ofs, depth + command_depth,
2958 style.latexparam());
2962 desc_on = (style.labeltype == LABEL_MANUAL);
2965 environment_inner[depth]= "varlistentry";
2967 environment_inner[depth]= "listitem";
2969 sgmlOpenTag(ofs, depth + 1 + command_depth,
2970 environment_inner[depth]);
2974 sgmlOpenTag(ofs, depth + 1 + command_depth,
2979 sgmlOpenTag(ofs, depth + 1 + command_depth,
2984 sgmlOpenTag(ofs, depth + command_depth,
2991 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
2992 depth + 1 + command_depth);
2994 DocBookHandleFootnote(ofs, par,
2995 depth + 1 + command_depth);
2997 while(par && par->IsDummy());
3000 // write closing SGML tags
3001 switch(style.latextype) {
3004 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3006 case LATEX_ENVIRONMENT:
3007 if(!style.latexparam().empty())
3008 sgmlCloseTag(ofs, depth + command_depth,
3009 style.latexparam());
3011 case LATEX_ITEM_ENVIRONMENT:
3012 if(desc_on == 1) break;
3014 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3016 case LATEX_PARAGRAPH:
3017 if(style.latexname() != "dummy")
3018 sgmlCloseTag(ofs, depth + command_depth,
3022 sgmlCloseTag(ofs, depth + command_depth,
3029 for(; depth >= 0; --depth) {
3030 if(!environment_stack[depth].empty()) {
3031 if(environment_inner[depth] != "!-- --") {
3032 item_name= "listitem";
3033 sgmlCloseTag(ofs, command_depth + depth,
3035 if( environment_inner[depth] == "varlistentry")
3036 sgmlCloseTag(ofs, depth + command_depth,
3037 environment_inner[depth]);
3040 sgmlCloseTag(ofs, depth + command_depth,
3041 environment_stack[depth]);
3045 for(int j = command_depth; j >= command_base; --j)
3046 if(!command_stack[j].empty())
3047 sgmlCloseTag(ofs, j, command_stack[j]);
3051 sgmlCloseTag(ofs, 0, top_element);
3055 // How to check for successful close
3059 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3060 LyXParagraph * par, int & desc_on,
3065 par->SimpleDocBookOneTablePar(this,
3066 os, extra, desc_on, depth);
3071 bool emph_flag = false;
3073 LyXLayout const & style = textclasslist.Style(params.textclass,
3076 LyXParagraph::size_type main_body;
3077 if (style.labeltype != LABEL_MANUAL)
3080 main_body = par->BeginningOfMainBody();
3082 // gets paragraph main font
3083 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3085 int char_line_count = depth;
3086 if(!style.free_spacing)
3087 for (int j = 0; j < depth; ++j)
3090 // parsing main loop
3091 for (LyXParagraph::size_type i = 0;
3092 i < par->size(); ++i) {
3093 LyXFont font2 = par->getFont(params, i);
3095 // handle <emphasis> tag
3096 if (font1.emph() != font2.emph() && i) {
3097 if (font2.emph() == LyXFont::ON) {
3101 os << "</emphasis>";
3106 char c = par->GetChar(i);
3108 if (c == LyXParagraph::META_INSET) {
3109 Inset * inset = par->GetInset(i);
3111 std::ostringstream ost;
3112 inset->DocBook(this, ost);
3113 string tmp_out = ost.str().c_str();
3116 inset->DocBook(this, ost);
3118 char * ctmp = ost.str();
3119 string tmp_out(ctmp);
3123 // This code needs some explanation:
3124 // Two insets are treated specially
3125 // label if it is the first element in a command paragraph
3127 // graphics inside tables or figure floats can't go on
3128 // title (the equivalente in latex for this case is caption
3129 // and title should come first
3132 if(desc_on!= 3 || i!= 0) {
3133 if(!tmp_out.empty() && tmp_out[0] == '@') {
3135 extra += frontStrip(tmp_out, '@');
3137 os << frontStrip(tmp_out, '@');
3142 } else if (font2.latex() == LyXFont::ON) {
3143 // "TeX"-Mode on ==> SGML-Mode on.
3149 if (par->linuxDocConvertChar(c, sgml_string)
3150 && !style.free_spacing) { // in freespacing
3152 // non-breaking characters
3156 os << "\n</term><listitem><para>";
3168 // needed if there is an optional argument but no contents
3169 if (main_body > 0 && main_body == par->size()) {
3173 os << "</emphasis>";
3176 // resets description flag correctly
3179 // <term> not closed...
3187 int Buffer::runLaTeX()
3189 if (!users->text) return 0;
3191 ProhibitInput(users);
3193 // get LaTeX-Filename
3194 string name = getLatexName();
3196 string path = OnlyPath(filename);
3198 string org_path = path;
3199 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3203 Path p(path); // path to LaTeX file
3204 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3206 // Remove all error insets
3207 bool a = users->removeAutoInsets();
3209 // Always generate the LaTeX file
3210 makeLaTeXFile(name, org_path, false);
3212 // do the LaTex run(s)
3214 string latex_command = lyxrc.pdf_mode ?
3215 lyxrc.pdflatex_command : lyxrc.latex_command;
3216 LaTeX latex(latex_command, name, filepath);
3217 int res = latex.run(terr,
3218 users->owner()->getMiniBuffer()); // running latex
3220 // check return value from latex.run().
3221 if ((res & LaTeX::NO_LOGFILE)) {
3222 WriteAlert(_("LaTeX did not work!"),
3223 _("Missing log file:"), name);
3224 } else if ((res & LaTeX::ERRORS)) {
3225 users->owner()->getMiniBuffer()->Set(_("Done"));
3226 // Insert all errors as errors boxes
3227 users->insertErrors(terr);
3229 // Dvi should also be kept dirty if the latex run
3230 // ends up with errors. However it should be possible
3231 // to view a dirty dvi too.
3233 //no errors or any other things to think about so:
3234 users->owner()->getMiniBuffer()->Set(_("Done"));
3237 // if we removed error insets before we ran LaTeX or if we inserted
3238 // error insets after we ran LaTeX this must be run:
3239 if (a || (res & LaTeX::ERRORS)){
3242 //users->updateScrollbar();
3246 return latex.getNumErrors();
3250 int Buffer::runLiterate()
3252 if (!users->text) return 0;
3254 ProhibitInput(users);
3256 // get LaTeX-Filename
3257 string name = getLatexName();
3258 // get Literate-Filename
3259 string lit_name = OnlyFilename(ChangeExtension (getLatexName(),
3260 lyxrc.literate_extension));
3262 string path = OnlyPath(filename);
3264 string org_path = path;
3265 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3269 Path p(path); // path to Literate file
3270 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3272 // Remove all error insets
3273 bool a = users->removeAutoInsets();
3275 // generate the Literate file if necessary
3276 makeLaTeXFile(lit_name, org_path, false);
3278 string latex_command = lyxrc.pdf_mode ?
3279 lyxrc.pdflatex_command : lyxrc.latex_command;
3280 Literate literate(latex_command, name, filepath,
3282 lyxrc.literate_command, lyxrc.literate_error_filter,
3283 lyxrc.build_command, lyxrc.build_error_filter);
3285 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3287 // check return value from literate.weave().
3288 if ((res & Literate::NO_LOGFILE)) {
3289 WriteAlert(_("Literate command did not work!"),
3290 _("Missing log file:"), name);
3291 } else if ((res & Literate::ERRORS)) {
3292 users->owner()->getMiniBuffer()->Set(_("Done"));
3293 // Insert all errors as errors boxes
3294 users->insertErrors(terr);
3296 // Dvi should also be kept dirty if the latex run
3297 // ends up with errors. However it should be possible
3298 // to view a dirty dvi too.
3300 //no errors or any other things to think about so:
3301 users->owner()->getMiniBuffer()->Set(_("Done"));
3304 // if we removed error insets before we ran LaTeX or if we inserted
3305 // error insets after we ran LaTeX this must be run:
3306 if (a || (res & Literate::ERRORS)){
3309 //users->updateScrollbar();
3313 return literate.getNumErrors();
3317 int Buffer::buildProgram()
3319 if (!users->text) return 0;
3321 ProhibitInput(users);
3323 // get LaTeX-Filename
3324 string name = getLatexName();
3325 // get Literate-Filename
3326 string lit_name = OnlyFilename(ChangeExtension(getLatexName(),
3327 lyxrc.literate_extension));
3329 string path = OnlyPath(filename);
3331 string org_path = path;
3332 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3336 Path p(path); // path to Literate file
3337 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3339 // Remove all error insets
3340 bool a = users->removeAutoInsets();
3342 // generate the LaTeX file if necessary
3343 if (!isNwClean() || a) {
3344 makeLaTeXFile(lit_name, org_path, false);
3348 string latex_command = lyxrc.pdf_mode ?
3349 lyxrc.pdflatex_command : lyxrc.latex_command;
3350 Literate literate(latex_command, name, filepath,
3352 lyxrc.literate_command, lyxrc.literate_error_filter,
3353 lyxrc.build_command, lyxrc.build_error_filter);
3355 int res = literate.build(terr, users->owner()->getMiniBuffer());
3357 // check return value from literate.build().
3358 if ((res & Literate::NO_LOGFILE)) {
3359 WriteAlert(_("Build did not work!"),
3360 _("Missing log file:"), name);
3361 } else if ((res & Literate::ERRORS)) {
3362 users->owner()->getMiniBuffer()->Set(_("Done"));
3363 // Insert all errors as errors boxes
3364 users->insertErrors(terr);
3366 // Literate files should also be kept dirty if the literate
3367 // command run ends up with errors.
3369 //no errors or any other things to think about so:
3370 users->owner()->getMiniBuffer()->Set(_("Done"));
3374 // if we removed error insets before we ran Literate/Build or
3375 // if we inserted error insets after we ran Literate/Build this
3377 if (a || (res & Literate::ERRORS)){
3380 //users->updateScrollbar();
3384 return literate.getNumErrors();
3388 // This should be enabled when the Chktex class is implemented. (Asger)
3389 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3390 // Other flags: -wall -v0 -x
3391 int Buffer::runChktex()
3393 if (!users->text) return 0;
3395 ProhibitInput(users);
3397 // get LaTeX-Filename
3398 string name = getLatexName();
3399 string path = OnlyPath(filename);
3401 string org_path = path;
3402 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3406 Path p(path); // path to LaTeX file
3407 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3409 // Remove all error insets
3410 bool removedErrorInsets = users->removeAutoInsets();
3412 // Generate the LaTeX file if neccessary
3413 makeLaTeXFile(name, org_path, false);
3416 Chktex chktex(lyxrc.chktex_command, name, filepath);
3417 int res = chktex.run(terr); // run chktex
3420 WriteAlert(_("chktex did not work!"),
3421 _("Could not run with file:"), name);
3422 } else if (res > 0) {
3423 // Insert all errors as errors boxes
3424 users->insertErrors(terr);
3427 // if we removed error insets before we ran chktex or if we inserted
3428 // error insets after we ran chktex, this must be run:
3429 if (removedErrorInsets || res){
3432 //users->updateScrollbar();
3440 void Buffer::validate(LaTeXFeatures & features) const
3442 LyXParagraph * par = paragraph;
3443 LyXTextClass const & tclass =
3444 textclasslist.TextClass(params.textclass);
3446 // AMS Style is at document level
3448 features.amsstyle = (params.use_amsmath ||
3449 tclass.provides(LyXTextClass::amsmath));
3452 // We don't use "lyxerr.debug" because of speed. (Asger)
3453 if (lyxerr.debugging(Debug::LATEX))
3454 lyxerr << "Paragraph: " << par << endl;
3456 // Now just follow the list of paragraphs and run
3457 // validate on each of them.
3458 par->validate(features);
3460 // and then the next paragraph
3464 // the bullet shapes are buffer level not paragraph level
3465 // so they are tested here
3466 for (int i = 0; i < 4; ++i) {
3467 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3468 int font = params.user_defined_bullets[i].getFont();
3471 .user_defined_bullets[i]
3478 features.latexsym = true;
3482 features.amssymb = true;
3484 else if ((font >= 2 && font <= 5)) {
3485 features.pifont = true;
3490 if (lyxerr.debugging(Debug::LATEX)) {
3491 features.showStruct();
3496 void Buffer::setPaperStuff()
3498 params.papersize = BufferParams::PAPER_DEFAULT;
3499 char c1 = params.paperpackage;
3500 if (c1 == BufferParams::PACKAGE_NONE) {
3501 char c2 = params.papersize2;
3502 if (c2 == BufferParams::VM_PAPER_USLETTER)
3503 params.papersize = BufferParams::PAPER_USLETTER;
3504 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3505 params.papersize = BufferParams::PAPER_LEGALPAPER;
3506 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3507 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3508 else if (c2 == BufferParams::VM_PAPER_A3)
3509 params.papersize = BufferParams::PAPER_A3PAPER;
3510 else if (c2 == BufferParams::VM_PAPER_A4)
3511 params.papersize = BufferParams::PAPER_A4PAPER;
3512 else if (c2 == BufferParams::VM_PAPER_A5)
3513 params.papersize = BufferParams::PAPER_A5PAPER;
3514 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3515 (c2 == BufferParams::VM_PAPER_B5))
3516 params.papersize = BufferParams::PAPER_B5PAPER;
3517 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3518 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3519 params.papersize = BufferParams::PAPER_A4PAPER;
3523 // This function should be in Buffer because it's a buffer's property (ale)
3524 string Buffer::getIncludeonlyList(char delim)
3527 for (inset_iterator it = inset_iterator_begin();
3528 it != inset_iterator_end(); ++it) {
3529 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3530 InsetInclude * insetinc =
3531 static_cast<InsetInclude *>(*it);
3532 if (insetinc->isInclude()
3533 && insetinc->isNoLoad()) {
3536 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3540 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3545 vector<string> Buffer::getLabelList()
3547 /// if this is a child document and the parent is already loaded
3548 /// Use the parent's list instead [ale990407]
3549 if (!params.parentname.empty()
3550 && bufferlist.exists(params.parentname)) {
3551 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3553 return tmp->getLabelList();
3556 vector<string> label_list;
3557 for (inset_iterator it = inset_iterator_begin();
3558 it != inset_iterator_end(); ++it) {
3559 vector<string> l = (*it)->getLabelList();
3560 label_list.insert(label_list.end(), l.begin(), l.end());
3566 vector<vector<Buffer::TocItem> > Buffer::getTocList()
3568 vector<vector<TocItem> > l(4);
3569 LyXParagraph * par = paragraph;
3571 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3572 if (textclasslist.Style(params.textclass,
3573 par->GetLayout()).labeltype
3574 == LABEL_SENSITIVE) {
3578 tmp.str = par->String(this, false);
3579 switch (par->footnotekind) {
3580 case LyXParagraph::FIG:
3581 case LyXParagraph::WIDE_FIG:
3582 l[TOC_LOF].push_back(tmp);
3584 case LyXParagraph::TAB:
3585 case LyXParagraph::WIDE_TAB:
3586 l[TOC_LOT].push_back(tmp);
3588 case LyXParagraph::ALGORITHM:
3589 l[TOC_LOA].push_back(tmp);
3591 case LyXParagraph::FOOTNOTE:
3592 case LyXParagraph::MARGIN:
3596 } else if (!par->IsDummy()) {
3597 char labeltype = textclasslist.Style(params.textclass,
3598 par->GetLayout()).labeltype;
3600 if (labeltype >= LABEL_COUNTER_CHAPTER
3601 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3602 // insert this into the table of contents
3607 textclasslist.TextClass(params.textclass).maxcounter());
3608 tmp.str = par->String(this, true);
3609 l[TOC_TOC].push_back(tmp);
3617 // This is also a buffer property (ale)
3618 vector<pair<string,string> > Buffer::getBibkeyList()
3620 /// if this is a child document and the parent is already loaded
3621 /// Use the parent's list instead [ale990412]
3622 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3623 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3625 return tmp->getBibkeyList();
3628 vector<pair<string, string> > keys;
3629 LyXParagraph * par = paragraph;
3632 keys.push_back(pair<string,string>(par->bibkey->getContents(),
3633 par->String(this, false)));
3637 // Might be either using bibtex or a child has bibliography
3639 for (inset_iterator it = inset_iterator_begin();
3640 it != inset_iterator_end(); ++it) {
3641 // Search for Bibtex or Include inset
3642 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3643 vector<pair<string,string> > tmp =
3644 static_cast<InsetBibtex*>(*it)->getKeys();
3645 keys.insert(keys.end(), tmp.begin(), tmp.end());
3646 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3647 vector<pair<string,string> > tmp =
3648 static_cast<InsetInclude*>(*it)->getKeys();
3649 keys.insert(keys.end(), tmp.begin(), tmp.end());
3658 bool Buffer::isDepClean(string const & name) const
3660 DEPCLEAN * item = dep_clean;
3661 while (item && item->master != name)
3663 if (!item) return true;
3668 void Buffer::markDepClean(string const & name)
3671 dep_clean = new DEPCLEAN;
3672 dep_clean->clean = true;
3673 dep_clean->master = name;
3674 dep_clean->next = 0;
3676 DEPCLEAN* item = dep_clean;
3677 while (item && item->master != name)
3682 item = new DEPCLEAN;
3684 item->master = name;
3691 bool Buffer::Dispatch(string const & command)
3693 // Split command string into command and argument
3694 string cmd, line = frontStrip(command);
3695 string arg = strip(frontStrip(split(line, cmd, ' ')));
3697 return Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3701 bool Buffer::Dispatch(int action, string const & argument)
3703 bool dispatched = true;
3706 MenuExport(this, argument);
3716 void Buffer::resize()
3718 /// first resize the BufferViews!
3722 /// then remove all LyXText in text-insets
3723 LyXParagraph * par = paragraph;
3724 for(;par;par = par->next) {
3725 par->deleteInsetsLyXText(users);
3730 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3733 LyXParagraph * par = paragraph;
3735 par->ChangeLanguage(params, from, to);
3741 bool Buffer::isMultiLingual()
3744 LyXParagraph * par = paragraph;
3746 if (par->isMultiLingual(params))
3754 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3755 LyXParagraph::size_type pos)
3757 it = par->InsetIterator(pos);
3758 if (it == par->inset_iterator_end()) {
3765 void Buffer::inset_iterator::SetParagraph() {
3767 it = par->inset_iterator_begin();
3768 if (it != par->inset_iterator_end())
3773 // We maintain an invariant that whenever par = 0 then it = 0