1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
23 #include <sys/types.h>
33 #pragma implementation "buffer.h"
37 #include "bufferlist.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
43 #include "tex-strings.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h"
59 #include "insets/insetcite.h"
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h"
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
92 #include "lyx_gui_misc.h" // WarnReadonly()
93 #include "frontends/Dialogs.h"
110 // all these externs should eventually be removed.
111 extern BufferList bufferlist;
113 extern LyXAction lyxaction;
116 static const float LYX_FORMAT = 2.17;
118 extern int tex_code_break_column;
121 Buffer::Buffer(string const & file, bool ronly)
123 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
125 filepath = OnlyPath(file);
134 if (read_only || (lyxrc.use_tempdir)) {
135 tmppath = CreateBufferTmpDir();
136 } else tmppath.erase();
142 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
143 // here the buffer should take care that it is
144 // saved properly, before it goes into the void.
146 // make sure that views using this buffer
151 if (!tmppath.empty()) {
152 DestroyBufferTmpDir(tmppath);
155 LyXParagraph * par = paragraph;
156 LyXParagraph * tmppar;
166 string const Buffer::getLatexName(bool no_path) const
169 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
172 return ChangeExtension(MakeLatexName(filename),
177 void Buffer::setReadonly(bool flag)
179 if (read_only != flag) {
182 users->owner()->getDialogs()->updateBufferDependent(false);
185 WarnReadonly(filename);
190 bool Buffer::saveParamsAsDefaults() // const
192 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
194 Buffer defaults = Buffer(fname);
196 // Use the current buffer's parameters as default
197 defaults.params = params;
199 // add an empty paragraph. Is this enough?
200 defaults.paragraph = new LyXParagraph;
202 return defaults.writeFile(defaults.filename, false);
206 /// Update window titles of all users
207 // Should work on a list
208 void Buffer::updateTitles() const
210 if (users) users->owner()->updateWindowTitle();
214 /// Reset autosave timer of all users
215 // Should work on a list
216 void Buffer::resetAutosaveTimers() const
218 if (users) users->owner()->resetAutosaveTimer();
222 void Buffer::setFileName(string const & newfile)
224 filename = MakeAbsPath(newfile);
225 filepath = OnlyPath(filename);
226 setReadonly(IsFileWriteable(filename) == 0);
231 // candidate for move to BufferView
232 // (at least some parts in the beginning of the func)
235 // changed to be public and have one parameter
236 // if par = 0 normal behavior
237 // else insert behavior
238 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
239 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
242 char depth = 0; // signed or unsigned?
244 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
245 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
247 bool the_end_read = false;
249 LyXParagraph * return_par = 0;
250 LyXFont font(LyXFont::ALL_INHERIT, params.language);
251 if (format < 2.16 && params.language->lang() == "hebrew")
252 font.setLanguage(default_language);
254 // If we are inserting, we cheat and get a token in advance
255 bool has_token = false;
259 par = new LyXParagraph;
261 users->text->BreakParagraph(users);
262 return_par = users->text->FirstParagraph();
265 // We don't want to adopt the parameters from the
266 // document we insert, so we skip until the text begins:
269 pretoken = lex.GetString();
270 if (pretoken == "\\layout") {
282 pretoken = lex.GetString();
285 if (pretoken.empty()) continue;
288 parseSingleLyXformat2Token(lex, par, return_par,
289 pretoken, pos, depth,
301 paragraph = return_par;
307 // We'll remove this later. (Lgb)
308 static string last_inset_read;
312 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
313 LyXParagraph *& return_par,
314 string const & token, int & pos,
315 char & depth, LyXFont & font
317 , LyXParagraph::footnote_flag & footnoteflag,
318 LyXParagraph::footnote_kind & footnotekind
322 bool the_end_read = false;
324 if (token[0] != '\\') {
325 for (string::const_iterator cit = token.begin();
326 cit != token.end(); ++cit) {
327 par->InsertChar(pos, (*cit), font);
330 } else if (token == "\\i") {
331 Inset * inset = new InsetLatexAccent;
332 inset->Read(this, lex);
333 par->InsertInset(pos, inset, font);
335 } else if (token == "\\layout") {
340 par = new LyXParagraph(par);
344 string const layoutname = lex.GetString();
345 pair<bool, LyXTextClass::LayoutList::size_type> pp
346 = textclasslist.NumberOfLayout(params.textclass,
349 par->layout = pp.second;
350 } else { // layout not found
351 // use default layout "Standard" (0)
354 // Test whether the layout is obsolete.
355 LyXLayout const & layout =
356 textclasslist.Style(params.textclass,
358 if (!layout.obsoleted_by().empty())
360 textclasslist.NumberOfLayout(params.textclass,
361 layout.obsoleted_by()).second;
363 par->footnoteflag = footnoteflag;
364 par->footnotekind = footnotekind;
367 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
368 if (format < 2.16 && params.language->lang() == "hebrew")
369 font.setLanguage(default_language);
371 } else if (token == "\\end_float") {
376 par = new LyXParagraph(par);
378 footnotekind = LyXParagraph::FOOTNOTE;
379 footnoteflag = LyXParagraph::NO_FOOTNOTE;
382 par->layout = LYX_DUMMY_LAYOUT;
383 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
384 if (format < 2.16 && params.language->lang() == "hebrew")
385 font.setLanguage(default_language);
386 } else if (token == "\\begin_float") {
387 int tmpret = lex.FindToken(string_footnotekinds);
388 if (tmpret == -1) ++tmpret;
389 if (tmpret != LYX_LAYOUT_DEFAULT)
390 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
391 if (footnotekind == LyXParagraph::FOOTNOTE
392 || footnotekind == LyXParagraph::MARGIN)
393 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
395 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
397 } else if (token == "\\begin_float") {
398 // This is the compability reader, unfinished but tested.
401 string const tmptok = lex.GetString();
402 //lyxerr << "old float: " << tmptok << endl;
407 if (tmptok == "footnote") {
408 inset = new InsetFoot;
409 } else if (tmptok == "margin") {
410 inset = new InsetMarginal;
411 } else if (tmptok == "fig") {
412 inset = new InsetFloat("figure");
413 old_float += "placement htbp\n";
414 } else if (tmptok == "tab") {
415 inset = new InsetFloat("table");
416 old_float += "placement htbp\n";
417 } else if (tmptok == "alg") {
418 inset = new InsetFloat("algorithm");
419 old_float += "placement htbp\n";
420 } else if (tmptok == "wide-fig") {
421 InsetFloat * tmp = new InsetFloat("figure");
424 old_float += "placement htbp\n";
425 } else if (tmptok == "wide-tab") {
426 InsetFloat * tmp = new InsetFloat("table");
429 old_float += "placement htbp\n";
432 if (!inset) return false; // no end read yet
434 old_float += "collapsed true\n";
436 // Here we need to check for \end_deeper and handle that
437 // before we do the footnote parsing.
438 // This _is_ a hack! (Lgb)
441 string const tmp = lex.GetString();
442 if (tmp == "\\end_deeper") {
443 lyxerr << "\\end_deeper caught!" << endl;
445 lex.printError("\\end_deeper: "
446 "depth is already null");
457 old_float += lex.getLongString("\\end_float");
458 old_float += "\n\\end_inset\n";
459 //lyxerr << "float body: " << old_float << endl;
461 istringstream istr(old_float);
464 nylex.setStream(istr);
466 inset->Read(this, nylex);
467 par->InsertInset(pos, inset, font);
470 } else if (token == "\\begin_deeper") {
472 } else if (token == "\\end_deeper") {
474 lex.printError("\\end_deeper: "
475 "depth is already null");
479 } else if (token == "\\begin_preamble") {
480 params.readPreamble(lex);
481 } else if (token == "\\textclass") {
483 pair<bool, LyXTextClassList::size_type> pp =
484 textclasslist.NumberOfClass(lex.GetString());
486 params.textclass = pp.second;
488 lex.printError("Unknown textclass `$$Token'");
489 params.textclass = 0;
491 if (!textclasslist.Load(params.textclass)) {
492 // if the textclass wasn't loaded properly
493 // we need to either substitute another
494 // or stop loading the file.
495 // I can substitute but I don't see how I can
496 // stop loading... ideas?? ARRae980418
497 WriteAlert(_("Textclass Loading Error!"),
498 string(_("Can't load textclass ")) +
499 textclasslist.NameOfClass(params.textclass),
500 _("-- substituting default"));
501 params.textclass = 0;
503 } else if (token == "\\options") {
505 params.options = lex.GetString();
506 } else if (token == "\\language") {
507 params.readLanguage(lex);
508 } else if (token == "\\fontencoding") {
510 } else if (token == "\\inputencoding") {
512 params.inputenc = lex.GetString();
513 } else if (token == "\\graphics") {
514 params.readGraphicsDriver(lex);
515 } else if (token == "\\fontscheme") {
517 params.fonts = lex.GetString();
518 } else if (token == "\\noindent") {
519 par->noindent = true;
520 } else if (token == "\\fill_top") {
521 par->added_space_top = VSpace(VSpace::VFILL);
522 } else if (token == "\\fill_bottom") {
523 par->added_space_bottom = VSpace(VSpace::VFILL);
524 } else if (token == "\\line_top") {
525 par->line_top = true;
526 } else if (token == "\\line_bottom") {
527 par->line_bottom = true;
528 } else if (token == "\\pagebreak_top") {
529 par->pagebreak_top = true;
530 } else if (token == "\\pagebreak_bottom") {
531 par->pagebreak_bottom = true;
532 } else if (token == "\\start_of_appendix") {
533 par->start_of_appendix = true;
534 } else if (token == "\\paragraph_separation") {
535 int tmpret = lex.FindToken(string_paragraph_separation);
536 if (tmpret == -1) ++tmpret;
537 if (tmpret != LYX_LAYOUT_DEFAULT)
538 params.paragraph_separation =
539 static_cast<BufferParams::PARSEP>(tmpret);
540 } else if (token == "\\defskip") {
542 params.defskip = VSpace(lex.GetString());
543 } else if (token == "\\epsfig") { // obsolete
544 // Indeed it is obsolete, but we HAVE to be backwards
545 // compatible until 0.14, because otherwise all figures
546 // in existing documents are irretrivably lost. (Asger)
547 params.readGraphicsDriver(lex);
548 } else if (token == "\\quotes_language") {
549 int tmpret = lex.FindToken(string_quotes_language);
550 if (tmpret == -1) ++tmpret;
551 if (tmpret != LYX_LAYOUT_DEFAULT) {
552 InsetQuotes::quote_language tmpl =
553 InsetQuotes::EnglishQ;
556 tmpl = InsetQuotes::EnglishQ;
559 tmpl = InsetQuotes::SwedishQ;
562 tmpl = InsetQuotes::GermanQ;
565 tmpl = InsetQuotes::PolishQ;
568 tmpl = InsetQuotes::FrenchQ;
571 tmpl = InsetQuotes::DanishQ;
574 params.quotes_language = tmpl;
576 } else if (token == "\\quotes_times") {
578 switch (lex.GetInteger()) {
580 params.quotes_times = InsetQuotes::SingleQ;
583 params.quotes_times = InsetQuotes::DoubleQ;
586 } else if (token == "\\papersize") {
587 int tmpret = lex.FindToken(string_papersize);
591 params.papersize2 = tmpret;
592 } else if (token == "\\paperpackage") {
593 int tmpret = lex.FindToken(string_paperpackages);
596 params.paperpackage = BufferParams::PACKAGE_NONE;
598 params.paperpackage = tmpret;
599 } else if (token == "\\use_geometry") {
601 params.use_geometry = lex.GetInteger();
602 } else if (token == "\\use_amsmath") {
604 params.use_amsmath = lex.GetInteger();
605 } else if (token == "\\paperorientation") {
606 int tmpret = lex.FindToken(string_orientation);
607 if (tmpret == -1) ++tmpret;
608 if (tmpret != LYX_LAYOUT_DEFAULT)
609 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
610 } else if (token == "\\paperwidth") {
612 params.paperwidth = lex.GetString();
613 } else if (token == "\\paperheight") {
615 params.paperheight = lex.GetString();
616 } else if (token == "\\leftmargin") {
618 params.leftmargin = lex.GetString();
619 } else if (token == "\\topmargin") {
621 params.topmargin = lex.GetString();
622 } else if (token == "\\rightmargin") {
624 params.rightmargin = lex.GetString();
625 } else if (token == "\\bottommargin") {
627 params.bottommargin = lex.GetString();
628 } else if (token == "\\headheight") {
630 params.headheight = lex.GetString();
631 } else if (token == "\\headsep") {
633 params.headsep = lex.GetString();
634 } else if (token == "\\footskip") {
636 params.footskip = lex.GetString();
637 } else if (token == "\\paperfontsize") {
639 params.fontsize = strip(lex.GetString());
640 } else if (token == "\\papercolumns") {
642 params.columns = lex.GetInteger();
643 } else if (token == "\\papersides") {
645 switch (lex.GetInteger()) {
647 case 1: params.sides = LyXTextClass::OneSide; break;
648 case 2: params.sides = LyXTextClass::TwoSides; break;
650 } else if (token == "\\paperpagestyle") {
652 params.pagestyle = strip(lex.GetString());
653 } else if (token == "\\bullet") {
655 int const index = lex.GetInteger();
657 int temp_int = lex.GetInteger();
658 params.user_defined_bullets[index].setFont(temp_int);
659 params.temp_bullets[index].setFont(temp_int);
661 temp_int = lex.GetInteger();
662 params.user_defined_bullets[index].setCharacter(temp_int);
663 params.temp_bullets[index].setCharacter(temp_int);
665 temp_int = lex.GetInteger();
666 params.user_defined_bullets[index].setSize(temp_int);
667 params.temp_bullets[index].setSize(temp_int);
669 string const temp_str = lex.GetString();
670 if (temp_str != "\\end_bullet") {
671 // this element isn't really necessary for
672 // parsing but is easier for humans
673 // to understand bullets. Put it back and
674 // set a debug message?
675 lex.printError("\\end_bullet expected, got" + temp_str);
676 //how can I put it back?
678 } else if (token == "\\bulletLaTeX") {
680 int const index = lex.GetInteger();
682 string temp_str = lex.GetString();
684 while (temp_str != "\\end_bullet") {
685 // this loop structure is needed when user
686 // enters an empty string since the first
687 // thing returned will be the \\end_bullet
689 // if the LaTeX entry has spaces. Each element
690 // therefore needs to be read in turn
693 temp_str = lex.GetString();
695 params.user_defined_bullets[index].setText(sum_str);
696 params.temp_bullets[index].setText(sum_str);
697 } else if (token == "\\secnumdepth") {
699 params.secnumdepth = lex.GetInteger();
700 } else if (token == "\\tocdepth") {
702 params.tocdepth = lex.GetInteger();
703 } else if (token == "\\spacing") {
705 string const tmp = strip(lex.GetString());
706 Spacing::Space tmp_space = Spacing::Default;
708 if (tmp == "single") {
709 tmp_space = Spacing::Single;
710 } else if (tmp == "onehalf") {
711 tmp_space = Spacing::Onehalf;
712 } else if (tmp == "double") {
713 tmp_space = Spacing::Double;
714 } else if (tmp == "other") {
716 tmp_space = Spacing::Other;
717 tmp_val = lex.GetFloat();
719 lex.printError("Unknown spacing token: '$$Token'");
721 // Small hack so that files written with klyx will be
724 par->spacing.set(tmp_space, tmp_val);
726 params.spacing.set(tmp_space, tmp_val);
728 } else if (token == "\\paragraph_spacing") {
730 string const tmp = strip(lex.GetString());
731 if (tmp == "single") {
732 par->spacing.set(Spacing::Single);
733 } else if (tmp == "onehalf") {
734 par->spacing.set(Spacing::Onehalf);
735 } else if (tmp == "double") {
736 par->spacing.set(Spacing::Double);
737 } else if (tmp == "other") {
739 par->spacing.set(Spacing::Other,
742 lex.printError("Unknown spacing token: '$$Token'");
744 } else if (token == "\\float_placement") {
746 params.float_placement = lex.GetString();
747 } else if (token == "\\family") {
749 font.setLyXFamily(lex.GetString());
750 } else if (token == "\\series") {
752 font.setLyXSeries(lex.GetString());
753 } else if (token == "\\shape") {
755 font.setLyXShape(lex.GetString());
756 } else if (token == "\\size") {
758 font.setLyXSize(lex.GetString());
759 } else if (token == "\\latex") {
761 string const tok = lex.GetString();
762 // This is dirty, but gone with LyX3. (Asger)
763 if (tok == "no_latex")
764 font.setLatex(LyXFont::OFF);
765 else if (tok == "latex")
766 font.setLatex(LyXFont::ON);
767 else if (tok == "default")
768 font.setLatex(LyXFont::INHERIT);
770 lex.printError("Unknown LaTeX font flag "
772 } else if (token == "\\lang") {
774 string const tok = lex.GetString();
775 Language const * lang = languages.getLanguage(tok);
777 font.setLanguage(lang);
779 font.setLanguage(params.language);
780 lex.printError("Unknown language `$$Token'");
782 } else if (token == "\\numeric") {
784 font.setNumber(font.setLyXMisc(lex.GetString()));
785 } else if (token == "\\emph") {
787 font.setEmph(font.setLyXMisc(lex.GetString()));
788 } else if (token == "\\bar") {
790 string const tok = lex.GetString();
791 // This is dirty, but gone with LyX3. (Asger)
793 font.setUnderbar(LyXFont::ON);
794 else if (tok == "no")
795 font.setUnderbar(LyXFont::OFF);
796 else if (tok == "default")
797 font.setUnderbar(LyXFont::INHERIT);
799 lex.printError("Unknown bar font flag "
801 } else if (token == "\\noun") {
803 font.setNoun(font.setLyXMisc(lex.GetString()));
804 } else if (token == "\\color") {
806 font.setLyXColor(lex.GetString());
807 } else if (token == "\\align") {
808 int tmpret = lex.FindToken(string_align);
809 if (tmpret == -1) ++tmpret;
810 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
813 for (; tmpret > 0; --tmpret)
814 tmpret2 = tmpret2 * 2;
816 int const tmpret2 = int(pow(2.0, tmpret));
818 lyxerr << "Tmpret2 = " << tmpret2 << endl;
819 par->align = LyXAlignment(tmpret2);
821 } else if (token == "\\added_space_top") {
823 par->added_space_top = VSpace(lex.GetString());
824 } else if (token == "\\added_space_bottom") {
826 par->added_space_bottom = VSpace(lex.GetString());
827 } else if (token == "\\pextra_type") {
829 par->pextra_type = lex.GetInteger();
830 } else if (token == "\\pextra_width") {
832 par->pextra_width = lex.GetString();
833 } else if (token == "\\pextra_widthp") {
835 par->pextra_widthp = lex.GetString();
836 } else if (token == "\\pextra_alignment") {
838 par->pextra_alignment = lex.GetInteger();
839 } else if (token == "\\pextra_hfill") {
841 par->pextra_hfill = lex.GetInteger();
842 } else if (token == "\\pextra_start_minipage") {
844 par->pextra_start_minipage = lex.GetInteger();
845 } else if (token == "\\labelwidthstring") {
847 par->labelwidthstring = lex.GetString();
848 // do not delete this token, it is still needed!
849 } else if (token == "\\end_inset") {
850 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
851 << "Last inset read was: " << last_inset_read
853 // Simply ignore this. The insets do not have
855 // But insets should read it, it is a part of
856 // the inset isn't it? Lgb.
857 } else if (token == "\\begin_inset") {
858 readInset(lex, par, pos, font);
859 } else if (token == "\\SpecialChar") {
860 LyXLayout const & layout =
861 textclasslist.Style(params.textclass,
864 // Insets don't make sense in a free-spacing context! ---Kayvan
865 if (layout.free_spacing) {
868 string next_token = lex.GetString();
869 if (next_token == "\\-") {
870 par->InsertChar(pos, '-', font);
871 } else if (next_token == "\\protected_separator"
872 || next_token == "~") {
873 par->InsertChar(pos, ' ', font);
875 lex.printError("Token `$$Token' "
877 "paragraph layout!");
882 Inset * inset = new InsetSpecialChar;
883 inset->Read(this, lex);
884 par->InsertInset(pos, inset, font);
887 } else if (token == "\\newline") {
888 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
890 } else if (token == "\\LyXTable") {
891 Inset * inset = new InsetTabular(*this);
892 inset->Read(this, lex);
893 par->InsertInset(pos, inset, font);
895 } else if (token == "\\hfill") {
896 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
898 } else if (token == "\\protected_separator") { // obsolete
899 // This is a backward compability thingie. (Lgb)
900 // Remove it later some time...introduced with fileformat
902 LyXLayout const & layout =
903 textclasslist.Style(params.textclass,
906 if (layout.free_spacing) {
907 par->InsertChar(pos, ' ', font);
909 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
910 par->InsertInset(pos, inset, font);
913 } else if (token == "\\bibitem") { // ale970302
915 InsetCommandParams p( "bibitem" );
916 par->bibkey = new InsetBibKey(p);
918 par->bibkey->Read(this, lex);
919 } else if (token == "\\backslash") {
920 par->InsertChar(pos, '\\', font);
922 } else if (token == "\\the_end") {
925 // This should be insurance for the future: (Asger)
926 lex.printError("Unknown token `$$Token'. "
927 "Inserting as text.");
928 string::const_iterator cit = token.begin();
929 string::const_iterator end = token.end();
930 for (; cit != end; ++cit) {
931 par->InsertChar(pos, (*cit), font);
939 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
940 int & pos, LyXFont & font)
943 if (lex.GetString() != "\\begin_inset") {
944 lyxerr << "Buffer::readInset: Consistency check failed."
951 string const tmptok = lex.GetString();
952 last_inset_read = tmptok;
954 // test the different insets
955 if (tmptok == "LatexCommand") {
956 InsetCommandParams inscmd;
959 if (inscmd.getCmdName() == "cite") {
960 inset = new InsetCitation(inscmd);
961 } else if (inscmd.getCmdName() == "bibitem") {
962 lex.printError("Wrong place for bibitem");
963 inset = new InsetBibKey(inscmd);
964 } else if (inscmd.getCmdName() == "BibTeX") {
965 inset = new InsetBibtex(inscmd);
966 } else if (inscmd.getCmdName() == "index") {
967 inset = new InsetIndex(inscmd);
968 } else if (inscmd.getCmdName() == "include") {
969 inset = new InsetInclude(inscmd, *this);
970 } else if (inscmd.getCmdName() == "label") {
971 inset = new InsetLabel(inscmd);
972 } else if (inscmd.getCmdName() == "url"
973 || inscmd.getCmdName() == "htmlurl") {
974 inset = new InsetUrl(inscmd);
975 } else if (inscmd.getCmdName() == "ref"
976 || inscmd.getCmdName() == "pageref"
977 || inscmd.getCmdName() == "vref"
978 || inscmd.getCmdName() == "vpageref"
979 || inscmd.getCmdName() == "prettyref") {
980 if (!inscmd.getOptions().empty()
981 || !inscmd.getContents().empty()) {
982 inset = new InsetRef(inscmd, *this);
984 } else if (inscmd.getCmdName() == "tableofcontents"
985 || inscmd.getCmdName() == "listofalgorithms"
986 || inscmd.getCmdName() == "listoffigures"
987 || inscmd.getCmdName() == "listoftables") {
988 inset = new InsetTOC(inscmd);
989 } else if (inscmd.getCmdName() == "printindex") {
990 inset = new InsetPrintIndex(inscmd);
991 } else if (inscmd.getCmdName() == "lyxparent") {
992 inset = new InsetParent(inscmd, *this);
995 if (tmptok == "Quotes") {
996 inset = new InsetQuotes;
997 } else if (tmptok == "External") {
998 inset = new InsetExternal;
999 } else if (tmptok == "FormulaMacro") {
1000 inset = new InsetFormulaMacro;
1001 } else if (tmptok == "Formula") {
1002 inset = new InsetFormula;
1003 } else if (tmptok == "Figure") {
1004 inset = new InsetFig(100, 100, *this);
1005 } else if (tmptok == "Info") {
1006 inset = new InsetInfo;
1007 } else if (tmptok == "Include") {
1008 InsetCommandParams p( "Include" );
1009 inset = new InsetInclude(p, *this);
1010 } else if (tmptok == "ERT") {
1011 inset = new InsetERT;
1012 } else if (tmptok == "Tabular") {
1013 inset = new InsetTabular(*this);
1014 } else if (tmptok == "Text") {
1015 inset = new InsetText;
1016 } else if (tmptok == "Foot") {
1017 inset = new InsetFoot;
1018 } else if (tmptok == "Marginal") {
1019 inset = new InsetMarginal;
1020 } else if (tmptok == "Minipage") {
1021 inset = new InsetMinipage;
1022 } else if (tmptok == "Float") {
1024 string tmptok = lex.GetString();
1025 inset = new InsetFloat(tmptok);
1026 } else if (tmptok == "List") {
1027 inset = new InsetList;
1028 } else if (tmptok == "Theorem") {
1029 inset = new InsetList;
1030 } else if (tmptok == "Caption") {
1031 inset = new InsetCaption;
1032 } else if (tmptok == "GRAPHICS") {
1033 inset = new InsetGraphics;
1036 if (inset) inset->Read(this, lex);
1040 par->InsertInset(pos, inset, font);
1046 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1050 string const token(lex.GetString());
1051 if (token == "\\lyxformat") { // the first token _must_ be...
1053 format = lex.GetFloat();
1055 if (LYX_FORMAT - format > 0.05) {
1056 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1057 LYX_FORMAT, format) << endl;
1059 if (format - LYX_FORMAT > 0.05) {
1060 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1061 LYX_FORMAT, format) << endl;
1063 bool the_end = readLyXformat2(lex, par);
1064 // Formats >= 2.13 support "\the_end" marker
1071 WriteAlert(_("Warning!"),
1072 _("Reading of document is not complete"),
1073 _("Maybe the document is truncated"));
1074 // We simulate a safe reading anyways to allow
1075 // users to take the chance... (Asger)
1079 WriteAlert(_("ERROR!"),
1080 _("Old LyX file format found. "
1081 "Use LyX 0.10.x to read this!"));
1085 } else { // "\\lyxformat" not found
1086 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1089 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1095 // Should probably be moved to somewhere else: BufferView? LyXView?
1096 bool Buffer::save() const
1098 // We don't need autosaves in the immediate future. (Asger)
1099 resetAutosaveTimers();
1103 if (lyxrc.make_backup) {
1104 s = fileName() + '~';
1105 if (!lyxrc.backupdir_path.empty())
1106 s = AddName(lyxrc.backupdir_path,
1107 subst(CleanupPath(s),'/','!'));
1109 // Rename is the wrong way of making a backup,
1110 // this is the correct way.
1111 /* truss cp fil fil2:
1112 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1113 stat("LyXVC.lyx", 0xEFFFF688) = 0
1114 open("LyXVC.lyx", O_RDONLY) = 3
1115 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1116 fstat(4, 0xEFFFF508) = 0
1117 fstat(3, 0xEFFFF508) = 0
1118 read(3, " # T h i s f i l e w".., 8192) = 5579
1119 write(4, " # T h i s f i l e w".., 5579) = 5579
1120 read(3, 0xEFFFD4A0, 8192) = 0
1123 chmod("LyXVC3.lyx", 0100644) = 0
1124 lseek(0, 0, SEEK_CUR) = 46440
1128 // Should proabaly have some more error checking here.
1129 // Should be cleaned up in 0.13, at least a bit.
1130 // Doing it this way, also makes the inodes stay the same.
1131 // This is still not a very good solution, in particular we
1132 // might loose the owner of the backup.
1133 FileInfo finfo(fileName());
1134 if (finfo.exist()) {
1135 mode_t fmode = finfo.getMode();
1136 struct utimbuf times = {
1137 finfo.getAccessTime(),
1138 finfo.getModificationTime() };
1140 ifstream ifs(fileName().c_str());
1141 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1146 ::chmod(s.c_str(), fmode);
1148 if (::utime(s.c_str(), ×)) {
1149 lyxerr << "utime error." << endl;
1152 lyxerr << "LyX was not able to make "
1153 "backupcopy. Beware." << endl;
1158 if (writeFile(fileName(), false)) {
1160 removeAutosaveFile(fileName());
1162 // Saving failed, so backup is not backup
1163 if (lyxrc.make_backup) {
1164 lyx::rename(s, fileName());
1172 // Returns false if unsuccesful
1173 bool Buffer::writeFile(string const & fname, bool flag) const
1175 // if flag is false writeFile will not create any GUI
1176 // warnings, only cerr.
1177 // Needed for autosave in background or panic save (Matthias 120496)
1179 if (read_only && (fname == filename)) {
1180 // Here we should come with a question if we should
1181 // perform the write anyway.
1183 lyxerr << _("Error! Document is read-only: ")
1186 WriteAlert(_("Error! Document is read-only: "),
1191 FileInfo finfo(fname);
1192 if (finfo.exist() && !finfo.writable()) {
1193 // Here we should come with a question if we should
1194 // try to do the save anyway. (i.e. do a chmod first)
1196 lyxerr << _("Error! Cannot write file: ")
1199 WriteFSAlert(_("Error! Cannot write file: "),
1204 ofstream ofs(fname.c_str());
1207 lyxerr << _("Error! Cannot open file: ")
1210 WriteFSAlert(_("Error! Cannot open file: "),
1216 // Use the standard "C" locale for file output.
1217 ofs.imbue(std::locale::classic());
1220 // The top of the file should not be written by params.
1222 // write out a comment in the top of the file
1223 ofs << '#' << LYX_DOCVERSION
1224 << " created this file. For more info see http://www.lyx.org/\n";
1225 ofs.setf(ios::showpoint|ios::fixed);
1228 char dummy_format[512];
1229 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1230 ofs << "\\lyxformat " << dummy_format << "\n";
1232 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1234 // now write out the buffer paramters.
1235 params.writeFile(ofs);
1237 char footnoteflag = 0;
1240 // this will write out all the paragraphs
1241 // using recursive descent.
1242 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1244 // Write marker that shows file is complete
1245 ofs << "\n\\the_end" << endl;
1249 // how to check if close went ok?
1250 // Following is an attempt... (BE 20001011)
1252 // good() returns false if any error occured, including some
1253 // formatting error.
1254 // bad() returns true if something bad happened in the buffer,
1255 // which should include file system full errors.
1262 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1264 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1274 string const Buffer::asciiParagraph(LyXParagraph const * par,
1275 unsigned int linelen) const
1277 ostringstream buffer;
1280 Inset const * inset;
1282 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1285 int ltype_depth = 0;
1286 unsigned int currlinelen = 0;
1287 bool ref_printed = false;
1293 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1297 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1301 /* begins a footnote environment ? */
1302 if (footnoteflag != par->footnoteflag) {
1303 footnoteflag = par->footnoteflag;
1305 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1306 if ((linelen > 0) &&
1307 ((currlinelen + j) > linelen)) {
1312 << string_footnotekinds[par->footnotekind]
1318 /* begins or ends a deeper area ?*/
1319 if (depth != par->depth) {
1320 if (par->depth > depth) {
1321 while (par->depth > depth) {
1326 while (par->depth < depth) {
1332 /* First write the layout */
1333 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1334 if (tmp == "Itemize") {
1336 ltype_depth = depth+1;
1337 } else if (tmp == "Enumerate") {
1339 ltype_depth = depth+1;
1340 } else if (strstr(tmp.c_str(), "ection")) {
1342 ltype_depth = depth+1;
1343 } else if (strstr(tmp.c_str(), "aragraph")) {
1345 ltype_depth = depth+1;
1346 } else if (tmp == "Description") {
1348 ltype_depth = depth+1;
1349 } else if (tmp == "Abstract") {
1352 } else if (tmp == "Bibliography") {
1360 /* maybe some vertical spaces */
1362 /* the labelwidthstring used in lists */
1366 /* some pagebreaks? */
1370 /* what about the alignment */
1373 /* dummy layout, that means a footnote ended */
1374 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1378 lyxerr << "Should this ever happen?" << endl;
1382 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1383 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1384 if (!i && !footnoteflag && !noparbreak){
1387 for (char j = 0; j < depth; ++j)
1389 currlinelen = depth * 2;
1391 case 0: /* Standard */
1392 case 4: /* (Sub)Paragraph */
1393 case 5: /* Description */
1395 case 6: /* Abstract */
1397 buffer << "Abstract\n\n";
1399 buffer << "Abstract: ";
1401 case 7: /* Bibliography */
1404 buffer << "References\n\n";
1406 buffer << "References: ";
1411 buffer << par->labelstring << " ";
1414 if (ltype_depth > depth) {
1415 for (char j = ltype_depth - 1; j > depth; --j)
1417 currlinelen += (ltype_depth-depth)*2;
1420 font2 = par->GetFontSettings(params, i);
1421 if (font1.latex() != font2.latex()) {
1422 if (font2.latex() == LyXFont::OFF)
1429 c = par->GetChar(i);
1433 case LyXParagraph::META_INSET:
1434 if ((inset = par->GetInset(i))) {
1435 if (!inset->Ascii(this, buffer)) {
1437 string s = rsplit(buffer.str().c_str(),
1439 currlinelen += s.length();
1441 // to be sure it breaks paragraph
1442 currlinelen += linelen;
1446 case LyXParagraph::META_NEWLINE:
1449 for (char j = 0; j < depth; ++j)
1452 currlinelen = depth * 2;
1453 if (ltype_depth > depth) {
1454 for (char j = ltype_depth;
1457 currlinelen += (ltype_depth - depth) * 2;
1460 case LyXParagraph::META_HFILL:
1467 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1468 (c == ' ') && ((i + 2) < par->size()))
1471 for (char j = 0; j < depth; ++j)
1473 currlinelen = depth * 2;
1474 if (ltype_depth > depth) {
1475 for (char j = ltype_depth;
1478 currlinelen += (ltype_depth-depth)*2;
1480 } else if (c != '\0')
1483 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1488 return buffer.str().c_str();
1492 void Buffer::writeFileAscii(string const & fname, int linelen)
1494 ofstream ofs(fname.c_str());
1496 WriteFSAlert(_("Error: Cannot write file:"), fname);
1499 writeFileAscii(ofs, linelen);
1503 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1505 LyXParagraph * par = paragraph;
1507 ofs << asciiParagraph(par, linelen);
1514 void Buffer::makeLaTeXFile(string const & fname,
1515 string const & original_path,
1516 bool nice, bool only_body)
1518 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1520 niceFile = nice; // this will be used by Insetincludes.
1522 tex_code_break_column = lyxrc.ascii_linelen;
1524 LyXTextClass const & tclass =
1525 textclasslist.TextClass(params.textclass);
1527 ofstream ofs(fname.c_str());
1529 WriteFSAlert(_("Error: Cannot open file: "), fname);
1533 // validate the buffer.
1534 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1535 LaTeXFeatures features(params, tclass.numLayouts());
1537 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1540 // The starting paragraph of the coming rows is the
1541 // first paragraph of the document. (Asger)
1542 texrow.start(paragraph, 0);
1544 if (!only_body && nice) {
1545 ofs << "%% " LYX_DOCVERSION " created this file. "
1546 "For more info, see http://www.lyx.org/.\n"
1547 "%% Do not edit unless you really know what "
1552 lyxerr.debug() << "lyx header finished" << endl;
1553 // There are a few differences between nice LaTeX and usual files:
1554 // usual is \batchmode and has a
1555 // special input@path to allow the including of figures
1556 // with either \input or \includegraphics (what figinsets do).
1557 // batchmode is not set if there is a tex_code_break_column.
1558 // In this case somebody is interested in the generated LaTeX,
1559 // so this is OK. input@path is set when the actual parameter
1560 // original_path is set. This is done for usual tex-file, but not
1561 // for nice-latex-file. (Matthias 250696)
1564 // code for usual, NOT nice-latex-file
1565 ofs << "\\batchmode\n"; // changed
1566 // from \nonstopmode
1569 if (!original_path.empty()) {
1570 ofs << "\\makeatletter\n"
1571 << "\\def\\input@path{{"
1572 << original_path << "/}}\n"
1573 << "\\makeatother\n";
1579 ofs << "\\documentclass";
1581 string options; // the document class options.
1583 if (tokenPos(tclass.opt_fontsize(),
1584 '|', params.fontsize) >= 0) {
1585 // only write if existing in list (and not default)
1586 options += params.fontsize;
1591 if (!params.use_geometry &&
1592 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1593 switch (params.papersize) {
1594 case BufferParams::PAPER_A4PAPER:
1595 options += "a4paper,";
1597 case BufferParams::PAPER_USLETTER:
1598 options += "letterpaper,";
1600 case BufferParams::PAPER_A5PAPER:
1601 options += "a5paper,";
1603 case BufferParams::PAPER_B5PAPER:
1604 options += "b5paper,";
1606 case BufferParams::PAPER_EXECUTIVEPAPER:
1607 options += "executivepaper,";
1609 case BufferParams::PAPER_LEGALPAPER:
1610 options += "legalpaper,";
1616 if (params.sides != tclass.sides()) {
1617 switch (params.sides) {
1618 case LyXTextClass::OneSide:
1619 options += "oneside,";
1621 case LyXTextClass::TwoSides:
1622 options += "twoside,";
1629 if (params.columns != tclass.columns()) {
1630 if (params.columns == 2)
1631 options += "twocolumn,";
1633 options += "onecolumn,";
1636 if (!params.use_geometry
1637 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1638 options += "landscape,";
1640 // language should be a parameter to \documentclass
1641 bool use_babel = false;
1642 if (params.language->babel() == "hebrew") // This seems necessary
1643 features.UsedLanguages.insert(default_language);
1644 #ifdef DO_USE_DEFAULT_LANGUAGE
1645 if (params.language->lang() != "default" ||
1646 !features.UsedLanguages.empty()) {
1649 for (LaTeXFeatures::LanguageList::const_iterator cit =
1650 features.UsedLanguages.begin();
1651 cit != features.UsedLanguages.end(); ++cit)
1652 options += (*cit)->babel() + ",";
1653 options += params.language->babel() + ',';
1654 #ifdef DO_USE_DEFAULT_LANGUAGE
1658 // the user-defined options
1659 if (!params.options.empty()) {
1660 options += params.options + ',';
1663 if (!options.empty()){
1664 options = strip(options, ',');
1665 ofs << '[' << options << ']';
1669 << textclasslist.LatexnameOfClass(params.textclass)
1672 // end of \documentclass defs
1674 // font selection must be done before loading fontenc.sty
1675 if (params.fonts != "default") {
1676 ofs << "\\usepackage{" << params.fonts << "}\n";
1679 // this one is not per buffer
1680 if (lyxrc.fontenc != "default") {
1681 ofs << "\\usepackage[" << lyxrc.fontenc
1686 if (params.inputenc == "auto") {
1687 string const doc_encoding =
1688 params.language->encoding()->LatexName();
1690 // Create a list with all the input encodings used
1692 set<string> encodings;
1693 for (LaTeXFeatures::LanguageList::const_iterator it =
1694 features.UsedLanguages.begin();
1695 it != features.UsedLanguages.end(); ++it)
1696 if ((*it)->encoding()->LatexName() != doc_encoding)
1697 encodings.insert((*it)->encoding()->LatexName());
1699 ofs << "\\usepackage[";
1700 std::copy(encodings.begin(), encodings.end(),
1701 std::ostream_iterator<string>(ofs, ","));
1702 ofs << doc_encoding << "]{inputenc}\n";
1704 } else if (params.inputenc != "default") {
1705 ofs << "\\usepackage[" << params.inputenc
1710 // At the very beginning the text parameters.
1711 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1712 switch (params.paperpackage) {
1713 case BufferParams::PACKAGE_A4:
1714 ofs << "\\usepackage{a4}\n";
1717 case BufferParams::PACKAGE_A4WIDE:
1718 ofs << "\\usepackage{a4wide}\n";
1721 case BufferParams::PACKAGE_WIDEMARGINSA4:
1722 ofs << "\\usepackage[widemargins]{a4}\n";
1727 if (params.use_geometry) {
1728 ofs << "\\usepackage{geometry}\n";
1730 ofs << "\\geometry{verbose";
1731 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1732 ofs << ",landscape";
1733 switch (params.papersize2) {
1734 case BufferParams::VM_PAPER_CUSTOM:
1735 if (!params.paperwidth.empty())
1736 ofs << ",paperwidth="
1737 << params.paperwidth;
1738 if (!params.paperheight.empty())
1739 ofs << ",paperheight="
1740 << params.paperheight;
1742 case BufferParams::VM_PAPER_USLETTER:
1743 ofs << ",letterpaper";
1745 case BufferParams::VM_PAPER_USLEGAL:
1746 ofs << ",legalpaper";
1748 case BufferParams::VM_PAPER_USEXECUTIVE:
1749 ofs << ",executivepaper";
1751 case BufferParams::VM_PAPER_A3:
1754 case BufferParams::VM_PAPER_A4:
1757 case BufferParams::VM_PAPER_A5:
1760 case BufferParams::VM_PAPER_B3:
1763 case BufferParams::VM_PAPER_B4:
1766 case BufferParams::VM_PAPER_B5:
1770 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1771 switch (lyxrc.default_papersize) {
1772 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1773 case BufferParams::PAPER_USLETTER:
1774 ofs << ",letterpaper";
1776 case BufferParams::PAPER_LEGALPAPER:
1777 ofs << ",legalpaper";
1779 case BufferParams::PAPER_EXECUTIVEPAPER:
1780 ofs << ",executivepaper";
1782 case BufferParams::PAPER_A3PAPER:
1785 case BufferParams::PAPER_A4PAPER:
1788 case BufferParams::PAPER_A5PAPER:
1791 case BufferParams::PAPER_B5PAPER:
1796 if (!params.topmargin.empty())
1797 ofs << ",tmargin=" << params.topmargin;
1798 if (!params.bottommargin.empty())
1799 ofs << ",bmargin=" << params.bottommargin;
1800 if (!params.leftmargin.empty())
1801 ofs << ",lmargin=" << params.leftmargin;
1802 if (!params.rightmargin.empty())
1803 ofs << ",rmargin=" << params.rightmargin;
1804 if (!params.headheight.empty())
1805 ofs << ",headheight=" << params.headheight;
1806 if (!params.headsep.empty())
1807 ofs << ",headsep=" << params.headsep;
1808 if (!params.footskip.empty())
1809 ofs << ",footskip=" << params.footskip;
1813 if (params.use_amsmath
1814 && !tclass.provides(LyXTextClass::amsmath)) {
1815 ofs << "\\usepackage{amsmath}\n";
1819 if (tokenPos(tclass.opt_pagestyle(),
1820 '|', params.pagestyle) >= 0) {
1821 if (params.pagestyle == "fancy") {
1822 ofs << "\\usepackage{fancyhdr}\n";
1825 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1829 // We try to load babel late, in case it interferes
1830 // with other packages.
1832 ofs << lyxrc.language_package << endl;
1836 if (params.secnumdepth != tclass.secnumdepth()) {
1837 ofs << "\\setcounter{secnumdepth}{"
1838 << params.secnumdepth
1842 if (params.tocdepth != tclass.tocdepth()) {
1843 ofs << "\\setcounter{tocdepth}{"
1849 if (params.paragraph_separation) {
1850 switch (params.defskip.kind()) {
1851 case VSpace::SMALLSKIP:
1852 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1854 case VSpace::MEDSKIP:
1855 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1857 case VSpace::BIGSKIP:
1858 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1860 case VSpace::LENGTH:
1861 ofs << "\\setlength\\parskip{"
1862 << params.defskip.length().asLatexString()
1865 default: // should never happen // Then delete it.
1866 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1871 ofs << "\\setlength\\parindent{0pt}\n";
1875 // Now insert the LyX specific LaTeX commands...
1877 // The optional packages;
1878 string preamble(features.getPackages());
1880 // this might be useful...
1881 preamble += "\n\\makeatletter\n";
1883 // Some macros LyX will need
1884 string tmppreamble(features.getMacros());
1886 if (!tmppreamble.empty()) {
1887 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1888 "LyX specific LaTeX commands.\n"
1889 + tmppreamble + '\n';
1892 // the text class specific preamble
1893 tmppreamble = features.getTClassPreamble();
1894 if (!tmppreamble.empty()) {
1895 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1896 "Textclass specific LaTeX commands.\n"
1897 + tmppreamble + '\n';
1900 /* the user-defined preamble */
1901 if (!params.preamble.empty()) {
1902 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1903 "User specified LaTeX commands.\n"
1904 + params.preamble + '\n';
1907 preamble += "\\makeatother\n";
1909 // Itemize bullet settings need to be last in case the user
1910 // defines their own bullets that use a package included
1911 // in the user-defined preamble -- ARRae
1912 // Actually it has to be done much later than that
1913 // since some packages like frenchb make modifications
1914 // at \begin{document} time -- JMarc
1916 for (int i = 0; i < 4; ++i) {
1917 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1918 if (bullets_def.empty())
1919 bullets_def="\\AtBeginDocument{\n";
1920 bullets_def += " \\renewcommand{\\labelitemi";
1922 // `i' is one less than the item to modify
1929 bullets_def += "ii";
1935 bullets_def += "}{" +
1936 params.user_defined_bullets[i].getText()
1941 if (!bullets_def.empty())
1942 preamble += bullets_def + "}\n\n";
1944 for (int j = countChar(preamble, '\n'); j-- ;) {
1951 ofs << "\\begin{document}\n";
1954 lyxerr.debug() << "preamble finished, now the body." << endl;
1955 #ifdef DO_USE_DEFAULT_LANGUAGE
1956 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
1958 if (!lyxrc.language_auto_begin) {
1960 ofs << subst(lyxrc.language_command_begin, "$$lang",
1961 params.language->babel())
1966 latexParagraphs(ofs, paragraph, 0, texrow);
1968 // add this just in case after all the paragraphs
1972 #ifdef DO_USE_DEFAULT_LANGUAGE
1973 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
1975 if (!lyxrc.language_auto_end) {
1977 ofs << subst(lyxrc.language_command_end, "$$lang",
1978 params.language->babel())
1984 ofs << "\\end{document}\n";
1987 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1989 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1993 // Just to be sure. (Asger)
1996 // tex_code_break_column's value is used to decide
1997 // if we are in batchmode or not (within mathed_write()
1998 // in math_write.C) so we must set it to a non-zero
1999 // value when we leave otherwise we save incorrect .lyx files.
2000 tex_code_break_column = lyxrc.ascii_linelen;
2004 lyxerr << "File was not closed properly." << endl;
2007 lyxerr.debug() << "Finished making latex file." << endl;
2012 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2014 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2015 LyXParagraph * endpar, TexRow & texrow) const
2017 bool was_title = false;
2018 bool already_title = false;
2019 std::ostringstream ftnote;
2024 while (par != endpar) {
2027 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2030 LyXLayout const & layout =
2031 textclasslist.Style(params.textclass,
2034 if (layout.intitle) {
2035 if (already_title) {
2036 lyxerr <<"Error in latexParagraphs: You"
2037 " should not mix title layouts"
2038 " with normal ones." << endl;
2041 } else if (was_title && !already_title) {
2042 ofs << "\\maketitle\n";
2044 already_title = true;
2047 // We are at depth 0 so we can just use
2048 // ordinary \footnote{} generation
2049 // flag this with ftcount
2051 if (layout.isEnvironment()
2052 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2053 par = par->TeXEnvironment(this, params, ofs, texrow
2055 ,ftnote, ft_texrow, ftcount
2059 par = par->TeXOnePar(this, params, ofs, texrow, false
2062 ftnote, ft_texrow, ftcount
2067 // Write out what we've generated...
2070 ofs << "\\addtocounter{footnote}{-"
2074 ofs << ftnote.str();
2075 texrow += ft_texrow;
2077 // The extra .c_str() is needed when we use
2078 // lyxstring instead of the STL string class.
2079 ftnote.str(string().c_str());
2084 // It might be that we only have a title in this document
2085 if (was_title && !already_title) {
2086 ofs << "\\maketitle\n";
2092 bool Buffer::isLatex() const
2094 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2098 bool Buffer::isLinuxDoc() const
2100 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2104 bool Buffer::isLiterate() const
2106 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2110 bool Buffer::isDocBook() const
2112 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2116 bool Buffer::isSGML() const
2118 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2119 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2123 void Buffer::sgmlOpenTag(ostream & os, int depth,
2124 string const & latexname) const
2126 if (latexname != "!-- --")
2127 os << string(depth, ' ') << "<" << latexname << ">\n";
2131 void Buffer::sgmlCloseTag(ostream & os, int depth,
2132 string const & latexname) const
2134 if (latexname != "!-- --")
2135 os << string(depth, ' ') << "</" << latexname << ">\n";
2139 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2141 LyXParagraph * par = paragraph;
2143 niceFile = nice; // this will be used by Insetincludes.
2145 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2146 string environment_stack[10];
2149 int depth = 0; // paragraph depth
2151 ofstream ofs(fname.c_str());
2154 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2158 LyXTextClass const & tclass =
2159 textclasslist.TextClass(params.textclass);
2161 LaTeXFeatures features(params, tclass.numLayouts());
2165 tex_code_break_column = lyxrc.ascii_linelen;
2167 //tex_code_break_column = 0;
2172 string sgml_includedfiles=features.getIncludedFiles(fname);
2174 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2175 ofs << "<!doctype linuxdoc system>\n\n";
2177 ofs << "<!doctype linuxdoc system [ "
2178 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2181 if (params.options.empty())
2182 sgmlOpenTag(ofs, 0, top_element);
2184 string top = top_element;
2186 top += params.options;
2187 sgmlOpenTag(ofs, 0, top);
2191 ofs << "<!-- " << LYX_DOCVERSION
2192 << " created this file. For more info see http://www.lyx.org/"
2196 int desc_on = 0; // description mode
2197 LyXLayout const & style =
2198 textclasslist.Style(params.textclass,
2201 // treat <toc> as a special case for compatibility with old code
2202 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2203 Inset * inset = par->GetInset(0);
2204 Inset::Code lyx_code = inset->LyxCode();
2205 if (lyx_code == Inset::TOC_CODE){
2206 string const temp = "toc";
2207 sgmlOpenTag(ofs, depth, temp);
2211 linuxDocHandleFootnote(ofs, par, depth);
2217 // environment tag closing
2218 for (; depth > par->depth; --depth) {
2219 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2220 environment_stack[depth].erase();
2223 // write opening SGML tags
2224 switch (style.latextype) {
2225 case LATEX_PARAGRAPH:
2226 if (depth == par->depth
2227 && !environment_stack[depth].empty()) {
2228 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2229 environment_stack[depth].erase();
2235 sgmlOpenTag(ofs, depth, style.latexname());
2240 LinuxDocError(par, 0,
2241 _("Error : Wrong depth for"
2242 " LatexType Command.\n"));
2244 if (!environment_stack[depth].empty()){
2245 sgmlCloseTag(ofs, depth,
2246 environment_stack[depth]);
2250 environment_stack[depth].erase();
2251 sgmlOpenTag(ofs, depth, style.latexname());
2254 case LATEX_ENVIRONMENT:
2255 case LATEX_ITEM_ENVIRONMENT:
2256 if (depth == par->depth
2257 && environment_stack[depth] != style.latexname()
2258 && !environment_stack[depth].empty()) {
2260 sgmlCloseTag(ofs, depth,
2261 environment_stack[depth]);
2262 environment_stack[depth].erase();
2264 if (depth < par->depth) {
2266 environment_stack[depth].erase();
2268 if (environment_stack[depth] != style.latexname()) {
2270 string const temp = "p";
2271 sgmlOpenTag(ofs, depth, temp);
2273 environment_stack[depth] = style.latexname();
2274 sgmlOpenTag(ofs, depth,
2275 environment_stack[depth]);
2277 if (style.latextype == LATEX_ENVIRONMENT) break;
2279 desc_on = (style.labeltype == LABEL_MANUAL);
2286 sgmlOpenTag(ofs, depth + 1, item_name);
2289 sgmlOpenTag(ofs, depth, style.latexname());
2296 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2300 linuxDocHandleFootnote(ofs, par, depth);
2302 while(par && par->IsDummy());
2306 // write closing SGML tags
2307 switch (style.latextype) {
2309 case LATEX_ENVIRONMENT:
2310 case LATEX_ITEM_ENVIRONMENT:
2313 sgmlCloseTag(ofs, depth, style.latexname());
2319 for (; depth > 0; --depth)
2320 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2322 if (!environment_stack[depth].empty())
2323 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2327 sgmlCloseTag(ofs, 0, top_element);
2331 // How to check for successful close
2336 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2339 string const tag = "footnote";
2341 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2342 sgmlOpenTag(os, depth + 1, tag);
2343 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2344 sgmlCloseTag(os, depth + 1, tag);
2351 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2352 int depth, int desc_on,
2353 LyXParagraph * & par)
2355 LyXParagraph * tpar = par;
2358 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2360 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2364 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2365 "Caption").second) {
2366 sgmlOpenTag(os, depth + 1, inner_tag);
2368 SimpleDocBookOnePar(os, extra_par, tpar,
2369 desc_on, depth + 2);
2370 sgmlCloseTag(os, depth+1, inner_tag);
2371 if (!extra_par.empty())
2378 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2381 string tag, inner_tag;
2382 string tmp_par, extra_par;
2383 bool inner_span = false;
2386 // Someone should give this enum a proper name (Lgb)
2394 SOME_ENUM last = NO_ONE;
2395 SOME_ENUM present = FOOTNOTE_LIKE;
2397 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2398 if (last == present) {
2400 if (!tmp_par.empty()) {
2403 sgmlCloseTag(os, depth + 1, inner_tag);
2404 sgmlOpenTag(os, depth + 1, inner_tag);
2411 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2413 if (!extra_par.empty()) os << extra_par;
2414 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2417 switch (par->footnotekind) {
2418 case LyXParagraph::FOOTNOTE:
2419 case LyXParagraph::ALGORITHM:
2422 present = FOOTNOTE_LIKE;
2425 case LyXParagraph::MARGIN:
2428 present = MARGIN_LIKE;
2431 case LyXParagraph::FIG:
2432 case LyXParagraph::WIDE_FIG:
2434 inner_tag = "title";
2438 case LyXParagraph::TAB:
2439 case LyXParagraph::WIDE_TAB:
2441 inner_tag = "title";
2446 sgmlOpenTag(os, depth, tag);
2447 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2448 DocBookHandleCaption(os, inner_tag, depth,
2452 sgmlOpenTag(os, depth + 1, inner_tag);
2455 // ignore all caption here, we processed them above!!!
2456 if (par->layout != textclasslist
2457 .NumberOfLayout(params.textclass,
2458 "Caption").second) {
2459 std::ostringstream ost;
2460 SimpleDocBookOnePar(ost, extra_par, par,
2461 desc_on, depth + 2);
2462 tmp_par += ost.str().c_str();
2464 tmp_par = frontStrip(strip(tmp_par));
2470 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2471 if (!extra_par.empty()) os << extra_par;
2472 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2477 // push a tag in a style stack
2478 void Buffer::push_tag(ostream & os, string const & tag,
2479 int & pos, char stack[5][3])
2481 #ifdef WITH_WARNINGS
2482 #warning Use a real stack! (Lgb)
2484 // pop all previous tags
2485 for (int j = pos; j >= 0; --j)
2486 os << "</" << stack[j] << ">";
2489 sprintf(stack[++pos], "%s", tag.c_str());
2492 for (int i = 0; i <= pos; ++i)
2493 os << "<" << stack[i] << ">";
2497 void Buffer::pop_tag(ostream & os, string const & tag,
2498 int & pos, char stack[5][3])
2500 #ifdef WITH_WARNINGS
2501 #warning Use a real stack! (Lgb)
2503 // Please, Lars, do not remove the global variable. I already
2504 // had to reintroduce it twice! (JMarc)
2505 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2509 // pop all tags till specified one
2510 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2511 os << "</" << stack[j] << ">";
2514 os << "</" << tag << ">";
2516 // push all tags, but the specified one
2517 for (j = j + 1; j <= pos; ++j) {
2518 os << "<" << stack[j] << ">";
2519 strcpy(stack[j - 1], stack[j]);
2523 // pop all tags till specified one
2525 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2526 os << "</" << stack[j] << ">";
2529 os << "</" << tag << ">";
2531 // push all tags, but the specified one
2532 for (int i = j + 1; i <= pos; ++i) {
2533 os << "<" << stack[i] << ">";
2534 strcpy(stack[i - 1], stack[i]);
2541 // Handle internal paragraph parsing -- layout already processed.
2543 // checks, if newcol chars should be put into this line
2544 // writes newline, if necessary.
2546 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2547 string::size_type newcol)
2550 if (colcount > lyxrc.ascii_linelen) {
2552 colcount = newcol; // assume write after this call
2557 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2558 int desc_on, int /*depth*/)
2563 LyXParagraph::size_type main_body;
2565 LyXLayout const & style = textclasslist.Style(params.textclass,
2568 char family_type = 0; // family font flag
2569 bool is_bold = false; // series font flag
2570 char shape_type = 0; // shape font flag
2571 bool is_em = false; // emphasis (italic) font flag
2573 int stack_num = -1; // style stack position
2574 // Can this be rewritten to use a std::stack, please. (Lgb)
2575 char stack[5][3]; // style stack
2576 string::size_type char_line_count = 5; // Heuristic choice ;-)
2578 if (style.labeltype != LABEL_MANUAL)
2581 main_body = par->BeginningOfMainBody();
2583 // gets paragraph main font
2585 font1 = style.labelfont;
2590 // parsing main loop
2591 for (LyXParagraph::size_type i = 0;
2592 i < par->size(); ++i) {
2604 LyXFont const font2 = par->getFont(params, i);
2606 if (font1.family() != font2.family()) {
2607 switch (family_type) {
2609 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2610 push_tag(os, "tt", stack_num, stack);
2613 else if (font2.family() == LyXFont::SANS_FAMILY) {
2614 push_tag(os, "sf", stack_num, stack);
2619 pop_tag(os, "tt", stack_num, stack);
2620 if (font2.family() == LyXFont::SANS_FAMILY) {
2621 push_tag(os, "sf", stack_num, stack);
2628 pop_tag(os, "sf", stack_num, stack);
2629 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2630 push_tag(os, "tt", stack_num, stack);
2639 if (font1.series() != font2.series()) {
2640 if (font2.series() == LyXFont::BOLD_SERIES) {
2641 push_tag(os, "bf", stack_num, stack);
2643 } else if (is_bold) {
2644 pop_tag(os, "bf", stack_num, stack);
2649 // handle italic and slanted fonts
2650 if (font1.shape() != font2.shape()) {
2651 switch (shape_type) {
2653 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2654 push_tag(os, "it", stack_num, stack);
2656 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2657 push_tag(os, "sl", stack_num, stack);
2662 pop_tag(os, "it", stack_num, stack);
2663 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2664 push_tag(os, "sl", stack_num, stack);
2671 pop_tag(os, "sl", stack_num, stack);
2672 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2673 push_tag(os, "it", stack_num, stack);
2681 if (font1.emph() != font2.emph()) {
2682 if (font2.emph() == LyXFont::ON) {
2683 push_tag(os, "em", stack_num, stack);
2686 pop_tag(os, "em", stack_num, stack);
2691 c = par->GetChar(i);
2693 if (c == LyXParagraph::META_INSET) {
2694 inset = par->GetInset(i);
2695 inset->Linuxdoc(this, os);
2698 if (font2.latex() == LyXFont::ON) {
2699 // "TeX"-Mode on == > SGML-Mode on.
2701 os << c; // see LaTeX-Generation...
2705 if (par->linuxDocConvertChar(c, sgml_string)
2706 && !style.free_spacing) { // in freespacing
2708 // non-breaking characters
2712 linux_doc_line_break(os, char_line_count, 6);
2716 linux_doc_line_break(os, char_line_count, 1);
2721 char_line_count += sgml_string.length();
2727 // needed if there is an optional argument but no contents
2728 if (main_body > 0 && main_body == par->size()) {
2732 // pop all defined Styles
2733 for (j = stack_num; j >= 0; --j) {
2734 linux_doc_line_break(os,
2736 3 + strlen(stack[j]));
2737 os << "</" << stack[j] << ">";
2740 // resets description flag correctly
2743 // <tag> not closed...
2744 linux_doc_line_break(os, char_line_count, 6);
2748 // fprintf(file, "</p>");
2754 // Print an error message.
2755 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2756 string const & message)
2758 // insert an error marker in text
2759 InsetError * new_inset = new InsetError(message);
2760 par->InsertInset(pos, new_inset);
2763 // This constant defines the maximum number of
2764 // environment layouts that can be nesteded.
2765 // The same applies for command layouts.
2766 // These values should be more than enough.
2767 // José Matos (1999/07/22)
2769 enum { MAX_NEST_LEVEL = 25};
2771 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2773 LyXParagraph * par = paragraph;
2775 niceFile = nice; // this will be used by Insetincludes.
2777 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2778 // Please use a real stack.
2779 string environment_stack[MAX_NEST_LEVEL];
2780 string environment_inner[MAX_NEST_LEVEL];
2781 // Please use a real stack.
2782 string command_stack[MAX_NEST_LEVEL];
2783 bool command_flag= false;
2784 int command_depth= 0, command_base= 0, cmd_depth= 0;
2786 string item_name, command_name;
2787 string c_depth, c_params, tmps;
2789 int depth = 0; // paragraph depth
2790 LyXTextClass const & tclass =
2791 textclasslist.TextClass(params.textclass);
2793 LaTeXFeatures features(params, tclass.numLayouts());
2797 tex_code_break_column = lyxrc.ascii_linelen;
2799 //tex_code_break_column = 0;
2801 ofstream ofs(fname.c_str());
2803 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2810 string sgml_includedfiles=features.getIncludedFiles(fname);
2812 ofs << "<!doctype " << top_element
2813 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2815 if (params.preamble.empty() && sgml_includedfiles.empty())
2818 ofs << "\n [ " << params.preamble
2819 << sgml_includedfiles << " \n]>\n\n";
2822 if (params.options.empty())
2823 sgmlOpenTag(ofs, 0, top_element);
2825 string top = top_element;
2827 top += params.options;
2828 sgmlOpenTag(ofs, 0, top);
2831 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2832 << "\n See http://www.lyx.org/ for more information -->\n";
2835 int desc_on = 0; // description mode
2836 LyXLayout const & style =
2837 textclasslist.Style(params.textclass,
2840 // environment tag closing
2841 for (; depth > par->depth; --depth) {
2842 if (environment_inner[depth] != "!-- --") {
2843 item_name= "listitem";
2844 sgmlCloseTag(ofs, command_depth + depth,
2846 if (environment_inner[depth] == "varlistentry")
2847 sgmlCloseTag(ofs, depth+command_depth,
2848 environment_inner[depth]);
2850 sgmlCloseTag(ofs, depth + command_depth,
2851 environment_stack[depth]);
2852 environment_stack[depth].erase();
2853 environment_inner[depth].erase();
2856 if (depth == par->depth
2857 && environment_stack[depth] != style.latexname()
2858 && !environment_stack[depth].empty()) {
2859 if (environment_inner[depth] != "!-- --") {
2860 item_name= "listitem";
2861 sgmlCloseTag(ofs, command_depth+depth,
2863 if (environment_inner[depth] == "varlistentry")
2865 depth + command_depth,
2866 environment_inner[depth]);
2869 sgmlCloseTag(ofs, depth + command_depth,
2870 environment_stack[depth]);
2872 environment_stack[depth].erase();
2873 environment_inner[depth].erase();
2876 // Write opening SGML tags.
2877 switch (style.latextype) {
2878 case LATEX_PARAGRAPH:
2879 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2884 LinuxDocError(par, 0,
2885 _("Error : Wrong depth for "
2886 "LatexType Command.\n"));
2888 command_name = style.latexname();
2890 tmps = style.latexparam();
2891 c_params = split(tmps, c_depth,'|');
2893 cmd_depth= lyx::atoi(c_depth);
2896 if (cmd_depth<command_base) {
2897 for (int j = command_depth;
2898 j >= command_base; --j)
2899 if (!command_stack[j].empty())
2900 sgmlCloseTag(ofs, j, command_stack[j]);
2901 command_depth= command_base= cmd_depth;
2902 } else if (cmd_depth <= command_depth) {
2903 for (int j = command_depth;
2904 j >= cmd_depth; --j)
2906 if (!command_stack[j].empty())
2907 sgmlCloseTag(ofs, j, command_stack[j]);
2908 command_depth= cmd_depth;
2910 command_depth= cmd_depth;
2912 command_depth = command_base = cmd_depth;
2913 command_flag = true;
2915 command_stack[command_depth]= command_name;
2917 // treat label as a special case for
2918 // more WYSIWYM handling.
2919 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2920 Inset * inset = par->GetInset(0);
2921 Inset::Code lyx_code = inset->LyxCode();
2922 if (lyx_code == Inset::LABEL_CODE){
2923 command_name += " id=\"";
2924 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2925 command_name += "\"";
2930 sgmlOpenTag(ofs, depth + command_depth, command_name);
2931 item_name = "title";
2932 if (command_name != "!-- --")
2933 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2936 case LATEX_ENVIRONMENT:
2937 case LATEX_ITEM_ENVIRONMENT:
2938 if (depth < par->depth) {
2940 environment_stack[depth].erase();
2943 if (environment_stack[depth] != style.latexname()) {
2944 environment_stack[depth] = style.latexname();
2945 environment_inner[depth] = "!-- --";
2946 sgmlOpenTag(ofs, depth + command_depth,
2947 environment_stack[depth]);
2949 if (environment_inner[depth] != "!-- --") {
2950 item_name= "listitem";
2952 command_depth + depth,
2954 if (environment_inner[depth] == "varlistentry")
2956 depth + command_depth,
2957 environment_inner[depth]);
2961 if (style.latextype == LATEX_ENVIRONMENT) {
2962 if (!style.latexparam().empty())
2963 sgmlOpenTag(ofs, depth + command_depth,
2964 style.latexparam());
2968 desc_on = (style.labeltype == LABEL_MANUAL);
2971 environment_inner[depth]= "varlistentry";
2973 environment_inner[depth]= "listitem";
2975 sgmlOpenTag(ofs, depth + 1 + command_depth,
2976 environment_inner[depth]);
2980 sgmlOpenTag(ofs, depth + 1 + command_depth,
2984 sgmlOpenTag(ofs, depth + 1 + command_depth,
2989 sgmlOpenTag(ofs, depth + command_depth,
2998 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
2999 depth + 1 + command_depth);
3002 DocBookHandleFootnote(ofs, par,
3003 depth + 1 + command_depth);
3005 while(par && par->IsDummy());
3008 // write closing SGML tags
3009 switch (style.latextype) {
3012 if (command_name != "!-- --")
3013 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3015 case LATEX_ENVIRONMENT:
3016 if (!style.latexparam().empty())
3017 sgmlCloseTag(ofs, depth + command_depth,
3018 style.latexparam());
3020 case LATEX_ITEM_ENVIRONMENT:
3021 if (desc_on == 1) break;
3023 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3025 case LATEX_PARAGRAPH:
3026 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3029 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3035 for (; depth >= 0; --depth) {
3036 if (!environment_stack[depth].empty()) {
3037 if (environment_inner[depth] != "!-- --") {
3038 item_name= "listitem";
3039 sgmlCloseTag(ofs, command_depth + depth,
3041 if (environment_inner[depth] == "varlistentry")
3042 sgmlCloseTag(ofs, depth + command_depth,
3043 environment_inner[depth]);
3046 sgmlCloseTag(ofs, depth + command_depth,
3047 environment_stack[depth]);
3051 for (int j = command_depth; j >= command_base; --j)
3052 if (!command_stack[j].empty())
3053 sgmlCloseTag(ofs, j, command_stack[j]);
3056 sgmlCloseTag(ofs, 0, top_element);
3059 // How to check for successful close
3063 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3064 LyXParagraph * par, int & desc_on,
3067 bool emph_flag = false;
3069 LyXLayout const & style = textclasslist.Style(params.textclass,
3072 LyXParagraph::size_type main_body;
3073 if (style.labeltype != LABEL_MANUAL)
3076 main_body = par->BeginningOfMainBody();
3078 // gets paragraph main font
3079 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3081 int char_line_count = depth;
3082 if (!style.free_spacing)
3083 for (int j = 0; j < depth; ++j)
3086 // parsing main loop
3087 for (LyXParagraph::size_type i = 0;
3088 i < par->size(); ++i) {
3089 LyXFont font2 = par->getFont(params, i);
3091 // handle <emphasis> tag
3092 if (font1.emph() != font2.emph() && i) {
3093 if (font2.emph() == LyXFont::ON) {
3097 os << "</emphasis>";
3102 char c = par->GetChar(i);
3104 if (c == LyXParagraph::META_INSET) {
3105 Inset * inset = par->GetInset(i);
3106 std::ostringstream ost;
3107 inset->DocBook(this, ost);
3108 string tmp_out = ost.str().c_str();
3111 // This code needs some explanation:
3112 // Two insets are treated specially
3113 // label if it is the first element in a command paragraph
3115 // graphics inside tables or figure floats can't go on
3116 // title (the equivalente in latex for this case is caption
3117 // and title should come first
3120 if (desc_on!= 3 || i!= 0) {
3121 if (!tmp_out.empty() && tmp_out[0] == '@') {
3123 extra += frontStrip(tmp_out, '@');
3125 os << frontStrip(tmp_out, '@');
3130 } else if (font2.latex() == LyXFont::ON) {
3131 // "TeX"-Mode on ==> SGML-Mode on.
3137 if (par->linuxDocConvertChar(c, sgml_string)
3138 && !style.free_spacing) { // in freespacing
3140 // non-breaking characters
3144 os << "\n</term><listitem><para>";
3156 // needed if there is an optional argument but no contents
3157 if (main_body > 0 && main_body == par->size()) {
3161 os << "</emphasis>";
3164 // resets description flag correctly
3167 // <term> not closed...
3175 // This should be enabled when the Chktex class is implemented. (Asger)
3176 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3177 // Other flags: -wall -v0 -x
3178 int Buffer::runChktex()
3180 if (!users->text) return 0;
3182 ProhibitInput(users);
3184 // get LaTeX-Filename
3185 string const name = getLatexName();
3186 string path = OnlyPath(filename);
3188 string const org_path = path;
3189 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3193 Path p(path); // path to LaTeX file
3194 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3196 // Remove all error insets
3197 bool const removedErrorInsets = users->removeAutoInsets();
3199 // Generate the LaTeX file if neccessary
3200 makeLaTeXFile(name, org_path, false);
3203 Chktex chktex(lyxrc.chktex_command, name, filepath);
3204 int res = chktex.run(terr); // run chktex
3207 WriteAlert(_("chktex did not work!"),
3208 _("Could not run with file:"), name);
3209 } else if (res > 0) {
3210 // Insert all errors as errors boxes
3211 users->insertErrors(terr);
3214 // if we removed error insets before we ran chktex or if we inserted
3215 // error insets after we ran chktex, this must be run:
3216 if (removedErrorInsets || res){
3218 users->fitCursor(users->text);
3226 void Buffer::validate(LaTeXFeatures & features) const
3228 LyXParagraph * par = paragraph;
3229 LyXTextClass const & tclass =
3230 textclasslist.TextClass(params.textclass);
3232 // AMS Style is at document level
3234 features.amsstyle = (params.use_amsmath ||
3235 tclass.provides(LyXTextClass::amsmath));
3238 // We don't use "lyxerr.debug" because of speed. (Asger)
3239 if (lyxerr.debugging(Debug::LATEX))
3240 lyxerr << "Paragraph: " << par << endl;
3242 // Now just follow the list of paragraphs and run
3243 // validate on each of them.
3244 par->validate(features);
3246 // and then the next paragraph
3250 // the bullet shapes are buffer level not paragraph level
3251 // so they are tested here
3252 for (int i = 0; i < 4; ++i) {
3253 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3254 int const font = params.user_defined_bullets[i].getFont();
3256 int const c = params
3257 .user_defined_bullets[i]
3264 features.latexsym = true;
3266 } else if (font == 1) {
3267 features.amssymb = true;
3268 } else if ((font >= 2 && font <= 5)) {
3269 features.pifont = true;
3274 if (lyxerr.debugging(Debug::LATEX)) {
3275 features.showStruct();
3280 void Buffer::setPaperStuff()
3282 params.papersize = BufferParams::PAPER_DEFAULT;
3283 char const c1 = params.paperpackage;
3284 if (c1 == BufferParams::PACKAGE_NONE) {
3285 char const c2 = params.papersize2;
3286 if (c2 == BufferParams::VM_PAPER_USLETTER)
3287 params.papersize = BufferParams::PAPER_USLETTER;
3288 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3289 params.papersize = BufferParams::PAPER_LEGALPAPER;
3290 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3291 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3292 else if (c2 == BufferParams::VM_PAPER_A3)
3293 params.papersize = BufferParams::PAPER_A3PAPER;
3294 else if (c2 == BufferParams::VM_PAPER_A4)
3295 params.papersize = BufferParams::PAPER_A4PAPER;
3296 else if (c2 == BufferParams::VM_PAPER_A5)
3297 params.papersize = BufferParams::PAPER_A5PAPER;
3298 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3299 (c2 == BufferParams::VM_PAPER_B5))
3300 params.papersize = BufferParams::PAPER_B5PAPER;
3301 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3302 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3303 params.papersize = BufferParams::PAPER_A4PAPER;
3307 // This function should be in Buffer because it's a buffer's property (ale)
3308 string const Buffer::getIncludeonlyList(char delim)
3311 for (inset_iterator it = inset_iterator_begin();
3312 it != inset_iterator_end(); ++it) {
3313 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3314 InsetInclude * insetinc =
3315 static_cast<InsetInclude *>(*it);
3316 if (insetinc->isInclude()
3317 && insetinc->isNoLoad()) {
3320 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3324 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3329 vector<string> const Buffer::getLabelList()
3331 /// if this is a child document and the parent is already loaded
3332 /// Use the parent's list instead [ale990407]
3333 if (!params.parentname.empty()
3334 && bufferlist.exists(params.parentname)) {
3335 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3337 return tmp->getLabelList();
3340 vector<string> label_list;
3341 for (inset_iterator it = inset_iterator_begin();
3342 it != inset_iterator_end(); ++it) {
3343 vector<string> const l = (*it)->getLabelList();
3344 label_list.insert(label_list.end(), l.begin(), l.end());
3350 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3355 vector<vector<TocItem> > l(4);
3356 LyXParagraph * par = paragraph;
3359 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3360 if (textclasslist.Style(params.textclass,
3361 par->GetLayout()).labeltype
3362 == LABEL_SENSITIVE) {
3366 tmp.str = par->String(this, false);
3367 switch (par->footnotekind) {
3368 case LyXParagraph::FIG:
3369 case LyXParagraph::WIDE_FIG:
3370 tmp.str = tostr(++figs) + ". "
3372 l[TOC_LOF].push_back(tmp);
3374 case LyXParagraph::TAB:
3375 case LyXParagraph::WIDE_TAB:
3376 tmp.str = tostr(++tables) + ". "
3378 l[TOC_LOT].push_back(tmp);
3380 case LyXParagraph::ALGORITHM:
3381 tmp.str = tostr(++algs) + ". "
3383 l[TOC_LOA].push_back(tmp);
3385 case LyXParagraph::FOOTNOTE:
3386 case LyXParagraph::MARGIN:
3390 } else if (!par->IsDummy()) {
3392 char const labeltype =
3393 textclasslist.Style(params.textclass,
3394 par->GetLayout()).labeltype;
3396 if (labeltype >= LABEL_COUNTER_CHAPTER
3397 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3398 // insert this into the table of contents
3403 textclasslist.TextClass(params.textclass).maxcounter());
3404 tmp.str = par->String(this, true);
3405 l[TOC_TOC].push_back(tmp);
3416 // This is also a buffer property (ale)
3417 vector<pair<string,string> > const Buffer::getBibkeyList()
3419 /// if this is a child document and the parent is already loaded
3420 /// Use the parent's list instead [ale990412]
3421 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3422 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3424 return tmp->getBibkeyList();
3427 vector<pair<string, string> > keys;
3428 LyXParagraph * par = paragraph;
3431 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3432 par->String(this, false)));
3436 // Might be either using bibtex or a child has bibliography
3438 for (inset_iterator it = inset_iterator_begin();
3439 it != inset_iterator_end(); ++it) {
3440 // Search for Bibtex or Include inset
3441 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3442 vector<pair<string,string> > tmp =
3443 static_cast<InsetBibtex*>(*it)->getKeys(this);
3444 keys.insert(keys.end(), tmp.begin(), tmp.end());
3445 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3446 vector<pair<string,string> > const tmp =
3447 static_cast<InsetInclude*>(*it)->getKeys();
3448 keys.insert(keys.end(), tmp.begin(), tmp.end());
3457 bool Buffer::isDepClean(string const & name) const
3459 DEPCLEAN * item = dep_clean;
3460 while (item && item->master != name)
3462 if (!item) return true;
3467 void Buffer::markDepClean(string const & name)
3470 dep_clean = new DEPCLEAN;
3471 dep_clean->clean = true;
3472 dep_clean->master = name;
3473 dep_clean->next = 0;
3475 DEPCLEAN * item = dep_clean;
3476 while (item && item->master != name)
3481 item = new DEPCLEAN;
3483 item->master = name;
3490 bool Buffer::Dispatch(string const & command)
3492 // Split command string into command and argument
3494 string line = frontStrip(command);
3495 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3497 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3501 bool Buffer::Dispatch(int action, string const & argument)
3503 bool dispatched = true;
3506 Exporter::Export(this, argument, false);
3516 void Buffer::resize()
3518 /// resize the BufferViews!
3524 void Buffer::resizeInsets(BufferView * bv)
3526 /// then remove all LyXText in text-insets
3527 LyXParagraph * par = paragraph;
3528 for (; par; par = par->next) {
3529 par->resizeInsetsLyXText(bv);
3533 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3536 LyXParagraph * par = paragraph;
3538 par->ChangeLanguage(params, from, to);
3544 bool Buffer::isMultiLingual()
3546 LyXParagraph * par = paragraph;
3548 if (par->isMultiLingual(params))
3556 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3557 LyXParagraph::size_type pos)
3560 it = par->InsetIterator(pos);
3561 if (it == par->inset_iterator_end()) {
3568 void Buffer::inset_iterator::SetParagraph()
3571 it = par->inset_iterator_begin();
3572 if (it != par->inset_iterator_end())
3577 // We maintain an invariant that whenever par = 0 then it = 0