1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
22 #include <sys/types.h>
32 #pragma implementation "buffer.h"
36 #include "bufferlist.h"
38 #include "lyx_gui_misc.h"
39 #include "LyXAction.h"
42 #include "tex-strings.h"
44 #include "bufferview_funcs.h"
45 #include "minibuffer.h"
48 #include "mathed/formulamacro.h"
49 #include "insets/lyxinset.h"
50 #include "insets/inseterror.h"
51 #include "insets/insetlabel.h"
52 #include "insets/insetref.h"
53 #include "insets/inseturl.h"
54 #include "insets/insetinfo.h"
55 #include "insets/insetquotes.h"
56 #include "insets/insetlatexaccent.h"
57 #include "insets/insetbib.h"
58 #include "insets/insetcite.h"
59 #include "insets/insetexternal.h"
60 #include "insets/insetindex.h"
61 #include "insets/insetinclude.h"
62 #include "insets/insettoc.h"
63 #include "insets/insetparent.h"
64 #include "insets/insetspecialchar.h"
65 #include "insets/figinset.h"
66 #include "insets/insettext.h"
67 #include "insets/insetert.h"
68 #include "insets/insetgraphics.h"
69 #include "insets/insetfoot.h"
70 #include "insets/insetmarginal.h"
71 #include "insets/insetminipage.h"
72 #include "insets/insetfloat.h"
73 #include "insets/insetlist.h"
74 #include "insets/insettabular.h"
75 #include "insets/insettheorem.h"
76 #include "insets/insetcaption.h"
77 #include "support/filetools.h"
78 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
91 #include "lyx_gui_misc.h" // WarnReadonly()
92 #include "frontends/Dialogs.h"
108 using std::istringstream;
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();
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::fileName(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_info);
251 if (format < 2.16 && params.language == "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_info);
368 if (format < 2.16 && params.language == "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_info);
384 if (format < 2.16 && params.language == "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 Languages::iterator lit = languages.find(tok);
776 if (lit != languages.end()) {
777 font.setLanguage(&(*lit).second);
779 font.setLanguage(params.language_info);
780 lex.printError("Unknown language `$$Token'");
782 } else if (token == "\\emph") {
784 font.setEmph(font.setLyXMisc(lex.GetString()));
785 } else if (token == "\\bar") {
787 string const tok = lex.GetString();
788 // This is dirty, but gone with LyX3. (Asger)
790 font.setUnderbar(LyXFont::ON);
791 else if (tok == "no")
792 font.setUnderbar(LyXFont::OFF);
793 else if (tok == "default")
794 font.setUnderbar(LyXFont::INHERIT);
796 lex.printError("Unknown bar font flag "
798 } else if (token == "\\noun") {
800 font.setNoun(font.setLyXMisc(lex.GetString()));
801 } else if (token == "\\color") {
803 font.setLyXColor(lex.GetString());
804 } else if (token == "\\align") {
805 int tmpret = lex.FindToken(string_align);
806 if (tmpret == -1) ++tmpret;
807 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
809 for (; tmpret > 0; --tmpret)
810 tmpret2 = tmpret2 * 2;
811 par->align = LyXAlignment(tmpret2);
813 } else if (token == "\\added_space_top") {
815 par->added_space_top = VSpace(lex.GetString());
816 } else if (token == "\\added_space_bottom") {
818 par->added_space_bottom = VSpace(lex.GetString());
819 } else if (token == "\\pextra_type") {
821 par->pextra_type = lex.GetInteger();
822 } else if (token == "\\pextra_width") {
824 par->pextra_width = lex.GetString();
825 } else if (token == "\\pextra_widthp") {
827 par->pextra_widthp = lex.GetString();
828 } else if (token == "\\pextra_alignment") {
830 par->pextra_alignment = lex.GetInteger();
831 } else if (token == "\\pextra_hfill") {
833 par->pextra_hfill = lex.GetInteger();
834 } else if (token == "\\pextra_start_minipage") {
836 par->pextra_start_minipage = lex.GetInteger();
837 } else if (token == "\\labelwidthstring") {
839 par->labelwidthstring = lex.GetString();
840 // do not delete this token, it is still needed!
841 } else if (token == "\\end_inset") {
842 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
843 << "Last inset read was: " << last_inset_read
845 // Simply ignore this. The insets do not have
847 // But insets should read it, it is a part of
848 // the inset isn't it? Lgb.
849 } else if (token == "\\begin_inset") {
850 readInset(lex, par, pos, font);
851 } else if (token == "\\SpecialChar") {
852 LyXLayout const & layout =
853 textclasslist.Style(params.textclass,
856 // Insets don't make sense in a free-spacing context! ---Kayvan
857 if (layout.free_spacing) {
860 string next_token = lex.GetString();
861 if (next_token == "\\-") {
862 par->InsertChar(pos, '-', font);
863 } else if (next_token == "\\protected_separator"
864 || next_token == "~") {
865 par->InsertChar(pos, ' ', font);
867 lex.printError("Token `$$Token' "
869 "paragraph layout!");
874 Inset * inset = new InsetSpecialChar;
875 inset->Read(this, lex);
876 par->InsertInset(pos, inset, font);
879 } else if (token == "\\newline") {
880 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
882 } else if (token == "\\LyXTable") {
883 Inset * inset = new InsetTabular(this);
884 inset->Read(this, lex);
885 par->InsertInset(pos, inset, font);
887 } else if (token == "\\hfill") {
888 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
890 } else if (token == "\\protected_separator") { // obsolete
891 // This is a backward compability thingie. (Lgb)
892 // Remove it later some time...introduced with fileformat
894 LyXLayout const & layout =
895 textclasslist.Style(params.textclass,
898 if (layout.free_spacing) {
899 par->InsertChar(pos, ' ', font);
901 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
902 par->InsertInset(pos, inset, font);
905 } else if (token == "\\bibitem") { // ale970302
907 InsetCommandParams p( "bibitem" );
908 par->bibkey = new InsetBibKey(p);
910 par->bibkey->Read(this, lex);
911 } else if (token == "\\backslash") {
912 par->InsertChar(pos, '\\', font);
914 } else if (token == "\\the_end") {
917 // This should be insurance for the future: (Asger)
918 lex.printError("Unknown token `$$Token'. "
919 "Inserting as text.");
920 string::const_iterator cit = token.begin();
921 string::const_iterator end = token.end();
922 for(; cit != end; ++cit) {
923 par->InsertChar(pos, (*cit), font);
931 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
932 int & pos, LyXFont & font)
935 if (lex.GetString() != "\\begin_inset") {
936 lyxerr << "Buffer::readInset: Consistency check failed."
943 string const tmptok = lex.GetString();
944 last_inset_read = tmptok;
946 // test the different insets
947 if (tmptok == "LatexCommand") {
948 InsetCommandParams inscmd;
951 if (inscmd.getCmdName() == "cite") {
952 inset = new InsetCitation(inscmd);
953 } else if (inscmd.getCmdName() == "bibitem") {
954 lex.printError("Wrong place for bibitem");
955 inset = new InsetBibKey(inscmd);
956 } else if (inscmd.getCmdName() == "BibTeX") {
957 inset = new InsetBibtex(inscmd, this);
958 } else if (inscmd.getCmdName() == "index") {
959 inset = new InsetIndex(inscmd);
960 } else if (inscmd.getCmdName() == "include") {
961 inset = new InsetInclude(inscmd, this);
962 } else if (inscmd.getCmdName() == "label") {
963 inset = new InsetLabel(inscmd);
964 } else if (inscmd.getCmdName() == "url"
965 || inscmd.getCmdName() == "htmlurl") {
966 inset = new InsetUrl(inscmd);
967 } else if (inscmd.getCmdName() == "ref"
968 || inscmd.getCmdName() == "pageref"
969 || inscmd.getCmdName() == "vref"
970 || inscmd.getCmdName() == "vpageref"
971 || inscmd.getCmdName() == "prettyref") {
972 if (!inscmd.getOptions().empty()
973 || !inscmd.getContents().empty()) {
974 inset = new InsetRef(inscmd);
976 } else if (inscmd.getCmdName() == "tableofcontents"
977 || inscmd.getCmdName() == "listofalgorithms"
978 || inscmd.getCmdName() == "listoffigures"
979 || inscmd.getCmdName() == "listoftables") {
980 inset = new InsetTOC(inscmd);
981 } else if (inscmd.getCmdName() == "printindex") {
982 inset = new InsetPrintIndex(inscmd);
983 } else if (inscmd.getCmdName() == "lyxparent") {
984 inset = new InsetParent(inscmd, this);
987 if (tmptok == "Quotes") {
988 inset = new InsetQuotes;
989 } else if (tmptok == "External") {
990 inset = new InsetExternal;
991 } else if (tmptok == "FormulaMacro") {
992 inset = new InsetFormulaMacro;
993 } else if (tmptok == "Formula") {
994 inset = new InsetFormula;
995 } else if (tmptok == "Figure") {
996 inset = new InsetFig(100, 100, this);
997 } else if (tmptok == "Info") {
998 inset = new InsetInfo;
999 } else if (tmptok == "Include") {
1000 InsetCommandParams p( "Include" );
1001 inset = new InsetInclude(p, this);
1002 } else if (tmptok == "ERT") {
1003 inset = new InsetERT;
1004 } else if (tmptok == "Tabular") {
1005 inset = new InsetTabular(this);
1006 } else if (tmptok == "Text") {
1007 inset = new InsetText;
1008 } else if (tmptok == "Foot") {
1009 inset = new InsetFoot;
1010 } else if (tmptok == "Marginal") {
1011 inset = new InsetMarginal;
1012 } else if (tmptok == "Minipage") {
1013 inset = new InsetMinipage;
1014 } else if (tmptok == "Float") {
1016 string tmptok = lex.GetString();
1017 inset = new InsetFloat(tmptok);
1018 } else if (tmptok == "List") {
1019 inset = new InsetList;
1020 } else if (tmptok == "Theorem") {
1021 inset = new InsetList;
1022 } else if (tmptok == "Caption") {
1023 inset = new InsetCaption;
1024 } else if (tmptok == "GRAPHICS") {
1025 inset = new InsetGraphics;
1028 if (inset) inset->Read(this, lex);
1032 par->InsertInset(pos, inset, font);
1038 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1042 string const token(lex.GetString());
1043 if (token == "\\lyxformat") { // the first token _must_ be...
1045 format = lex.GetFloat();
1047 if (LYX_FORMAT - format > 0.05) {
1049 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1050 LYX_FORMAT, format);
1052 if (format - LYX_FORMAT > 0.05) {
1053 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1054 LYX_FORMAT, format);
1056 bool the_end = readLyXformat2(lex, par);
1057 // Formats >= 2.13 support "\the_end" marker
1064 WriteAlert(_("Warning!"),
1065 _("Reading of document is not complete"),
1066 _("Maybe the document is truncated"));
1067 // We simulate a safe reading anyways to allow
1068 // users to take the chance... (Asger)
1072 WriteAlert(_("ERROR!"),
1073 _("Old LyX file format found. "
1074 "Use LyX 0.10.x to read this!"));
1078 } else { // "\\lyxformat" not found
1079 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1082 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1088 // Should probably be moved to somewhere else: BufferView? LyXView?
1089 bool Buffer::save() const
1091 // We don't need autosaves in the immediate future. (Asger)
1092 resetAutosaveTimers();
1096 if (lyxrc.make_backup) {
1097 s = fileName() + '~';
1098 if (!lyxrc.backupdir_path.empty())
1099 s = AddName(lyxrc.backupdir_path,
1100 subst(CleanupPath(s),'/','!'));
1102 // Rename is the wrong way of making a backup,
1103 // this is the correct way.
1104 /* truss cp fil fil2:
1105 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1106 stat("LyXVC.lyx", 0xEFFFF688) = 0
1107 open("LyXVC.lyx", O_RDONLY) = 3
1108 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1109 fstat(4, 0xEFFFF508) = 0
1110 fstat(3, 0xEFFFF508) = 0
1111 read(3, " # T h i s f i l e w".., 8192) = 5579
1112 write(4, " # T h i s f i l e w".., 5579) = 5579
1113 read(3, 0xEFFFD4A0, 8192) = 0
1116 chmod("LyXVC3.lyx", 0100644) = 0
1117 lseek(0, 0, SEEK_CUR) = 46440
1121 // Should proabaly have some more error checking here.
1122 // Should be cleaned up in 0.13, at least a bit.
1123 // Doing it this way, also makes the inodes stay the same.
1124 // This is still not a very good solution, in particular we
1125 // might loose the owner of the backup.
1126 FileInfo finfo(fileName());
1127 if (finfo.exist()) {
1128 mode_t fmode = finfo.getMode();
1129 struct utimbuf times = {
1130 finfo.getAccessTime(),
1131 finfo.getModificationTime() };
1133 ifstream ifs(fileName().c_str());
1134 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1139 ::chmod(s.c_str(), fmode);
1141 if (::utime(s.c_str(), ×)) {
1142 lyxerr << "utime error." << endl;
1145 lyxerr << "LyX was not able to make "
1146 "backupcopy. Beware." << endl;
1151 if (writeFile(fileName(), false)) {
1153 removeAutosaveFile(fileName());
1155 // Saving failed, so backup is not backup
1156 if (lyxrc.make_backup) {
1157 lyx::rename(s, fileName());
1165 // Returns false if unsuccesful
1166 bool Buffer::writeFile(string const & fname, bool flag) const
1168 // if flag is false writeFile will not create any GUI
1169 // warnings, only cerr.
1170 // Needed for autosave in background or panic save (Matthias 120496)
1172 if (read_only && (fname == filename)) {
1173 // Here we should come with a question if we should
1174 // perform the write anyway.
1176 lyxerr << _("Error! Document is read-only: ")
1179 WriteAlert(_("Error! Document is read-only: "),
1184 FileInfo finfo(fname);
1185 if (finfo.exist() && !finfo.writable()) {
1186 // Here we should come with a question if we should
1187 // try to do the save anyway. (i.e. do a chmod first)
1189 lyxerr << _("Error! Cannot write file: ")
1192 WriteFSAlert(_("Error! Cannot write file: "),
1197 ofstream ofs(fname.c_str());
1200 lyxerr << _("Error! Cannot open file: ")
1203 WriteFSAlert(_("Error! Cannot open file: "),
1209 // Use the standard "C" locale for file output.
1210 ofs.imbue(std::locale::classic());
1213 // The top of the file should not be written by params.
1215 // write out a comment in the top of the file
1216 ofs << '#' << LYX_DOCVERSION
1217 << " created this file. For more info see http://www.lyx.org/\n";
1218 ofs.setf(ios::showpoint|ios::fixed);
1221 char dummy_format[512];
1222 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1223 ofs << "\\lyxformat " << dummy_format << "\n";
1225 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1227 // now write out the buffer paramters.
1228 params.writeFile(ofs);
1230 char footnoteflag = 0;
1233 // this will write out all the paragraphs
1234 // using recursive descent.
1235 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1237 // Write marker that shows file is complete
1238 ofs << "\n\\the_end" << endl;
1240 // how to check if close went ok?
1246 void Buffer::writeFileAscii(string const & fname, int linelen)
1250 char footnoteflag = 0;
1253 LyXParagraph::size_type i;
1256 int ltype_depth = 0;
1259 int currlinelen = 0;
1261 bool ref_printed = false;
1263 ofstream ofs(fname.c_str());
1265 WriteFSAlert(_("Error: Cannot write file:"), fname);
1269 string const fname1 = TmpFileName();
1270 LyXParagraph * par = paragraph;
1276 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1280 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1285 /* begins a footnote environment ? */
1286 if (footnoteflag != par->footnoteflag) {
1287 footnoteflag = par->footnoteflag;
1289 j = strlen(string_footnotekinds[par->footnotekind])+4;
1290 if (currlinelen + j > linelen)
1293 << string_footnotekinds[par->footnotekind] << "] ";
1299 /* begins or ends a deeper area ?*/
1300 if (depth != par->depth) {
1301 if (par->depth > depth) {
1302 while (par->depth > depth) {
1307 while (par->depth < depth) {
1313 /* First write the layout */
1314 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1315 if (tmp == "Itemize") {
1317 ltype_depth = depth+1;
1318 } else if (tmp == "Enumerate") {
1320 ltype_depth = depth+1;
1321 } else if (contains(tmp, "ection")) {
1323 ltype_depth = depth+1;
1324 } else if (contains(tmp, "aragraph")) {
1326 ltype_depth = depth+1;
1327 } else if (tmp == "Description") {
1329 ltype_depth = depth+1;
1330 } else if (tmp == "Abstract") {
1333 } else if (tmp == "Bibliography") {
1341 /* maybe some vertical spaces */
1343 /* the labelwidthstring used in lists */
1347 /* some pagebreaks? */
1351 /* what about the alignment */
1354 /* dummy layout, that means a footnote ended */
1355 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1359 lyxerr << "Should this ever happen?" << endl;
1364 LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1366 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1367 if (!i && !footnoteflag && !noparbreak){
1369 for(j = 0; j < depth; ++j)
1371 currlinelen = depth * 2;
1373 case 0: /* Standard */
1374 case 4: /* (Sub)Paragraph */
1375 case 5: /* Description */
1377 case 6: /* Abstract */
1378 ofs << "Abstract\n\n";
1380 case 7: /* Bibliography */
1382 ofs << "References\n\n";
1387 ofs << par->labelstring << " ";
1390 if (ltype_depth > depth) {
1391 for(j = ltype_depth - 1; j > depth; --j)
1393 currlinelen += (ltype_depth-depth)*2;
1396 LyXFont font2 = par->GetFontSettings(params, i);
1397 if (font1.latex() != font2.latex()) {
1398 if (font2.latex() == LyXFont::OFF)
1405 c = par->GetChar(i);
1409 case LyXParagraph::META_INSET:
1410 if ((inset = par->GetInset(i))) {
1412 inset->Ascii(this, ofs);
1413 currlinelen += (ofs.tellp() - fpos);
1414 actpos += (ofs.tellp() - fpos) - 1;
1417 case LyXParagraph::META_NEWLINE:
1419 for(j = 0; j < depth; ++j)
1421 currlinelen = depth * 2;
1422 if (ltype_depth > depth) {
1423 for(j = ltype_depth;
1426 currlinelen += (ltype_depth - depth) * 2;
1429 case LyXParagraph::META_HFILL:
1436 if (currlinelen > linelen - 10
1437 && c == ' ' && i + 2 < par->size()) {
1439 for(j = 0; j < depth; ++j)
1441 currlinelen = depth * 2;
1442 if (ltype_depth > depth) {
1443 for(j = ltype_depth;
1446 currlinelen += (ltype_depth-depth)*2;
1448 } else if (c != '\0')
1451 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1461 //----------------------------------------------------------------------------
1463 //----------------------------------------------------------------------------
1464 string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
1466 ostringstream buffer;
1467 LyXFont font1, font2;
1468 Inset const * inset;
1469 char c, footnoteflag = 0, depth = 0;
1471 LyXParagraph::size_type i;
1474 int ltype_depth = 0;
1475 int currlinelen = 0;
1476 bool ref_printed = false;
1482 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1486 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1490 /* begins a footnote environment ? */
1491 if (footnoteflag != par->footnoteflag) {
1492 footnoteflag = par->footnoteflag;
1494 j = strlen(string_footnotekinds[par->footnotekind])+4;
1495 if ((linelen > 0) &&
1496 ((currlinelen + j) > linelen)) {
1502 string_footnotekinds[par->footnotekind] <<
1508 /* begins or ends a deeper area ?*/
1509 if (depth != par->depth) {
1510 if (par->depth > depth) {
1511 while (par->depth > depth) {
1516 while (par->depth < depth) {
1522 /* First write the layout */
1523 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1524 if (tmp == "Itemize") {
1526 ltype_depth = depth+1;
1527 } else if (tmp == "Enumerate") {
1529 ltype_depth = depth+1;
1530 } else if (strstr(tmp.c_str(), "ection")) {
1532 ltype_depth = depth+1;
1533 } else if (strstr(tmp.c_str(), "aragraph")) {
1535 ltype_depth = depth+1;
1536 } else if (tmp == "Description") {
1538 ltype_depth = depth+1;
1539 } else if (tmp == "Abstract") {
1542 } else if (tmp == "Bibliography") {
1550 /* maybe some vertical spaces */
1552 /* the labelwidthstring used in lists */
1556 /* some pagebreaks? */
1560 /* what about the alignment */
1563 /* dummy layout, that means a footnote ended */
1564 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1568 lyxerr << "Should this ever happen?" << endl;
1572 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1573 for (i = 0; i < par->size(); ++i) {
1574 if (!i && !footnoteflag && !noparbreak){
1576 for(j = 0; j < depth; ++j)
1578 currlinelen = depth * 2;
1580 case 0: /* Standard */
1581 case 4: /* (Sub)Paragraph */
1582 case 5: /* Description */
1584 case 6: /* Abstract */
1585 buffer << "Abstract\n\n";
1587 case 7: /* Bibliography */
1589 buffer << "References\n\n";
1594 buffer << par->labelstring << " ";
1597 if (ltype_depth > depth) {
1598 for(j = ltype_depth - 1; j > depth; --j)
1600 currlinelen += (ltype_depth-depth)*2;
1603 font2 = par->GetFontSettings(params, i);
1604 if (font1.latex() != font2.latex()) {
1605 if (font2.latex() == LyXFont::OFF)
1612 c = par->GetChar(i);
1616 case LyXParagraph::META_INSET:
1617 if ((inset = par->GetInset(i))) {
1618 if (!inset->Ascii(this, buffer)) {
1620 string s = rsplit(buffer.str(),
1622 currlinelen += s.length();
1624 // to be sure it breaks paragraph
1625 currlinelen += linelen;
1629 case LyXParagraph::META_NEWLINE:
1631 for(j = 0; j < depth; ++j)
1633 currlinelen = depth * 2;
1634 if (ltype_depth > depth) {
1635 for(j = ltype_depth;
1638 currlinelen += (ltype_depth - depth) * 2;
1641 case LyXParagraph::META_HFILL:
1648 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1649 (c == ' ') && ((i + 2) < par->size()))
1652 for(j = 0; j < depth; ++j)
1654 currlinelen = depth * 2;
1655 if (ltype_depth > depth) {
1656 for(j = ltype_depth;
1659 currlinelen += (ltype_depth-depth)*2;
1661 } else if (c != '\0')
1664 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1669 return buffer.str();
1673 void Buffer::writeFileAscii(string const & fname, int linelen)
1675 ofstream ofs(fname.c_str());
1677 WriteFSAlert(_("Error: Cannot write file:"), fname);
1680 writeFileAscii(ofs, linelen);
1684 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1686 LyXParagraph * par = paragraph;
1688 ofs << asciiParagraph(par, linelen);
1695 void Buffer::makeLaTeXFile(string const & fname,
1696 string const & original_path,
1697 bool nice, bool only_body)
1699 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1701 niceFile = nice; // this will be used by Insetincludes.
1703 tex_code_break_column = lyxrc.ascii_linelen;
1705 LyXTextClass const & tclass =
1706 textclasslist.TextClass(params.textclass);
1708 ofstream ofs(fname.c_str());
1710 WriteFSAlert(_("Error: Cannot open file: "), fname);
1714 // validate the buffer.
1715 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1716 LaTeXFeatures features(params, tclass.numLayouts());
1718 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1721 // The starting paragraph of the coming rows is the
1722 // first paragraph of the document. (Asger)
1723 texrow.start(paragraph, 0);
1725 if (!only_body && nice) {
1726 ofs << "%% " LYX_DOCVERSION " created this file. "
1727 "For more info, see http://www.lyx.org/.\n"
1728 "%% Do not edit unless you really know what "
1733 lyxerr.debug() << "lyx header finished" << endl;
1734 // There are a few differences between nice LaTeX and usual files:
1735 // usual is \batchmode and has a
1736 // special input@path to allow the including of figures
1737 // with either \input or \includegraphics (what figinsets do).
1738 // batchmode is not set if there is a tex_code_break_column.
1739 // In this case somebody is interested in the generated LaTeX,
1740 // so this is OK. input@path is set when the actual parameter
1741 // original_path is set. This is done for usual tex-file, but not
1742 // for nice-latex-file. (Matthias 250696)
1745 // code for usual, NOT nice-latex-file
1746 ofs << "\\batchmode\n"; // changed
1747 // from \nonstopmode
1750 if (!original_path.empty()) {
1751 ofs << "\\makeatletter\n"
1752 << "\\def\\input@path{{"
1753 << original_path << "/}}\n"
1754 << "\\makeatother\n";
1760 ofs << "\\documentclass";
1762 string options; // the document class options.
1764 if (tokenPos(tclass.opt_fontsize(),
1765 '|', params.fontsize) >= 0) {
1766 // only write if existing in list (and not default)
1767 options += params.fontsize;
1772 if (!params.use_geometry &&
1773 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1774 switch (params.papersize) {
1775 case BufferParams::PAPER_A4PAPER:
1776 options += "a4paper,";
1778 case BufferParams::PAPER_USLETTER:
1779 options += "letterpaper,";
1781 case BufferParams::PAPER_A5PAPER:
1782 options += "a5paper,";
1784 case BufferParams::PAPER_B5PAPER:
1785 options += "b5paper,";
1787 case BufferParams::PAPER_EXECUTIVEPAPER:
1788 options += "executivepaper,";
1790 case BufferParams::PAPER_LEGALPAPER:
1791 options += "legalpaper,";
1797 if (params.sides != tclass.sides()) {
1798 switch (params.sides) {
1799 case LyXTextClass::OneSide:
1800 options += "oneside,";
1802 case LyXTextClass::TwoSides:
1803 options += "twoside,";
1810 if (params.columns != tclass.columns()) {
1811 if (params.columns == 2)
1812 options += "twocolumn,";
1814 options += "onecolumn,";
1817 if (!params.use_geometry
1818 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1819 options += "landscape,";
1821 // language should be a parameter to \documentclass
1822 bool use_babel = false;
1823 if (params.language_info->lang() == "hebrew") // This seems necessary
1824 features.UsedLanguages.insert(default_language);
1825 if (params.language != "default" ||
1826 !features.UsedLanguages.empty() ) {
1828 for (LaTeXFeatures::LanguageList::const_iterator cit =
1829 features.UsedLanguages.begin();
1830 cit != features.UsedLanguages.end(); ++cit)
1831 options += (*cit)->lang() + ",";
1832 options += params.language_info->lang() + ',';
1835 // the user-defined options
1836 if (!params.options.empty()) {
1837 options += params.options + ',';
1840 if (!options.empty()){
1841 options = strip(options, ',');
1842 ofs << '[' << options << ']';
1846 << textclasslist.LatexnameOfClass(params.textclass)
1849 // end of \documentclass defs
1851 // font selection must be done before loading fontenc.sty
1852 if (params.fonts != "default") {
1853 ofs << "\\usepackage{" << params.fonts << "}\n";
1856 // this one is not per buffer
1857 if (lyxrc.fontenc != "default") {
1858 ofs << "\\usepackage[" << lyxrc.fontenc
1863 if (params.inputenc == "auto") {
1864 string const doc_encoding =
1865 params.language_info->encoding()->LatexName();
1867 // Create a list with all the input encodings used
1869 set<string> encodings;
1870 for (LaTeXFeatures::LanguageList::const_iterator it =
1871 features.UsedLanguages.begin();
1872 it != features.UsedLanguages.end(); ++it)
1873 if ((*it)->encoding()->LatexName() != doc_encoding)
1874 encodings.insert((*it)->encoding()->LatexName());
1876 ofs << "\\usepackage[";
1877 for (set<string>::const_iterator it = encodings.begin();
1878 it != encodings.end(); ++it)
1880 ofs << doc_encoding << "]{inputenc}\n";
1882 } else if (params.inputenc != "default") {
1883 ofs << "\\usepackage[" << params.inputenc
1888 // At the very beginning the text parameters.
1889 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1890 switch (params.paperpackage) {
1891 case BufferParams::PACKAGE_A4:
1892 ofs << "\\usepackage{a4}\n";
1895 case BufferParams::PACKAGE_A4WIDE:
1896 ofs << "\\usepackage{a4wide}\n";
1899 case BufferParams::PACKAGE_WIDEMARGINSA4:
1900 ofs << "\\usepackage[widemargins]{a4}\n";
1905 if (params.use_geometry) {
1906 ofs << "\\usepackage{geometry}\n";
1908 ofs << "\\geometry{verbose";
1909 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1910 ofs << ",landscape";
1911 switch (params.papersize2) {
1912 case BufferParams::VM_PAPER_CUSTOM:
1913 if (!params.paperwidth.empty())
1914 ofs << ",paperwidth="
1915 << params.paperwidth;
1916 if (!params.paperheight.empty())
1917 ofs << ",paperheight="
1918 << params.paperheight;
1920 case BufferParams::VM_PAPER_USLETTER:
1921 ofs << ",letterpaper";
1923 case BufferParams::VM_PAPER_USLEGAL:
1924 ofs << ",legalpaper";
1926 case BufferParams::VM_PAPER_USEXECUTIVE:
1927 ofs << ",executivepaper";
1929 case BufferParams::VM_PAPER_A3:
1932 case BufferParams::VM_PAPER_A4:
1935 case BufferParams::VM_PAPER_A5:
1938 case BufferParams::VM_PAPER_B3:
1941 case BufferParams::VM_PAPER_B4:
1944 case BufferParams::VM_PAPER_B5:
1948 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1949 switch (lyxrc.default_papersize) {
1950 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1951 case BufferParams::PAPER_USLETTER:
1952 ofs << ",letterpaper";
1954 case BufferParams::PAPER_LEGALPAPER:
1955 ofs << ",legalpaper";
1957 case BufferParams::PAPER_EXECUTIVEPAPER:
1958 ofs << ",executivepaper";
1960 case BufferParams::PAPER_A3PAPER:
1963 case BufferParams::PAPER_A4PAPER:
1966 case BufferParams::PAPER_A5PAPER:
1969 case BufferParams::PAPER_B5PAPER:
1974 if (!params.topmargin.empty())
1975 ofs << ",tmargin=" << params.topmargin;
1976 if (!params.bottommargin.empty())
1977 ofs << ",bmargin=" << params.bottommargin;
1978 if (!params.leftmargin.empty())
1979 ofs << ",lmargin=" << params.leftmargin;
1980 if (!params.rightmargin.empty())
1981 ofs << ",rmargin=" << params.rightmargin;
1982 if (!params.headheight.empty())
1983 ofs << ",headheight=" << params.headheight;
1984 if (!params.headsep.empty())
1985 ofs << ",headsep=" << params.headsep;
1986 if (!params.footskip.empty())
1987 ofs << ",footskip=" << params.footskip;
1991 if (params.use_amsmath
1992 && !tclass.provides(LyXTextClass::amsmath)) {
1993 ofs << "\\usepackage{amsmath}\n";
1997 if (tokenPos(tclass.opt_pagestyle(),
1998 '|', params.pagestyle) >= 0) {
1999 if (params.pagestyle == "fancy") {
2000 ofs << "\\usepackage{fancyhdr}\n";
2003 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2007 // We try to load babel late, in case it interferes
2008 // with other packages.
2010 ofs << lyxrc.language_package << endl;
2014 if (params.secnumdepth != tclass.secnumdepth()) {
2015 ofs << "\\setcounter{secnumdepth}{"
2016 << params.secnumdepth
2020 if (params.tocdepth != tclass.tocdepth()) {
2021 ofs << "\\setcounter{tocdepth}{"
2027 if (params.paragraph_separation) {
2028 switch (params.defskip.kind()) {
2029 case VSpace::SMALLSKIP:
2030 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2032 case VSpace::MEDSKIP:
2033 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2035 case VSpace::BIGSKIP:
2036 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2038 case VSpace::LENGTH:
2039 ofs << "\\setlength\\parskip{"
2040 << params.defskip.length().asLatexString()
2043 default: // should never happen // Then delete it.
2044 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2049 ofs << "\\setlength\\parindent{0pt}\n";
2053 // Now insert the LyX specific LaTeX commands...
2055 // The optional packages;
2056 string preamble(features.getPackages());
2058 // this might be useful...
2059 preamble += "\n\\makeatletter\n";
2061 // Some macros LyX will need
2062 string tmppreamble(features.getMacros());
2064 if (!tmppreamble.empty()) {
2065 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2066 "LyX specific LaTeX commands.\n"
2067 + tmppreamble + '\n';
2070 // the text class specific preamble
2071 tmppreamble = features.getTClassPreamble();
2072 if (!tmppreamble.empty()) {
2073 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2074 "Textclass specific LaTeX commands.\n"
2075 + tmppreamble + '\n';
2078 /* the user-defined preamble */
2079 if (!params.preamble.empty()) {
2080 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2081 "User specified LaTeX commands.\n"
2082 + params.preamble + '\n';
2085 preamble += "\\makeatother\n";
2087 // Itemize bullet settings need to be last in case the user
2088 // defines their own bullets that use a package included
2089 // in the user-defined preamble -- ARRae
2090 // Actually it has to be done much later than that
2091 // since some packages like frenchb make modifications
2092 // at \begin{document} time -- JMarc
2094 for (int i = 0; i < 4; ++i) {
2095 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2096 if (bullets_def.empty())
2097 bullets_def="\\AtBeginDocument{\n";
2098 bullets_def += " \\renewcommand{\\labelitemi";
2100 // `i' is one less than the item to modify
2107 bullets_def += "ii";
2113 bullets_def += "}{" +
2114 params.user_defined_bullets[i].getText()
2119 if (!bullets_def.empty())
2120 preamble += bullets_def + "}\n\n";
2122 for (int j = countChar(preamble, '\n'); j-- ;) {
2129 ofs << "\\begin{document}\n";
2132 lyxerr.debug() << "preamble finished, now the body." << endl;
2133 if (!lyxrc.language_auto_begin && params.language != "default") {
2134 ofs << subst(lyxrc.language_command_begin, "$$lang",
2140 latexParagraphs(ofs, paragraph, 0, texrow);
2142 // add this just in case after all the paragraphs
2146 if (!lyxrc.language_auto_end && params.language != "default") {
2147 ofs << subst(lyxrc.language_command_end, "$$lang",
2154 ofs << "\\end{document}\n";
2157 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2159 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2163 // Just to be sure. (Asger)
2166 // tex_code_break_column's value is used to decide
2167 // if we are in batchmode or not (within mathed_write()
2168 // in math_write.C) so we must set it to a non-zero
2169 // value when we leave otherwise we save incorrect .lyx files.
2170 tex_code_break_column = lyxrc.ascii_linelen;
2174 lyxerr << "File was not closed properly." << endl;
2177 lyxerr.debug() << "Finished making latex file." << endl;
2182 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2184 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2185 LyXParagraph * endpar, TexRow & texrow) const
2187 bool was_title = false;
2188 bool already_title = false;
2189 std::ostringstream ftnote;
2194 while (par != endpar) {
2197 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2200 LyXLayout const & layout =
2201 textclasslist.Style(params.textclass,
2204 if (layout.intitle) {
2205 if (already_title) {
2206 lyxerr <<"Error in latexParagraphs: You"
2207 " should not mix title layouts"
2208 " with normal ones." << endl;
2211 } else if (was_title && !already_title) {
2212 ofs << "\\maketitle\n";
2214 already_title = true;
2217 // We are at depth 0 so we can just use
2218 // ordinary \footnote{} generation
2219 // flag this with ftcount
2221 if (layout.isEnvironment()
2222 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2223 par = par->TeXEnvironment(this, params, ofs, texrow
2225 ,ftnote, ft_texrow, ftcount
2229 par = par->TeXOnePar(this, params, ofs, texrow, false
2232 ftnote, ft_texrow, ftcount
2237 // Write out what we've generated...
2240 ofs << "\\addtocounter{footnote}{-"
2244 ofs << ftnote.str();
2245 texrow += ft_texrow;
2247 // The extra .c_str() is needed when we use
2248 // lyxstring instead of the STL string class.
2249 ftnote.str(string().c_str());
2254 // It might be that we only have a title in this document
2255 if (was_title && !already_title) {
2256 ofs << "\\maketitle\n";
2262 bool Buffer::isLatex() const
2264 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2268 bool Buffer::isLinuxDoc() const
2270 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2274 bool Buffer::isLiterate() const
2276 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2280 bool Buffer::isDocBook() const
2282 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2286 bool Buffer::isSGML() const
2288 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2289 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2293 void Buffer::sgmlOpenTag(ostream & os, int depth,
2294 string const & latexname) const
2296 os << string(depth, ' ') << "<" << latexname << ">\n";
2300 void Buffer::sgmlCloseTag(ostream & os, int depth,
2301 string const & latexname) const
2303 os << string(depth, ' ') << "</" << latexname << ">\n";
2307 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2309 LyXParagraph * par = paragraph;
2311 niceFile = nice; // this will be used by Insetincludes.
2313 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2314 string environment_stack[10];
2317 int depth = 0; // paragraph depth
2319 ofstream ofs(fname.c_str());
2322 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2326 LyXTextClass const & tclass =
2327 textclasslist.TextClass(params.textclass);
2329 LaTeXFeatures features(params, tclass.numLayouts());
2333 tex_code_break_column = lyxrc.ascii_linelen;
2335 //tex_code_break_column = 0;
2340 string sgml_includedfiles=features.getIncludedFiles();
2342 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2343 ofs << "<!doctype linuxdoc system>\n\n";
2345 ofs << "<!doctype linuxdoc system [ "
2346 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2349 if(params.options.empty())
2350 sgmlOpenTag(ofs, 0, top_element);
2352 string top = top_element;
2354 top += params.options;
2355 sgmlOpenTag(ofs, 0, top);
2359 ofs << "<!-- " << LYX_DOCVERSION
2360 << " created this file. For more info see http://www.lyx.org/"
2364 int desc_on = 0; // description mode
2365 LyXLayout const & style =
2366 textclasslist.Style(params.textclass,
2369 // treat <toc> as a special case for compatibility with old code
2370 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2371 Inset * inset = par->GetInset(0);
2372 Inset::Code lyx_code = inset->LyxCode();
2373 if (lyx_code == Inset::TOC_CODE){
2374 string const temp = "toc";
2375 sgmlOpenTag(ofs, depth, temp);
2379 linuxDocHandleFootnote(ofs, par, depth);
2385 // environment tag closing
2386 for (; depth > par->depth; --depth) {
2387 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2388 environment_stack[depth].erase();
2391 // write opening SGML tags
2392 switch (style.latextype) {
2393 case LATEX_PARAGRAPH:
2394 if(depth == par->depth
2395 && !environment_stack[depth].empty()) {
2396 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2397 environment_stack[depth].erase();
2403 sgmlOpenTag(ofs, depth, style.latexname());
2408 LinuxDocError(par, 0,
2409 _("Error : Wrong depth for"
2410 " LatexType Command.\n"));
2412 if (!environment_stack[depth].empty()){
2413 sgmlCloseTag(ofs, depth,
2414 environment_stack[depth]);
2418 environment_stack[depth].erase();
2419 sgmlOpenTag(ofs, depth, style.latexname());
2422 case LATEX_ENVIRONMENT:
2423 case LATEX_ITEM_ENVIRONMENT:
2424 if (depth == par->depth
2425 && environment_stack[depth] != style.latexname()
2426 && !environment_stack[depth].empty()) {
2428 sgmlCloseTag(ofs, depth,
2429 environment_stack[depth]);
2430 environment_stack[depth].erase();
2432 if (depth < par->depth) {
2434 environment_stack[depth].erase();
2436 if (environment_stack[depth] != style.latexname()) {
2438 string const temp = "p";
2439 sgmlOpenTag(ofs, depth, temp);
2441 environment_stack[depth] = style.latexname();
2442 sgmlOpenTag(ofs, depth,
2443 environment_stack[depth]);
2445 if(style.latextype == LATEX_ENVIRONMENT) break;
2447 desc_on = (style.labeltype == LABEL_MANUAL);
2454 sgmlOpenTag(ofs, depth + 1, item_name);
2457 sgmlOpenTag(ofs, depth, style.latexname());
2464 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2468 linuxDocHandleFootnote(ofs, par, depth);
2470 while(par && par->IsDummy());
2474 // write closing SGML tags
2475 switch(style.latextype) {
2477 case LATEX_ENVIRONMENT:
2478 case LATEX_ITEM_ENVIRONMENT:
2481 sgmlCloseTag(ofs, depth, style.latexname());
2487 for(; depth > 0; --depth)
2488 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2490 if(!environment_stack[depth].empty())
2491 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2495 sgmlCloseTag(ofs, 0, top_element);
2499 // How to check for successful close
2504 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2507 string const tag = "footnote";
2509 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2510 sgmlOpenTag(os, depth + 1, tag);
2511 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2512 sgmlCloseTag(os, depth + 1, tag);
2519 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2520 int const depth, int desc_on,
2521 LyXParagraph * & par)
2523 LyXParagraph * tpar = par;
2526 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2528 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2532 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2533 "Caption").second) {
2534 sgmlOpenTag(os, depth + 1, inner_tag);
2536 SimpleDocBookOnePar(os, extra_par, tpar,
2537 desc_on, depth + 2);
2538 sgmlCloseTag(os, depth+1, inner_tag);
2539 if(!extra_par.empty())
2546 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2549 string tag, inner_tag;
2550 string tmp_par, extra_par;
2551 bool inner_span = false;
2554 // Someone should give this enum a proper name (Lgb)
2562 SOME_ENUM last = NO_ONE;
2563 SOME_ENUM present = FOOTNOTE_LIKE;
2565 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2566 if (last == present) {
2568 if (!tmp_par.empty()) {
2571 sgmlCloseTag(os, depth + 1, inner_tag);
2572 sgmlOpenTag(os, depth + 1, inner_tag);
2579 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2581 if (!extra_par.empty()) os << extra_par;
2582 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2585 switch (par->footnotekind) {
2586 case LyXParagraph::FOOTNOTE:
2587 case LyXParagraph::ALGORITHM:
2590 present = FOOTNOTE_LIKE;
2593 case LyXParagraph::MARGIN:
2596 present = MARGIN_LIKE;
2599 case LyXParagraph::FIG:
2600 case LyXParagraph::WIDE_FIG:
2602 inner_tag = "title";
2606 case LyXParagraph::TAB:
2607 case LyXParagraph::WIDE_TAB:
2609 inner_tag = "title";
2614 sgmlOpenTag(os, depth, tag);
2615 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2616 DocBookHandleCaption(os, inner_tag, depth,
2620 sgmlOpenTag(os, depth + 1, inner_tag);
2623 // ignore all caption here, we processed them above!!!
2624 if (par->layout != textclasslist
2625 .NumberOfLayout(params.textclass,
2626 "Caption").second) {
2627 std::ostringstream ost;
2628 SimpleDocBookOnePar(ost, extra_par, par,
2629 desc_on, depth + 2);
2630 tmp_par += ost.str().c_str();
2632 tmp_par = frontStrip(strip(tmp_par));
2638 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2639 if(!extra_par.empty()) os << extra_par;
2640 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2645 // push a tag in a style stack
2646 void Buffer::push_tag(ostream & os, string const & tag,
2647 int & pos, char stack[5][3])
2649 #warning Use a real stack! (Lgb)
2650 // pop all previous tags
2651 for (int j = pos; j >= 0; --j)
2652 os << "</" << stack[j] << ">";
2655 sprintf(stack[++pos], "%s", tag.c_str());
2658 for (int i = 0; i <= pos; ++i)
2659 os << "<" << stack[i] << ">";
2663 void Buffer::pop_tag(ostream & os, string const & tag,
2664 int & pos, char stack[5][3])
2666 #ifdef WITH_WARNINGS
2667 #warning Use a real stack! (Lgb)
2669 // Please, Lars, do not remove the global variable. I already
2670 // had to reintroduce it twice! (JMarc)
2673 // pop all tags till specified one
2674 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2675 os << "</" << stack[j] << ">";
2678 os << "</" << tag << ">";
2680 // push all tags, but the specified one
2681 for (j = j + 1; j <= pos; ++j) {
2682 os << "<" << stack[j] << ">";
2683 strcpy(stack[j-1], stack[j]);
2689 // Handle internal paragraph parsing -- layout already processed.
2691 // checks, if newcol chars should be put into this line
2692 // writes newline, if necessary.
2694 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2695 const unsigned int newcol)
2698 if (colcount > lyxrc.ascii_linelen) {
2700 colcount = newcol; // assume write after this call
2705 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2706 int desc_on, int const /*depth*/)
2711 LyXParagraph::size_type main_body;
2713 LyXLayout const & style = textclasslist.Style(params.textclass,
2716 char family_type = 0; // family font flag
2717 bool is_bold = false; // series font flag
2718 char shape_type = 0; // shape font flag
2719 bool is_em = false; // emphasis (italic) font flag
2721 int stack_num = -1; // style stack position
2722 // Can this be rewritten to use a std::stack, please. (Lgb)
2723 char stack[5][3]; // style stack
2724 unsigned int char_line_count = 5; // Heuristic choice ;-)
2726 if (style.labeltype != LABEL_MANUAL)
2729 main_body = par->BeginningOfMainBody();
2731 // gets paragraph main font
2733 font1 = style.labelfont;
2738 // parsing main loop
2739 for (LyXParagraph::size_type i = 0;
2740 i < par->size(); ++i) {
2752 LyXFont const font2 = par->getFont(params, i);
2754 if (font1.family() != font2.family()) {
2755 switch(family_type) {
2757 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2758 push_tag(os, "tt", stack_num, stack);
2761 else if (font2.family() == LyXFont::SANS_FAMILY) {
2762 push_tag(os, "sf", stack_num, stack);
2767 pop_tag(os, "tt", stack_num, stack);
2768 if (font2.family() == LyXFont::SANS_FAMILY) {
2769 push_tag(os, "sf", stack_num, stack);
2776 pop_tag(os, "sf", stack_num, stack);
2777 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2778 push_tag(os, "tt", stack_num, stack);
2787 if (font1.series() != font2.series()) {
2788 if (font2.series() == LyXFont::BOLD_SERIES) {
2789 push_tag(os, "bf", stack_num, stack);
2791 } else if (is_bold) {
2792 pop_tag(os, "bf", stack_num, stack);
2797 // handle italic and slanted fonts
2798 if (font1.shape() != font2.shape()) {
2799 switch(shape_type) {
2801 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2802 push_tag(os, "it", stack_num, stack);
2804 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2805 push_tag(os, "sl", stack_num, stack);
2810 pop_tag(os, "it", stack_num, stack);
2811 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2812 push_tag(os, "sl", stack_num, stack);
2819 pop_tag(os, "sl", stack_num, stack);
2820 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2821 push_tag(os, "it", stack_num, stack);
2829 if (font1.emph() != font2.emph()) {
2830 if (font2.emph() == LyXFont::ON) {
2831 push_tag(os, "em", stack_num, stack);
2834 pop_tag(os, "em", stack_num, stack);
2839 c = par->GetChar(i);
2841 if (c == LyXParagraph::META_INSET) {
2842 inset = par->GetInset(i);
2843 inset->Linuxdoc(this, os);
2846 if (font2.latex() == LyXFont::ON) {
2847 // "TeX"-Mode on == > SGML-Mode on.
2849 os << c; // see LaTeX-Generation...
2853 if (par->linuxDocConvertChar(c, sgml_string)
2854 && !style.free_spacing) { // in freespacing
2856 // non-breaking characters
2860 linux_doc_line_break(os, char_line_count, 6);
2864 linux_doc_line_break(os, char_line_count, 1);
2869 char_line_count += sgml_string.length();
2875 // needed if there is an optional argument but no contents
2876 if (main_body > 0 && main_body == par->size()) {
2880 // pop all defined Styles
2881 for (j = stack_num; j >= 0; --j) {
2882 linux_doc_line_break(os,
2884 3 + strlen(stack[j]));
2885 os << "</" << stack[j] << ">";
2888 // resets description flag correctly
2891 // <tag> not closed...
2892 linux_doc_line_break(os, char_line_count, 6);
2896 // fprintf(file, "</p>");
2902 // Print an error message.
2903 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2904 string const & message)
2906 // insert an error marker in text
2907 InsetError * new_inset = new InsetError(message);
2908 par->InsertInset(pos, new_inset);
2911 // This constant defines the maximum number of
2912 // environment layouts that can be nesteded.
2913 // The same applies for command layouts.
2914 // These values should be more than enough.
2915 // José Matos (1999/07/22)
2917 enum { MAX_NEST_LEVEL = 25};
2919 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2921 LyXParagraph * par = paragraph;
2923 niceFile = nice; // this will be used by Insetincludes.
2925 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2926 // Please use a real stack.
2927 string environment_stack[MAX_NEST_LEVEL];
2928 string environment_inner[MAX_NEST_LEVEL];
2929 // Please use a real stack.
2930 string command_stack[MAX_NEST_LEVEL];
2931 bool command_flag= false;
2932 int command_depth= 0, command_base= 0, cmd_depth= 0;
2934 string item_name, command_name;
2935 string c_depth, c_params, tmps;
2937 int depth = 0; // paragraph depth
2938 LyXTextClass const & tclass =
2939 textclasslist.TextClass(params.textclass);
2941 LaTeXFeatures features(params, tclass.numLayouts());
2945 tex_code_break_column = lyxrc.ascii_linelen;
2947 //tex_code_break_column = 0;
2949 ofstream ofs(fname.c_str());
2951 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2958 string sgml_includedfiles=features.getIncludedFiles();
2960 ofs << "<!doctype " << top_element
2961 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2963 if (params.preamble.empty() && sgml_includedfiles.empty())
2966 ofs << "\n [ " << params.preamble
2967 << sgml_includedfiles << " \n]>\n\n";
2969 if(params.options.empty())
2970 sgmlOpenTag(ofs, 0, top_element);
2972 string top = top_element;
2974 top += params.options;
2975 sgmlOpenTag(ofs, 0, top);
2979 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2980 << "\n See http://www.lyx.org/ for more information -->\n";
2983 int desc_on = 0; // description mode
2984 LyXLayout const & style =
2985 textclasslist.Style(params.textclass,
2988 // environment tag closing
2989 for( ; depth > par->depth; --depth) {
2990 if(environment_inner[depth] != "!-- --") {
2991 item_name= "listitem";
2992 sgmlCloseTag(ofs, command_depth + depth,
2994 if( environment_inner[depth] == "varlistentry")
2995 sgmlCloseTag(ofs, depth+command_depth,
2996 environment_inner[depth]);
2998 sgmlCloseTag(ofs, depth + command_depth,
2999 environment_stack[depth]);
3000 environment_stack[depth].erase();
3001 environment_inner[depth].erase();
3004 if(depth == par->depth
3005 && environment_stack[depth] != style.latexname()
3006 && !environment_stack[depth].empty()) {
3007 if(environment_inner[depth] != "!-- --") {
3008 item_name= "listitem";
3009 sgmlCloseTag(ofs, command_depth+depth,
3011 if( environment_inner[depth] == "varlistentry")
3013 depth + command_depth,
3014 environment_inner[depth]);
3017 sgmlCloseTag(ofs, depth + command_depth,
3018 environment_stack[depth]);
3020 environment_stack[depth].erase();
3021 environment_inner[depth].erase();
3024 // Write opening SGML tags.
3025 switch(style.latextype) {
3026 case LATEX_PARAGRAPH:
3027 if(style.latexname() != "dummy")
3028 sgmlOpenTag(ofs, depth+command_depth,
3034 LinuxDocError(par, 0,
3035 _("Error : Wrong depth for "
3036 "LatexType Command.\n"));
3038 command_name = style.latexname();
3040 tmps = style.latexparam();
3041 c_params = split(tmps, c_depth,'|');
3043 cmd_depth= lyx::atoi(c_depth);
3046 if(cmd_depth<command_base) {
3047 for(int j = command_depth;
3048 j >= command_base; --j)
3049 if(!command_stack[j].empty())
3050 sgmlCloseTag(ofs, j, command_stack[j]);
3051 command_depth= command_base= cmd_depth;
3052 } else if(cmd_depth <= command_depth) {
3053 for(int j = command_depth;
3054 j >= cmd_depth; --j)
3056 if(!command_stack[j].empty())
3057 sgmlCloseTag(ofs, j, command_stack[j]);
3058 command_depth= cmd_depth;
3060 command_depth= cmd_depth;
3062 command_depth = command_base = cmd_depth;
3063 command_flag = true;
3065 command_stack[command_depth]= command_name;
3067 // treat label as a special case for
3068 // more WYSIWYM handling.
3069 if (par->GetChar(0) == LyXParagraph::META_INSET) {
3070 Inset * inset = par->GetInset(0);
3071 Inset::Code lyx_code = inset->LyxCode();
3072 if (lyx_code == Inset::LABEL_CODE){
3073 command_name += " id=\"";
3074 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3075 command_name += "\"";
3080 sgmlOpenTag(ofs, depth + command_depth, command_name);
3081 item_name = "title";
3082 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3085 case LATEX_ENVIRONMENT:
3086 case LATEX_ITEM_ENVIRONMENT:
3087 if (depth < par->depth) {
3089 environment_stack[depth].erase();
3092 if (environment_stack[depth] != style.latexname()) {
3093 environment_stack[depth] = style.latexname();
3094 environment_inner[depth] = "!-- --";
3095 sgmlOpenTag(ofs, depth + command_depth,
3096 environment_stack[depth]);
3098 if(environment_inner[depth] != "!-- --") {
3099 item_name= "listitem";
3101 command_depth + depth,
3103 if (environment_inner[depth] == "varlistentry")
3105 depth + command_depth,
3106 environment_inner[depth]);
3110 if(style.latextype == LATEX_ENVIRONMENT) {
3111 if(!style.latexparam().empty())
3112 sgmlOpenTag(ofs, depth + command_depth,
3113 style.latexparam());
3117 desc_on = (style.labeltype == LABEL_MANUAL);
3120 environment_inner[depth]= "varlistentry";
3122 environment_inner[depth]= "listitem";
3124 sgmlOpenTag(ofs, depth + 1 + command_depth,
3125 environment_inner[depth]);
3129 sgmlOpenTag(ofs, depth + 1 + command_depth,
3133 sgmlOpenTag(ofs, depth + 1 + command_depth,
3138 sgmlOpenTag(ofs, depth + command_depth,
3147 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3148 depth + 1 + command_depth);
3151 DocBookHandleFootnote(ofs, par,
3152 depth + 1 + command_depth);
3154 while(par && par->IsDummy());
3157 // write closing SGML tags
3158 switch(style.latextype) {
3161 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3163 case LATEX_ENVIRONMENT:
3164 if(!style.latexparam().empty())
3165 sgmlCloseTag(ofs, depth + command_depth,
3166 style.latexparam());
3168 case LATEX_ITEM_ENVIRONMENT:
3169 if(desc_on == 1) break;
3171 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3173 case LATEX_PARAGRAPH:
3174 if(style.latexname() != "dummy")
3175 sgmlCloseTag(ofs, depth + command_depth,
3179 sgmlCloseTag(ofs, depth + command_depth,
3186 for(; depth >= 0; --depth) {
3187 if(!environment_stack[depth].empty()) {
3188 if(environment_inner[depth] != "!-- --") {
3189 item_name= "listitem";
3190 sgmlCloseTag(ofs, command_depth + depth,
3192 if( environment_inner[depth] == "varlistentry")
3193 sgmlCloseTag(ofs, depth + command_depth,
3194 environment_inner[depth]);
3197 sgmlCloseTag(ofs, depth + command_depth,
3198 environment_stack[depth]);
3202 for(int j = command_depth; j >= command_base; --j)
3203 if(!command_stack[j].empty())
3204 sgmlCloseTag(ofs, j, command_stack[j]);
3208 sgmlCloseTag(ofs, 0, top_element);
3212 // How to check for successful close
3216 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3217 LyXParagraph * par, int & desc_on,
3220 bool emph_flag = false;
3222 LyXLayout const & style = textclasslist.Style(params.textclass,
3225 LyXParagraph::size_type main_body;
3226 if (style.labeltype != LABEL_MANUAL)
3229 main_body = par->BeginningOfMainBody();
3231 // gets paragraph main font
3232 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3234 int char_line_count = depth;
3235 if(!style.free_spacing)
3236 for (int j = 0; j < depth; ++j)
3239 // parsing main loop
3240 for (LyXParagraph::size_type i = 0;
3241 i < par->size(); ++i) {
3242 LyXFont font2 = par->getFont(params, i);
3244 // handle <emphasis> tag
3245 if (font1.emph() != font2.emph() && i) {
3246 if (font2.emph() == LyXFont::ON) {
3250 os << "</emphasis>";
3255 char c = par->GetChar(i);
3257 if (c == LyXParagraph::META_INSET) {
3258 Inset * inset = par->GetInset(i);
3259 std::ostringstream ost;
3260 inset->DocBook(this, ost);
3261 string tmp_out = ost.str().c_str();
3264 // This code needs some explanation:
3265 // Two insets are treated specially
3266 // label if it is the first element in a command paragraph
3268 // graphics inside tables or figure floats can't go on
3269 // title (the equivalente in latex for this case is caption
3270 // and title should come first
3273 if(desc_on!= 3 || i!= 0) {
3274 if(!tmp_out.empty() && tmp_out[0] == '@') {
3276 extra += frontStrip(tmp_out, '@');
3278 os << frontStrip(tmp_out, '@');
3283 } else if (font2.latex() == LyXFont::ON) {
3284 // "TeX"-Mode on ==> SGML-Mode on.
3290 if (par->linuxDocConvertChar(c, sgml_string)
3291 && !style.free_spacing) { // in freespacing
3293 // non-breaking characters
3297 os << "\n</term><listitem><para>";
3309 // needed if there is an optional argument but no contents
3310 if (main_body > 0 && main_body == par->size()) {
3314 os << "</emphasis>";
3317 // resets description flag correctly
3320 // <term> not closed...
3328 int Buffer::runLiterate()
3330 if (!users->text) return 0;
3332 ProhibitInput(users);
3334 // get LaTeX-Filename
3335 string name = getLatexName();
3336 // get Literate-Filename
3337 string lit_name = OnlyFilename(ChangeExtension (getLatexName(),
3338 lyxrc.literate_extension));
3340 string path = OnlyPath(filename);
3342 string org_path = path;
3343 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3347 Path p(path); // path to Literate file
3348 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3350 // Remove all error insets
3351 bool removedErrorInsets = users->removeAutoInsets();
3353 // generate the Literate file if necessary
3354 makeLaTeXFile(lit_name, org_path, false);
3356 string latex_command = lyxrc.pdf_mode ?
3357 lyxrc.pdflatex_command : lyxrc.latex_command;
3358 Literate literate(latex_command, name, filepath,
3360 lyxrc.literate_command, lyxrc.literate_error_filter,
3361 lyxrc.build_command, lyxrc.build_error_filter);
3363 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3365 // check return value from literate.weave().
3366 if ((res & Literate::NO_LOGFILE)) {
3367 WriteAlert(_("Literate command did not work!"),
3368 _("Missing log file:"), name);
3369 } else if ((res & Literate::ERRORS)) {
3370 users->owner()->getMiniBuffer()->Set(_("Done"));
3371 // Insert all errors as errors boxes
3372 users->insertErrors(terr);
3374 // Dvi should also be kept dirty if the latex run
3375 // ends up with errors. However it should be possible
3376 // to view a dirty dvi too.
3378 //no errors or any other things to think about so:
3379 users->owner()->getMiniBuffer()->Set(_("Done"));
3382 // if we removed error insets before we ran LaTeX or if we inserted
3383 // error insets after we ran LaTeX this must be run:
3384 if (removedErrorInsets || (res & Literate::ERRORS)){
3387 //users->updateScrollbar();
3391 return literate.getNumErrors();
3395 int Buffer::buildProgram()
3397 if (!users->text) return 0;
3399 ProhibitInput(users);
3401 // get LaTeX-Filename
3402 string name = getLatexName();
3403 // get Literate-Filename
3404 string lit_name = OnlyFilename(ChangeExtension(getLatexName(),
3405 lyxrc.literate_extension));
3407 string path = OnlyPath(filename);
3409 string org_path = path;
3410 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3414 Path p(path); // path to Literate file
3415 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3417 // Remove all error insets
3418 bool removedErrorInsets = users->removeAutoInsets();
3420 // generate the LaTeX file if necessary
3421 if (!isNwClean() || removedErrorInsets) {
3422 makeLaTeXFile(lit_name, org_path, false);
3426 string latex_command = lyxrc.pdf_mode ?
3427 lyxrc.pdflatex_command : lyxrc.latex_command;
3428 Literate literate(latex_command, name, filepath,
3430 lyxrc.literate_command, lyxrc.literate_error_filter,
3431 lyxrc.build_command, lyxrc.build_error_filter);
3433 int const res = literate.build(terr, users->owner()->getMiniBuffer());
3435 // check return value from literate.build().
3436 if ((res & Literate::NO_LOGFILE)) {
3437 WriteAlert(_("Build did not work!"),
3438 _("Missing log file:"), name);
3439 } else if ((res & Literate::ERRORS)) {
3440 users->owner()->getMiniBuffer()->Set(_("Done"));
3441 // Insert all errors as errors boxes
3442 users->insertErrors(terr);
3444 // Literate files should also be kept dirty if the literate
3445 // command run ends up with errors.
3447 //no errors or any other things to think about so:
3448 users->owner()->getMiniBuffer()->Set(_("Done"));
3452 // if we removed error insets before we ran Literate/Build or
3453 // if we inserted error insets after we ran Literate/Build this
3455 if (removedErrorInsets || (res & Literate::ERRORS)){
3458 //users->updateScrollbar();
3462 return literate.getNumErrors();
3466 // This should be enabled when the Chktex class is implemented. (Asger)
3467 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3468 // Other flags: -wall -v0 -x
3469 int Buffer::runChktex()
3471 if (!users->text) return 0;
3473 ProhibitInput(users);
3475 // get LaTeX-Filename
3476 string const name = getLatexName();
3477 string path = OnlyPath(filename);
3479 string const org_path = path;
3480 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3484 Path p(path); // path to LaTeX file
3485 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3487 // Remove all error insets
3488 bool const removedErrorInsets = users->removeAutoInsets();
3490 // Generate the LaTeX file if neccessary
3491 makeLaTeXFile(name, org_path, false);
3494 Chktex chktex(lyxrc.chktex_command, name, filepath);
3495 int res = chktex.run(terr); // run chktex
3498 WriteAlert(_("chktex did not work!"),
3499 _("Could not run with file:"), name);
3500 } else if (res > 0) {
3501 // Insert all errors as errors boxes
3502 users->insertErrors(terr);
3505 // if we removed error insets before we ran chktex or if we inserted
3506 // error insets after we ran chktex, this must be run:
3507 if (removedErrorInsets || res){
3510 //users->updateScrollbar();
3518 void Buffer::validate(LaTeXFeatures & features) const
3520 LyXParagraph * par = paragraph;
3521 LyXTextClass const & tclass =
3522 textclasslist.TextClass(params.textclass);
3524 // AMS Style is at document level
3526 features.amsstyle = (params.use_amsmath ||
3527 tclass.provides(LyXTextClass::amsmath));
3530 // We don't use "lyxerr.debug" because of speed. (Asger)
3531 if (lyxerr.debugging(Debug::LATEX))
3532 lyxerr << "Paragraph: " << par << endl;
3534 // Now just follow the list of paragraphs and run
3535 // validate on each of them.
3536 par->validate(features);
3538 // and then the next paragraph
3542 // the bullet shapes are buffer level not paragraph level
3543 // so they are tested here
3544 for (int i = 0; i < 4; ++i) {
3545 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3546 int const font = params.user_defined_bullets[i].getFont();
3548 int const c = params
3549 .user_defined_bullets[i]
3556 features.latexsym = true;
3558 } else if (font == 1) {
3559 features.amssymb = true;
3560 } else if ((font >= 2 && font <= 5)) {
3561 features.pifont = true;
3566 if (lyxerr.debugging(Debug::LATEX)) {
3567 features.showStruct();
3572 void Buffer::setPaperStuff()
3574 params.papersize = BufferParams::PAPER_DEFAULT;
3575 char const c1 = params.paperpackage;
3576 if (c1 == BufferParams::PACKAGE_NONE) {
3577 char const c2 = params.papersize2;
3578 if (c2 == BufferParams::VM_PAPER_USLETTER)
3579 params.papersize = BufferParams::PAPER_USLETTER;
3580 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3581 params.papersize = BufferParams::PAPER_LEGALPAPER;
3582 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3583 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3584 else if (c2 == BufferParams::VM_PAPER_A3)
3585 params.papersize = BufferParams::PAPER_A3PAPER;
3586 else if (c2 == BufferParams::VM_PAPER_A4)
3587 params.papersize = BufferParams::PAPER_A4PAPER;
3588 else if (c2 == BufferParams::VM_PAPER_A5)
3589 params.papersize = BufferParams::PAPER_A5PAPER;
3590 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3591 (c2 == BufferParams::VM_PAPER_B5))
3592 params.papersize = BufferParams::PAPER_B5PAPER;
3593 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3594 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3595 params.papersize = BufferParams::PAPER_A4PAPER;
3599 // This function should be in Buffer because it's a buffer's property (ale)
3600 string const Buffer::getIncludeonlyList(char delim)
3603 for (inset_iterator it = inset_iterator_begin();
3604 it != inset_iterator_end(); ++it) {
3605 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3606 InsetInclude * insetinc =
3607 static_cast<InsetInclude *>(*it);
3608 if (insetinc->isInclude()
3609 && insetinc->isNoLoad()) {
3612 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3616 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3621 vector<string> const Buffer::getLabelList()
3623 /// if this is a child document and the parent is already loaded
3624 /// Use the parent's list instead [ale990407]
3625 if (!params.parentname.empty()
3626 && bufferlist.exists(params.parentname)) {
3627 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3629 return tmp->getLabelList();
3632 vector<string> label_list;
3633 for (inset_iterator it = inset_iterator_begin();
3634 it != inset_iterator_end(); ++it) {
3635 vector<string> const l = (*it)->getLabelList();
3636 label_list.insert(label_list.end(), l.begin(), l.end());
3642 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
3644 vector<vector<TocItem> > l(4);
3645 LyXParagraph * par = paragraph;
3648 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3649 if (textclasslist.Style(params.textclass,
3650 par->GetLayout()).labeltype
3651 == LABEL_SENSITIVE) {
3655 tmp.str = par->String(this, false);
3656 switch (par->footnotekind) {
3657 case LyXParagraph::FIG:
3658 case LyXParagraph::WIDE_FIG:
3659 l[TOC_LOF].push_back(tmp);
3661 case LyXParagraph::TAB:
3662 case LyXParagraph::WIDE_TAB:
3663 l[TOC_LOT].push_back(tmp);
3665 case LyXParagraph::ALGORITHM:
3666 l[TOC_LOA].push_back(tmp);
3668 case LyXParagraph::FOOTNOTE:
3669 case LyXParagraph::MARGIN:
3673 } else if (!par->IsDummy()) {
3675 char const labeltype =
3676 textclasslist.Style(params.textclass,
3677 par->GetLayout()).labeltype;
3679 if (labeltype >= LABEL_COUNTER_CHAPTER
3680 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3681 // insert this into the table of contents
3686 textclasslist.TextClass(params.textclass).maxcounter());
3687 tmp.str = par->String(this, true);
3688 l[TOC_TOC].push_back(tmp);
3699 // This is also a buffer property (ale)
3700 vector<pair<string,string> > const Buffer::getBibkeyList()
3702 /// if this is a child document and the parent is already loaded
3703 /// Use the parent's list instead [ale990412]
3704 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3705 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3707 return tmp->getBibkeyList();
3710 vector<pair<string, string> > keys;
3711 LyXParagraph * par = paragraph;
3714 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3715 par->String(this, false)));
3719 // Might be either using bibtex or a child has bibliography
3721 for (inset_iterator it = inset_iterator_begin();
3722 it != inset_iterator_end(); ++it) {
3723 // Search for Bibtex or Include inset
3724 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3725 vector<pair<string,string> > tmp =
3726 static_cast<InsetBibtex*>(*it)->getKeys();
3727 keys.insert(keys.end(), tmp.begin(), tmp.end());
3728 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3729 vector<pair<string,string> > const tmp =
3730 static_cast<InsetInclude*>(*it)->getKeys();
3731 keys.insert(keys.end(), tmp.begin(), tmp.end());
3740 bool Buffer::isDepClean(string const & name) const
3742 DEPCLEAN * item = dep_clean;
3743 while (item && item->master != name)
3745 if (!item) return true;
3750 void Buffer::markDepClean(string const & name)
3753 dep_clean = new DEPCLEAN;
3754 dep_clean->clean = true;
3755 dep_clean->master = name;
3756 dep_clean->next = 0;
3758 DEPCLEAN * item = dep_clean;
3759 while (item && item->master != name)
3764 item = new DEPCLEAN;
3766 item->master = name;
3773 bool Buffer::Dispatch(string const & command)
3775 // Split command string into command and argument
3777 string line = frontStrip(command);
3778 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3780 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3784 bool Buffer::Dispatch(int action, string const & argument)
3786 bool dispatched = true;
3789 Exporter::Export(this, argument, false);
3799 void Buffer::resize()
3801 /// resize the BufferViews!
3807 void Buffer::resizeInsets(BufferView * bv)
3809 /// then remove all LyXText in text-insets
3810 LyXParagraph * par = paragraph;
3811 for(; par; par = par->next) {
3812 par->resizeInsetsLyXText(bv);
3816 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3819 LyXParagraph * par = paragraph;
3821 par->ChangeLanguage(params, from, to);
3827 bool Buffer::isMultiLingual()
3829 LyXParagraph * par = paragraph;
3831 if (par->isMultiLingual(params))
3839 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3840 LyXParagraph::size_type pos)
3843 it = par->InsetIterator(pos);
3844 if (it == par->inset_iterator_end()) {
3851 void Buffer::inset_iterator::SetParagraph()
3854 it = par->inset_iterator_begin();
3855 if (it != par->inset_iterator_end())
3860 // We maintain an invariant that whenever par = 0 then it = 0