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 * ======================================================
26 #include <sys/types.h>
36 #pragma implementation
40 #include "bufferlist.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
46 #include "tex-strings.h"
48 #include "bufferview_funcs.h"
51 #include "mathed/formulamacro.h"
52 #include "insets/lyxinset.h"
53 #include "insets/inseterror.h"
54 #include "insets/insetlabel.h"
55 #include "insets/insetref.h"
56 #include "insets/inseturl.h"
57 #include "insets/insetinfo.h"
58 #include "insets/insetquotes.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetbib.h"
61 #include "insets/insetcite.h"
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h"
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/figinset.h"
69 #include "insets/insettext.h"
70 #include "insets/insetert.h"
71 #include "insets/insetgraphics.h"
72 #include "insets/insetfoot.h"
73 #include "insets/insetmarginal.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insetlist.h"
77 #include "insets/insettabular.h"
78 #include "insets/insettheorem.h"
79 #include "insets/insetcaption.h"
80 #include "insets/insetfloatlist.h"
81 #include "support/filetools.h"
82 #include "support/path.h"
87 #include "LaTeXFeatures.h"
88 #include "support/syscall.h"
89 #include "support/lyxlib.h"
90 #include "support/FileInfo.h"
91 #include "support/lyxmanip.h"
95 #include "lyx_gui_misc.h" // WarnReadonly()
96 #include "frontends/Dialogs.h"
100 #include "converter.h"
102 using std::stringstream;
111 using std::make_pair;
119 // all these externs should eventually be removed.
120 extern BufferList bufferlist;
122 extern LyXAction lyxaction;
126 const int LYX_FORMAT = 218;
130 extern int tex_code_break_column;
133 Buffer::Buffer(string const & file, bool ronly)
135 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
137 filepath = OnlyPath(file);
146 if (read_only || (lyxrc.use_tempdir)) {
147 tmppath = CreateBufferTmpDir();
148 } else tmppath.erase();
154 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
155 // here the buffer should take care that it is
156 // saved properly, before it goes into the void.
158 // make sure that views using this buffer
163 if (!tmppath.empty()) {
164 DestroyBufferTmpDir(tmppath);
167 LyXParagraph * par = paragraph;
168 LyXParagraph * tmppar;
170 tmppar = par->next();
178 string const Buffer::getLatexName(bool no_path) const
181 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
184 return ChangeExtension(MakeLatexName(filename),
189 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
191 string const filename = getLatexName(false);
193 if (filename.empty())
194 return make_pair(Buffer::latexlog, string());
196 string path = OnlyPath(filename);
198 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
201 string const fname = AddName(path,
202 OnlyFilename(ChangeExtension(filename,
205 AddName(path, OnlyFilename(
206 ChangeExtension(filename,
207 formats.Extension("literate") + ".out")));
209 // If no Latex log or Build log is newer, show Build log
211 FileInfo const f_fi(fname);
212 FileInfo const b_fi(bname);
215 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
216 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
217 return make_pair(Buffer::buildlog, bname);
219 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
220 return make_pair(Buffer::latexlog, fname);
224 void Buffer::setReadonly(bool flag)
226 if (read_only != flag) {
229 users->owner()->getDialogs()->updateBufferDependent(false);
232 WarnReadonly(filename);
237 bool Buffer::saveParamsAsDefaults() // const
239 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
241 Buffer defaults = Buffer(fname);
243 // Use the current buffer's parameters as default
244 defaults.params = params;
246 // add an empty paragraph. Is this enough?
247 defaults.paragraph = new LyXParagraph;
249 return defaults.writeFile(defaults.filename, false);
253 /// Update window titles of all users
254 // Should work on a list
255 void Buffer::updateTitles() const
257 if (users) users->owner()->updateWindowTitle();
261 /// Reset autosave timer of all users
262 // Should work on a list
263 void Buffer::resetAutosaveTimers() const
265 if (users) users->owner()->resetAutosaveTimer();
269 void Buffer::setFileName(string const & newfile)
271 filename = MakeAbsPath(newfile);
272 filepath = OnlyPath(filename);
273 setReadonly(IsFileWriteable(filename) == 0);
278 // candidate for move to BufferView
279 // (at least some parts in the beginning of the func)
282 // changed to be public and have one parameter
283 // if par = 0 normal behavior
284 // else insert behavior
285 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
286 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
289 char depth = 0; // signed or unsigned?
290 bool the_end_read = false;
292 LyXParagraph * return_par = 0;
293 LyXFont font(LyXFont::ALL_INHERIT, params.language);
294 if (file_format < 216 && params.language->lang() == "hebrew")
295 font.setLanguage(default_language);
296 // If we are inserting, we cheat and get a token in advance
297 bool has_token = false;
301 par = new LyXParagraph;
303 users->text->BreakParagraph(users);
304 return_par = users->text->FirstParagraph();
307 // We don't want to adopt the parameters from the
308 // document we insert, so we skip until the text begins:
311 pretoken = lex.GetString();
312 if (pretoken == "\\layout") {
324 pretoken = lex.GetString();
327 if (pretoken.empty()) continue;
330 parseSingleLyXformat2Token(lex, par, return_par,
331 pretoken, pos, depth,
339 paragraph = return_par;
345 // We'll remove this later. (Lgb)
348 string last_inset_read;
354 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
355 LyXParagraph *& return_par,
356 string const & token, int & pos,
357 char & depth, LyXFont & font
360 bool the_end_read = false;
361 #ifndef NO_PEXTRA_REALLY
362 // This is super temporary but is needed to get the compability
363 // mode for minipages work correctly together with new tabulars.
364 static int call_depth = 0;
366 bool checkminipage = false;
367 static LyXParagraph * minipar = 0;
368 static LyXParagraph * parBeforeMinipage = 0;
371 if (token[0] != '\\') {
372 for (string::const_iterator cit = token.begin();
373 cit != token.end(); ++cit)
375 par->InsertChar(pos, (*cit), font);
378 checkminipage = true;
379 } else if (token == "\\i") {
380 Inset * inset = new InsetLatexAccent;
381 inset->Read(this, lex);
382 par->InsertInset(pos, inset, font);
384 } else if (token == "\\layout") {
386 string const layoutname = lex.GetString();
387 pair<bool, LyXTextClass::LayoutList::size_type> pp
388 = textclasslist.NumberOfLayout(params.textclass,
392 // The is the compability reading of layout caption.
393 // It can be removed in LyX version 1.3.0. (Lgb)
394 if (compare_no_case(layoutname, "caption") == 0) {
395 // We expect that the par we are now working on is
396 // really inside a InsetText inside a InsetFloat.
397 // We also know that captions can only be
398 // one paragraph. (Lgb)
400 // We should now read until the next "\layout"
402 // This is probably not good enough, what if the
403 // caption is the last par in the document (Lgb)
404 istream & ist = lex.getStream();
410 if (prefixIs(line, "\\layout")) {
414 if (prefixIs(line, "\\begin_inset"))
416 if (prefixIs(line, "\\end_inset")) {
427 // Now we should have the whole layout in ss
428 // we should now be able to give this to the
430 ss << "\\end_inset\n";
432 // This seems like a bug in stringstream.
433 // We really should be able to use ss
435 istringstream is(ss.str());
437 tmplex.setStream(is);
438 Inset * inset = new InsetCaption;
439 inset->Read(this, tmplex);
440 par->InsertInset(pos, inset, font);
448 par = new LyXParagraph(par);
452 par->layout = pp.second;
455 // use default layout "Standard" (0)
458 // Test whether the layout is obsolete.
459 LyXLayout const & layout =
460 textclasslist.Style(params.textclass,
462 if (!layout.obsoleted_by().empty())
463 par->layout = textclasslist
464 .NumberOfLayout(params.textclass,
465 layout.obsoleted_by())
467 par->params.depth(depth);
468 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
469 if (file_format < 216
470 && params.language->lang() == "hebrew")
471 font.setLanguage(default_language);
476 } else if (token == "\\begin_float") {
477 // This is the compability reader. It can be removed in
478 // LyX version 1.3.0. (Lgb)
480 string const tmptok = lex.GetString();
481 //lyxerr << "old float: " << tmptok << endl;
484 stringstream old_float;
486 if (tmptok == "footnote") {
487 inset = new InsetFoot;
488 } else if (tmptok == "margin") {
489 inset = new InsetMarginal;
490 } else if (tmptok == "fig") {
491 inset = new InsetFloat("figure");
492 old_float << "placement htbp\n";
493 } else if (tmptok == "tab") {
494 inset = new InsetFloat("table");
495 old_float << "placement htbp\n";
496 } else if (tmptok == "alg") {
497 inset = new InsetFloat("algorithm");
498 old_float << "placement htbp\n";
499 } else if (tmptok == "wide-fig") {
500 InsetFloat * tmp = new InsetFloat("figure");
503 old_float << "placement htbp\n";
504 } else if (tmptok == "wide-tab") {
505 InsetFloat * tmp = new InsetFloat("table");
508 old_float << "placement htbp\n";
513 return false; // no end read yet
516 old_float << "collapsed true\n";
518 // Here we need to check for \end_deeper and handle that
519 // before we do the footnote parsing.
520 // This _is_ a hack! (Lgb)
523 string const tmp = lex.GetString();
524 if (tmp == "\\end_deeper") {
525 //lyxerr << "\\end_deeper caught!" << endl;
527 lex.printError("\\end_deeper: "
528 "depth is already null");
533 old_float << tmp << ' ';
538 old_float << lex.getLongString("\\end_float")
539 << "\n\\end_inset\n";
540 //lyxerr << "Float Body:\n" << old_float.str() << endl;
541 // That this does not work seems like a bug
542 // in stringstream. (Lgb)
543 istringstream istr(old_float.str());
545 nylex.setStream(istr);
546 inset->Read(this, nylex);
547 par->InsertInset(pos, inset, font);
549 } else if (token == "\\begin_deeper") {
551 } else if (token == "\\end_deeper") {
553 lex.printError("\\end_deeper: "
554 "depth is already null");
558 } else if (token == "\\begin_preamble") {
559 params.readPreamble(lex);
560 } else if (token == "\\textclass") {
562 pair<bool, LyXTextClassList::size_type> pp =
563 textclasslist.NumberOfClass(lex.GetString());
565 params.textclass = pp.second;
567 WriteAlert(string(_("Textclass error")),
568 string(_("The document uses an unknown textclass \"")) +
569 lex.GetString() + string("\"."),
570 string(_("LyX will not be able to produce output correctly.")));
571 params.textclass = 0;
573 if (!textclasslist.Load(params.textclass)) {
574 // if the textclass wasn't loaded properly
575 // we need to either substitute another
576 // or stop loading the file.
577 // I can substitute but I don't see how I can
578 // stop loading... ideas?? ARRae980418
579 WriteAlert(_("Textclass Loading Error!"),
580 string(_("Can't load textclass ")) +
581 textclasslist.NameOfClass(params.textclass),
582 _("-- substituting default"));
583 params.textclass = 0;
585 } else if (token == "\\options") {
587 params.options = lex.GetString();
588 } else if (token == "\\language") {
589 params.readLanguage(lex);
590 } else if (token == "\\fontencoding") {
592 } else if (token == "\\inputencoding") {
594 params.inputenc = lex.GetString();
595 } else if (token == "\\graphics") {
596 params.readGraphicsDriver(lex);
597 } else if (token == "\\fontscheme") {
599 params.fonts = lex.GetString();
600 } else if (token == "\\noindent") {
601 par->params.noindent(true);
602 } else if (token == "\\fill_top") {
603 par->params.spaceTop(VSpace(VSpace::VFILL));
604 } else if (token == "\\fill_bottom") {
605 par->params.spaceBottom(VSpace(VSpace::VFILL));
606 } else if (token == "\\line_top") {
607 par->params.lineTop(true);
608 } else if (token == "\\line_bottom") {
609 par->params.lineBottom(true);
610 } else if (token == "\\pagebreak_top") {
611 par->params.pagebreakTop(true);
612 } else if (token == "\\pagebreak_bottom") {
613 par->params.pagebreakBottom(true);
614 } else if (token == "\\start_of_appendix") {
615 par->params.startOfAppendix(true);
616 } else if (token == "\\paragraph_separation") {
617 int tmpret = lex.FindToken(string_paragraph_separation);
618 if (tmpret == -1) ++tmpret;
619 if (tmpret != LYX_LAYOUT_DEFAULT)
620 params.paragraph_separation =
621 static_cast<BufferParams::PARSEP>(tmpret);
622 } else if (token == "\\defskip") {
624 params.defskip = VSpace(lex.GetString());
625 } else if (token == "\\epsfig") { // obsolete
626 // Indeed it is obsolete, but we HAVE to be backwards
627 // compatible until 0.14, because otherwise all figures
628 // in existing documents are irretrivably lost. (Asger)
629 params.readGraphicsDriver(lex);
630 } else if (token == "\\quotes_language") {
631 int tmpret = lex.FindToken(string_quotes_language);
632 if (tmpret == -1) ++tmpret;
633 if (tmpret != LYX_LAYOUT_DEFAULT) {
634 InsetQuotes::quote_language tmpl =
635 InsetQuotes::EnglishQ;
638 tmpl = InsetQuotes::EnglishQ;
641 tmpl = InsetQuotes::SwedishQ;
644 tmpl = InsetQuotes::GermanQ;
647 tmpl = InsetQuotes::PolishQ;
650 tmpl = InsetQuotes::FrenchQ;
653 tmpl = InsetQuotes::DanishQ;
656 params.quotes_language = tmpl;
658 } else if (token == "\\quotes_times") {
660 switch (lex.GetInteger()) {
662 params.quotes_times = InsetQuotes::SingleQ;
665 params.quotes_times = InsetQuotes::DoubleQ;
668 } else if (token == "\\papersize") {
669 int tmpret = lex.FindToken(string_papersize);
673 params.papersize2 = tmpret;
674 } else if (token == "\\paperpackage") {
675 int tmpret = lex.FindToken(string_paperpackages);
678 params.paperpackage = BufferParams::PACKAGE_NONE;
680 params.paperpackage = tmpret;
681 } else if (token == "\\use_geometry") {
683 params.use_geometry = lex.GetInteger();
684 } else if (token == "\\use_amsmath") {
686 params.use_amsmath = lex.GetInteger();
687 } else if (token == "\\paperorientation") {
688 int tmpret = lex.FindToken(string_orientation);
689 if (tmpret == -1) ++tmpret;
690 if (tmpret != LYX_LAYOUT_DEFAULT)
691 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
692 } else if (token == "\\paperwidth") {
694 params.paperwidth = lex.GetString();
695 } else if (token == "\\paperheight") {
697 params.paperheight = lex.GetString();
698 } else if (token == "\\leftmargin") {
700 params.leftmargin = lex.GetString();
701 } else if (token == "\\topmargin") {
703 params.topmargin = lex.GetString();
704 } else if (token == "\\rightmargin") {
706 params.rightmargin = lex.GetString();
707 } else if (token == "\\bottommargin") {
709 params.bottommargin = lex.GetString();
710 } else if (token == "\\headheight") {
712 params.headheight = lex.GetString();
713 } else if (token == "\\headsep") {
715 params.headsep = lex.GetString();
716 } else if (token == "\\footskip") {
718 params.footskip = lex.GetString();
719 } else if (token == "\\paperfontsize") {
721 params.fontsize = strip(lex.GetString());
722 } else if (token == "\\papercolumns") {
724 params.columns = lex.GetInteger();
725 } else if (token == "\\papersides") {
727 switch (lex.GetInteger()) {
729 case 1: params.sides = LyXTextClass::OneSide; break;
730 case 2: params.sides = LyXTextClass::TwoSides; break;
732 } else if (token == "\\paperpagestyle") {
734 params.pagestyle = strip(lex.GetString());
735 } else if (token == "\\bullet") {
737 int const index = lex.GetInteger();
739 int temp_int = lex.GetInteger();
740 params.user_defined_bullets[index].setFont(temp_int);
741 params.temp_bullets[index].setFont(temp_int);
743 temp_int = lex.GetInteger();
744 params.user_defined_bullets[index].setCharacter(temp_int);
745 params.temp_bullets[index].setCharacter(temp_int);
747 temp_int = lex.GetInteger();
748 params.user_defined_bullets[index].setSize(temp_int);
749 params.temp_bullets[index].setSize(temp_int);
751 string const temp_str = lex.GetString();
752 if (temp_str != "\\end_bullet") {
753 // this element isn't really necessary for
754 // parsing but is easier for humans
755 // to understand bullets. Put it back and
756 // set a debug message?
757 lex.printError("\\end_bullet expected, got" + temp_str);
758 //how can I put it back?
760 } else if (token == "\\bulletLaTeX") {
762 int const index = lex.GetInteger();
764 string temp_str = lex.GetString();
766 while (temp_str != "\\end_bullet") {
767 // this loop structure is needed when user
768 // enters an empty string since the first
769 // thing returned will be the \\end_bullet
771 // if the LaTeX entry has spaces. Each element
772 // therefore needs to be read in turn
775 temp_str = lex.GetString();
777 params.user_defined_bullets[index].setText(sum_str);
778 params.temp_bullets[index].setText(sum_str);
779 } else if (token == "\\secnumdepth") {
781 params.secnumdepth = lex.GetInteger();
782 } else if (token == "\\tocdepth") {
784 params.tocdepth = lex.GetInteger();
785 } else if (token == "\\spacing") {
787 string const tmp = strip(lex.GetString());
788 Spacing::Space tmp_space = Spacing::Default;
790 if (tmp == "single") {
791 tmp_space = Spacing::Single;
792 } else if (tmp == "onehalf") {
793 tmp_space = Spacing::Onehalf;
794 } else if (tmp == "double") {
795 tmp_space = Spacing::Double;
796 } else if (tmp == "other") {
798 tmp_space = Spacing::Other;
799 tmp_val = lex.GetFloat();
801 lex.printError("Unknown spacing token: '$$Token'");
803 // Small hack so that files written with klyx will be
806 par->params.spacing(Spacing(tmp_space, tmp_val));
808 params.spacing.set(tmp_space, tmp_val);
810 } else if (token == "\\paragraph_spacing") {
812 string const tmp = strip(lex.GetString());
813 if (tmp == "single") {
814 par->params.spacing(Spacing(Spacing::Single));
815 } else if (tmp == "onehalf") {
816 par->params.spacing(Spacing(Spacing::Onehalf));
817 } else if (tmp == "double") {
818 par->params.spacing(Spacing(Spacing::Double));
819 } else if (tmp == "other") {
821 par->params.spacing(Spacing(Spacing::Other,
824 lex.printError("Unknown spacing token: '$$Token'");
826 } else if (token == "\\float_placement") {
828 params.float_placement = lex.GetString();
829 } else if (token == "\\family") {
831 font.setLyXFamily(lex.GetString());
832 } else if (token == "\\series") {
834 font.setLyXSeries(lex.GetString());
835 } else if (token == "\\shape") {
837 font.setLyXShape(lex.GetString());
838 } else if (token == "\\size") {
840 font.setLyXSize(lex.GetString());
841 } else if (token == "\\latex") {
843 string const tok = lex.GetString();
844 // This is dirty, but gone with LyX3. (Asger)
845 if (tok == "no_latex")
846 font.setLatex(LyXFont::OFF);
847 else if (tok == "latex")
848 font.setLatex(LyXFont::ON);
849 else if (tok == "default")
850 font.setLatex(LyXFont::INHERIT);
852 lex.printError("Unknown LaTeX font flag "
854 } else if (token == "\\lang") {
856 string const tok = lex.GetString();
857 Language const * lang = languages.getLanguage(tok);
859 font.setLanguage(lang);
861 font.setLanguage(params.language);
862 lex.printError("Unknown language `$$Token'");
864 } else if (token == "\\numeric") {
866 font.setNumber(font.setLyXMisc(lex.GetString()));
867 } else if (token == "\\emph") {
869 font.setEmph(font.setLyXMisc(lex.GetString()));
870 } else if (token == "\\bar") {
872 string const tok = lex.GetString();
873 // This is dirty, but gone with LyX3. (Asger)
875 font.setUnderbar(LyXFont::ON);
876 else if (tok == "no")
877 font.setUnderbar(LyXFont::OFF);
878 else if (tok == "default")
879 font.setUnderbar(LyXFont::INHERIT);
881 lex.printError("Unknown bar font flag "
883 } else if (token == "\\noun") {
885 font.setNoun(font.setLyXMisc(lex.GetString()));
886 } else if (token == "\\color") {
888 font.setLyXColor(lex.GetString());
889 } else if (token == "\\align") {
890 int tmpret = lex.FindToken(string_align);
891 if (tmpret == -1) ++tmpret;
892 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
893 int const tmpret2 = int(pow(2.0, tmpret));
894 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
895 par->params.align(LyXAlignment(tmpret2));
897 } else if (token == "\\added_space_top") {
899 par->params.spaceTop(VSpace(lex.GetString()));
900 } else if (token == "\\added_space_bottom") {
902 par->params.spaceBottom(VSpace(lex.GetString()));
903 #ifndef NO_PEXTRA_REALLY
904 } else if (token == "\\pextra_type") {
906 par->params.pextraType(lex.GetInteger());
907 } else if (token == "\\pextra_width") {
909 par->params.pextraWidth(lex.GetString());
910 } else if (token == "\\pextra_widthp") {
912 par->params.pextraWidthp(lex.GetString());
913 } else if (token == "\\pextra_alignment") {
915 par->params.pextraAlignment(lex.GetInteger());
916 } else if (token == "\\pextra_hfill") {
918 par->params.pextraHfill(lex.GetInteger());
919 } else if (token == "\\pextra_start_minipage") {
921 par->params.pextraStartMinipage(lex.GetInteger());
923 } else if (token == "\\labelwidthstring") {
925 par->params.labelWidthString(lex.GetString());
926 // do not delete this token, it is still needed!
927 } else if (token == "\\end_inset") {
928 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
929 << "Last inset read was: " << last_inset_read
931 // Simply ignore this. The insets do not have
933 // But insets should read it, it is a part of
934 // the inset isn't it? Lgb.
935 } else if (token == "\\begin_inset") {
936 readInset(lex, par, pos, font);
937 } else if (token == "\\SpecialChar") {
938 LyXLayout const & layout =
939 textclasslist.Style(params.textclass,
942 // Insets don't make sense in a free-spacing context! ---Kayvan
943 if (layout.free_spacing) {
946 string next_token = lex.GetString();
947 if (next_token == "\\-") {
948 par->InsertChar(pos, '-', font);
949 } else if (next_token == "\\protected_separator"
950 || next_token == "~") {
951 par->InsertChar(pos, ' ', font);
953 lex.printError("Token `$$Token' "
955 "paragraph layout!");
960 Inset * inset = new InsetSpecialChar;
961 inset->Read(this, lex);
962 par->InsertInset(pos, inset, font);
965 } else if (token == "\\newline") {
966 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
968 } else if (token == "\\LyXTable") {
969 Inset * inset = new InsetTabular(*this);
970 inset->Read(this, lex);
971 par->InsertInset(pos, inset, font);
973 // because of OLD_TABULAR_READ where tabulars have been
975 checkminipage = true;
976 } else if (token == "\\hfill") {
977 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
979 } else if (token == "\\protected_separator") { // obsolete
980 // This is a backward compability thingie. (Lgb)
981 // Remove it later some time...introduced with fileformat
983 LyXLayout const & layout =
984 textclasslist.Style(params.textclass,
987 if (layout.free_spacing) {
988 par->InsertChar(pos, ' ', font);
990 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
991 par->InsertInset(pos, inset, font);
994 } else if (token == "\\bibitem") { // ale970302
996 InsetCommandParams p("bibitem", "dummy");
997 par->bibkey = new InsetBibKey(p);
999 par->bibkey->Read(this, lex);
1000 } else if (token == "\\backslash") {
1001 par->InsertChar(pos, '\\', font);
1003 } else if (token == "\\the_end") {
1004 the_end_read = true;
1005 minipar = parBeforeMinipage = 0;
1007 // This should be insurance for the future: (Asger)
1008 lex.printError("Unknown token `$$Token'. "
1009 "Inserting as text.");
1010 string::const_iterator cit = token.begin();
1011 string::const_iterator end = token.end();
1012 for (; cit != end; ++cit) {
1013 par->InsertChar(pos, (*cit), font);
1017 #ifndef NO_PEXTRA_REALLY
1018 // now check if we have a minipage paragraph as at this
1019 // point we already read all the necessary data!
1020 // this cannot be done in layout because there we did
1021 // not read yet the paragraph PEXTRA-params (Jug)
1023 // BEGIN pextra_minipage compability
1024 // This should be removed in 1.3.x (Lgb)
1026 // This compability code is not perfect. In a couple
1027 // of rand cases it fails. When the minipage par is
1028 // the first par in the document, and when there are
1029 // none or only one regular paragraphs after the
1030 // minipage. Currently I am not investing any effort
1031 // in fixing those cases.
1033 //lyxerr << "Call depth: " << call_depth << endl;
1034 if (checkminipage && (call_depth == 1)) {
1035 checkminipage = false;
1036 if (minipar && (minipar != par) &&
1037 (par->params.pextraType()==LyXParagraph::PEXTRA_MINIPAGE))
1039 lyxerr << "minipages in a row" << endl;
1040 if (par->params.pextraStartMinipage()) {
1041 lyxerr << "start new minipage" << endl;
1042 // minipages in a row
1043 par->previous()->next(0);
1046 LyXParagraph * tmp = minipar;
1048 tmp->params.pextraType(0);
1049 tmp->params.pextraWidth(string());
1050 tmp->params.pextraWidthp(string());
1051 tmp->params.pextraAlignment(0);
1052 tmp->params.pextraHfill(false);
1053 tmp->params.pextraStartMinipage(false);
1056 // create a new paragraph to insert the
1057 // minipages in the following case
1058 if (par->params.pextraStartMinipage() &&
1059 !par->params.pextraHfill())
1061 LyXParagraph * p = new LyXParagraph;
1063 p->previous(parBeforeMinipage);
1064 parBeforeMinipage->next(p);
1066 p->params.depth(parBeforeMinipage->params.depth());
1067 parBeforeMinipage = p;
1069 InsetMinipage * mini = new InsetMinipage;
1070 mini->pos(static_cast<InsetMinipage::Position>(par->params.pextraAlignment()));
1071 mini->width(par->params.pextraWidth());
1072 if (!par->params.pextraWidthp().empty()) {
1073 lyxerr << "WP:" << mini->width() << endl;
1074 mini->width(tostr(par->params.pextraWidthp())+"%");
1076 mini->inset.par = par;
1077 // Insert the minipage last in the
1078 // previous paragraph.
1079 if (par->params.pextraHfill()) {
1080 parBeforeMinipage->InsertChar
1081 (parBeforeMinipage->size(), LyXParagraph::META_HFILL);
1083 parBeforeMinipage->InsertInset
1084 (parBeforeMinipage->size(), mini);
1088 lyxerr << "new minipage par" << endl;
1089 //nothing to do just continue reading
1092 } else if (minipar && (minipar != par)) {
1093 lyxerr << "last minipage par read" << endl;
1094 // The last paragraph read was not part of a
1095 // minipage but the par linked list is...
1096 // So we need to remove the last par from the
1098 if (par->previous())
1099 par->previous()->next(0);
1100 par->previous(parBeforeMinipage);
1101 parBeforeMinipage->next(par);
1102 LyXParagraph * tmp = minipar;
1104 tmp->params.pextraType(0);
1105 tmp->params.pextraWidth(string());
1106 tmp->params.pextraWidthp(string());
1107 tmp->params.pextraAlignment(0);
1108 tmp->params.pextraHfill(false);
1109 tmp->params.pextraStartMinipage(false);
1112 depth = parBeforeMinipage->params.depth();
1113 minipar = parBeforeMinipage = 0;
1114 } else if (!minipar &&
1115 (par->params.pextraType() == LyXParagraph::PEXTRA_MINIPAGE))
1117 // par is the first paragraph in a minipage
1118 lyxerr << "begin minipage" << endl;
1119 // To minimize problems for
1120 // the users we will insert
1121 // the first minipage in
1122 // a sequence of minipages
1123 // in its own paragraph.
1124 LyXParagraph * p = new LyXParagraph;
1126 p->previous(par->previous());
1128 p->params.depth(depth);
1129 par->params.depth(0);
1131 if (par->previous())
1132 par->previous()->next(p);
1134 parBeforeMinipage = p;
1136 if (!return_par || (return_par == par))
1139 InsetMinipage * mini = new InsetMinipage;
1140 mini->pos(static_cast<InsetMinipage::Position>(minipar->params.pextraAlignment()));
1141 mini->width(minipar->params.pextraWidth());
1142 if (!par->params.pextraWidthp().empty()) {
1143 lyxerr << "WP:" << mini->width() << endl;
1144 mini->width(tostr(par->params.pextraWidthp())+"%");
1146 mini->inset.par = minipar;
1148 // Insert the minipage last in the
1149 // previous paragraph.
1150 if (minipar->params.pextraHfill()) {
1151 parBeforeMinipage->InsertChar
1152 (parBeforeMinipage->size(),LyXParagraph::META_HFILL);
1154 parBeforeMinipage->InsertInset
1155 (parBeforeMinipage->size(), mini);
1158 // End of pextra_minipage compability
1161 return the_end_read;
1165 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1166 int & pos, LyXFont & font)
1168 // consistency check
1169 if (lex.GetString() != "\\begin_inset") {
1170 lyxerr << "Buffer::readInset: Consistency check failed."
1177 string const tmptok = lex.GetString();
1178 last_inset_read = tmptok;
1180 // test the different insets
1181 if (tmptok == "LatexCommand") {
1182 InsetCommandParams inscmd;
1185 string const cmdName = inscmd.getCmdName();
1187 if (cmdName == "cite") {
1188 inset = new InsetCitation(inscmd);
1189 } else if (cmdName == "bibitem") {
1190 lex.printError("Wrong place for bibitem");
1191 inset = new InsetBibKey(inscmd);
1192 } else if (cmdName == "BibTeX") {
1193 inset = new InsetBibtex(inscmd);
1194 } else if (cmdName == "index") {
1195 inset = new InsetIndex(inscmd);
1196 } else if (cmdName == "include") {
1197 inset = new InsetInclude(inscmd, *this);
1198 } else if (cmdName == "label") {
1199 inset = new InsetLabel(inscmd);
1200 } else if (cmdName == "url"
1201 || cmdName == "htmlurl") {
1202 inset = new InsetUrl(inscmd);
1203 } else if (cmdName == "ref"
1204 || cmdName == "pageref"
1205 || cmdName == "vref"
1206 || cmdName == "vpageref"
1207 || cmdName == "prettyref") {
1208 if (!inscmd.getOptions().empty()
1209 || !inscmd.getContents().empty()) {
1210 inset = new InsetRef(inscmd, *this);
1212 } else if (cmdName == "tableofcontents") {
1213 inset = new InsetTOC(inscmd);
1214 } else if (cmdName == "listofalgorithms") {
1215 inset = new InsetFloatList("algorithm");
1216 } else if (cmdName == "listoffigures") {
1217 inset = new InsetFloatList("figure");
1218 } else if (cmdName == "listoftables") {
1219 inset = new InsetFloatList("table");
1220 } else if (cmdName == "printindex") {
1221 inset = new InsetPrintIndex(inscmd);
1222 } else if (cmdName == "lyxparent") {
1223 inset = new InsetParent(inscmd, *this);
1226 if (tmptok == "Quotes") {
1227 inset = new InsetQuotes;
1228 } else if (tmptok == "External") {
1229 inset = new InsetExternal;
1230 } else if (tmptok == "FormulaMacro") {
1231 inset = new InsetFormulaMacro;
1232 } else if (tmptok == "Formula") {
1233 inset = new InsetFormula;
1234 } else if (tmptok == "Figure") {
1235 inset = new InsetFig(100, 100, *this);
1236 } else if (tmptok == "Info") {
1237 inset = new InsetInfo;
1238 } else if (tmptok == "Include") {
1239 InsetCommandParams p( "Include" );
1240 inset = new InsetInclude(p, *this);
1241 } else if (tmptok == "ERT") {
1242 inset = new InsetERT;
1243 } else if (tmptok == "Tabular") {
1244 inset = new InsetTabular(*this);
1245 } else if (tmptok == "Text") {
1246 inset = new InsetText;
1247 } else if (tmptok == "Foot") {
1248 inset = new InsetFoot;
1249 } else if (tmptok == "Marginal") {
1250 inset = new InsetMarginal;
1251 } else if (tmptok == "Minipage") {
1252 inset = new InsetMinipage;
1253 } else if (tmptok == "Float") {
1255 string tmptok = lex.GetString();
1256 inset = new InsetFloat(tmptok);
1257 } else if (tmptok == "List") {
1258 inset = new InsetList;
1259 } else if (tmptok == "Theorem") {
1260 inset = new InsetList;
1261 } else if (tmptok == "Caption") {
1262 inset = new InsetCaption;
1263 } else if (tmptok == "GRAPHICS") {
1264 inset = new InsetGraphics;
1265 } else if (tmptok == "FloatList") {
1266 inset = new InsetFloatList;
1269 if (inset) inset->Read(this, lex);
1273 par->InsertInset(pos, inset, font);
1279 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1283 string const token(lex.GetString());
1284 if (token == "\\lyxformat") { // the first token _must_ be...
1286 string tmp_format = lex.GetString();
1287 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1288 // if present remove ".," from string.
1289 string::size_type dot = tmp_format.find_first_of(".,");
1290 //lyxerr << " dot found at " << dot << endl;
1291 if (dot != string::npos)
1292 tmp_format.erase(dot, 1);
1293 file_format = strToInt(tmp_format);
1294 if (file_format == LYX_FORMAT) {
1296 } else if (file_format > LYX_FORMAT) {
1298 WriteAlert(_("Warning!"),
1299 _("LyX file format is newer that what"),
1300 _("is supported in this LyX version. Expect some problems."));
1302 } else if (file_format < LYX_FORMAT) {
1304 if (file_format < 200) {
1305 WriteAlert(_("ERROR!"),
1306 _("Old LyX file format found. "
1307 "Use LyX 0.10.x to read this!"));
1311 bool the_end = readLyXformat2(lex, par);
1313 // the_end was added in 213
1314 if (file_format < 213)
1318 WriteAlert(_("Warning!"),
1319 _("Reading of document is not complete"),
1320 _("Maybe the document is truncated"));
1322 } else { // "\\lyxformat" not found
1323 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1326 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1332 // Should probably be moved to somewhere else: BufferView? LyXView?
1333 bool Buffer::save() const
1335 // We don't need autosaves in the immediate future. (Asger)
1336 resetAutosaveTimers();
1340 if (lyxrc.make_backup) {
1341 s = fileName() + '~';
1342 if (!lyxrc.backupdir_path.empty())
1343 s = AddName(lyxrc.backupdir_path,
1344 subst(CleanupPath(s),'/','!'));
1346 // Rename is the wrong way of making a backup,
1347 // this is the correct way.
1348 /* truss cp fil fil2:
1349 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1350 stat("LyXVC.lyx", 0xEFFFF688) = 0
1351 open("LyXVC.lyx", O_RDONLY) = 3
1352 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1353 fstat(4, 0xEFFFF508) = 0
1354 fstat(3, 0xEFFFF508) = 0
1355 read(3, " # T h i s f i l e w".., 8192) = 5579
1356 write(4, " # T h i s f i l e w".., 5579) = 5579
1357 read(3, 0xEFFFD4A0, 8192) = 0
1360 chmod("LyXVC3.lyx", 0100644) = 0
1361 lseek(0, 0, SEEK_CUR) = 46440
1365 // Should proabaly have some more error checking here.
1366 // Should be cleaned up in 0.13, at least a bit.
1367 // Doing it this way, also makes the inodes stay the same.
1368 // This is still not a very good solution, in particular we
1369 // might loose the owner of the backup.
1370 FileInfo finfo(fileName());
1371 if (finfo.exist()) {
1372 mode_t fmode = finfo.getMode();
1373 struct utimbuf times = {
1374 finfo.getAccessTime(),
1375 finfo.getModificationTime() };
1377 ifstream ifs(fileName().c_str());
1378 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1383 ::chmod(s.c_str(), fmode);
1385 if (::utime(s.c_str(), ×)) {
1386 lyxerr << "utime error." << endl;
1389 lyxerr << "LyX was not able to make "
1390 "backupcopy. Beware." << endl;
1395 if (writeFile(fileName(), false)) {
1397 removeAutosaveFile(fileName());
1399 // Saving failed, so backup is not backup
1400 if (lyxrc.make_backup) {
1401 lyx::rename(s, fileName());
1409 // Returns false if unsuccesful
1410 bool Buffer::writeFile(string const & fname, bool flag) const
1412 // if flag is false writeFile will not create any GUI
1413 // warnings, only cerr.
1414 // Needed for autosave in background or panic save (Matthias 120496)
1416 if (read_only && (fname == filename)) {
1417 // Here we should come with a question if we should
1418 // perform the write anyway.
1420 lyxerr << _("Error! Document is read-only: ")
1423 WriteAlert(_("Error! Document is read-only: "),
1428 FileInfo finfo(fname);
1429 if (finfo.exist() && !finfo.writable()) {
1430 // Here we should come with a question if we should
1431 // try to do the save anyway. (i.e. do a chmod first)
1433 lyxerr << _("Error! Cannot write file: ")
1436 WriteFSAlert(_("Error! Cannot write file: "),
1441 ofstream ofs(fname.c_str());
1444 lyxerr << _("Error! Cannot open file: ")
1447 WriteFSAlert(_("Error! Cannot open file: "),
1453 // Use the standard "C" locale for file output.
1454 ofs.imbue(std::locale::classic());
1457 // The top of the file should not be written by params.
1459 // write out a comment in the top of the file
1460 ofs << '#' << LYX_DOCVERSION
1461 << " created this file. For more info see http://www.lyx.org/\n"
1462 << "\\lyxformat " << LYX_FORMAT << "\n";
1464 // now write out the buffer paramters.
1465 params.writeFile(ofs);
1469 // this will write out all the paragraphs
1470 // using recursive descent.
1471 paragraph->writeFile(this, ofs, params, depth);
1473 // Write marker that shows file is complete
1474 ofs << "\n\\the_end" << endl;
1478 // how to check if close went ok?
1479 // Following is an attempt... (BE 20001011)
1481 // good() returns false if any error occured, including some
1482 // formatting error.
1483 // bad() returns true if something bad happened in the buffer,
1484 // which should include file system full errors.
1491 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1493 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1503 string const Buffer::asciiParagraph(LyXParagraph const * par,
1504 unsigned int linelen) const
1506 ostringstream buffer;
1509 Inset const * inset;
1513 int ltype_depth = 0;
1514 unsigned int currlinelen = 0;
1515 bool ref_printed = false;
1519 if (!par->previous()) {
1520 /* begins or ends a deeper area ?*/
1521 if (depth != par->params.depth()) {
1522 if (par->params.depth() > depth) {
1523 while (par->params.depth() > depth) {
1527 while (par->params.depth() < depth) {
1533 /* First write the layout */
1534 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1535 if (tmp == "Itemize") {
1537 ltype_depth = depth + 1;
1538 } else if (tmp == "Enumerate") {
1540 ltype_depth = depth + 1;
1541 } else if (strstr(tmp.c_str(), "ection")) {
1543 ltype_depth = depth + 1;
1544 } else if (strstr(tmp.c_str(), "aragraph")) {
1546 ltype_depth = depth + 1;
1547 } else if (tmp == "Description") {
1549 ltype_depth = depth + 1;
1550 } else if (tmp == "Abstract") {
1553 } else if (tmp == "Bibliography") {
1561 /* maybe some vertical spaces */
1563 /* the labelwidthstring used in lists */
1567 /* some pagebreaks? */
1571 /* what about the alignment */
1573 lyxerr << "Should this ever happen?" << endl;
1576 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1577 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1578 if (!i && !noparbreak) {
1581 for (char j = 0; j < depth; ++j)
1583 currlinelen = depth * 2;
1585 case 0: /* Standard */
1586 case 4: /* (Sub)Paragraph */
1587 case 5: /* Description */
1589 case 6: /* Abstract */
1591 buffer << "Abstract\n\n";
1593 buffer << "Abstract: ";
1595 case 7: /* Bibliography */
1598 buffer << "References\n\n";
1600 buffer << "References: ";
1605 buffer << par->params.labelString() << " ";
1608 if (ltype_depth > depth) {
1609 for (char j = ltype_depth - 1; j > depth; --j)
1611 currlinelen += (ltype_depth-depth)*2;
1614 font2 = par->GetFontSettings(params, i);
1615 if (font1.latex() != font2.latex()) {
1616 if (font2.latex() == LyXFont::OFF)
1623 c = par->GetUChar(params, i);
1627 case LyXParagraph::META_INSET:
1628 if ((inset = par->GetInset(i))) {
1629 if (!inset->Ascii(this, buffer)) {
1631 string s = rsplit(buffer.str().c_str(),
1633 currlinelen += s.length();
1635 // to be sure it breaks paragraph
1636 currlinelen += linelen;
1640 case LyXParagraph::META_NEWLINE:
1643 for (char j = 0; j < depth; ++j)
1646 currlinelen = depth * 2;
1647 if (ltype_depth > depth) {
1648 for (char j = ltype_depth;
1651 currlinelen += (ltype_depth - depth) * 2;
1654 case LyXParagraph::META_HFILL:
1661 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1662 (c == ' ') && ((i + 2) < par->size()))
1665 for (char j = 0; j < depth; ++j)
1667 currlinelen = depth * 2;
1668 if (ltype_depth > depth) {
1669 for (char j = ltype_depth;
1672 currlinelen += (ltype_depth-depth)*2;
1674 } else if (c != '\0')
1677 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1682 return buffer.str().c_str();
1686 void Buffer::writeFileAscii(string const & fname, int linelen)
1688 ofstream ofs(fname.c_str());
1690 WriteFSAlert(_("Error: Cannot write file:"), fname);
1693 writeFileAscii(ofs, linelen);
1697 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1699 LyXParagraph * par = paragraph;
1701 ofs << asciiParagraph(par, linelen);
1709 void Buffer::makeLaTeXFile(string const & fname,
1710 string const & original_path,
1711 bool nice, bool only_body)
1713 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1715 niceFile = nice; // this will be used by Insetincludes.
1717 tex_code_break_column = lyxrc.ascii_linelen;
1719 LyXTextClass const & tclass =
1720 textclasslist.TextClass(params.textclass);
1722 ofstream ofs(fname.c_str());
1724 WriteFSAlert(_("Error: Cannot open file: "), fname);
1728 // validate the buffer.
1729 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1730 LaTeXFeatures features(params, tclass.numLayouts());
1732 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1735 // The starting paragraph of the coming rows is the
1736 // first paragraph of the document. (Asger)
1737 texrow.start(paragraph, 0);
1739 if (!only_body && nice) {
1740 ofs << "%% " LYX_DOCVERSION " created this file. "
1741 "For more info, see http://www.lyx.org/.\n"
1742 "%% Do not edit unless you really know what "
1747 lyxerr.debug() << "lyx header finished" << endl;
1748 // There are a few differences between nice LaTeX and usual files:
1749 // usual is \batchmode and has a
1750 // special input@path to allow the including of figures
1751 // with either \input or \includegraphics (what figinsets do).
1752 // batchmode is not set if there is a tex_code_break_column.
1753 // In this case somebody is interested in the generated LaTeX,
1754 // so this is OK. input@path is set when the actual parameter
1755 // original_path is set. This is done for usual tex-file, but not
1756 // for nice-latex-file. (Matthias 250696)
1759 // code for usual, NOT nice-latex-file
1760 ofs << "\\batchmode\n"; // changed
1761 // from \nonstopmode
1764 if (!original_path.empty()) {
1765 ofs << "\\makeatletter\n"
1766 << "\\def\\input@path{{"
1767 << original_path << "/}}\n"
1768 << "\\makeatother\n";
1774 ofs << "\\documentclass";
1776 ostringstream options; // the document class options.
1778 if (tokenPos(tclass.opt_fontsize(),
1779 '|', params.fontsize) >= 0) {
1780 // only write if existing in list (and not default)
1781 options << params.fontsize;
1786 if (!params.use_geometry &&
1787 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1788 switch (params.papersize) {
1789 case BufferParams::PAPER_A4PAPER:
1790 options << "a4paper,";
1792 case BufferParams::PAPER_USLETTER:
1793 options << "letterpaper,";
1795 case BufferParams::PAPER_A5PAPER:
1796 options << "a5paper,";
1798 case BufferParams::PAPER_B5PAPER:
1799 options << "b5paper,";
1801 case BufferParams::PAPER_EXECUTIVEPAPER:
1802 options << "executivepaper,";
1804 case BufferParams::PAPER_LEGALPAPER:
1805 options << "legalpaper,";
1811 if (params.sides != tclass.sides()) {
1812 switch (params.sides) {
1813 case LyXTextClass::OneSide:
1814 options << "oneside,";
1816 case LyXTextClass::TwoSides:
1817 options << "twoside,";
1823 if (params.columns != tclass.columns()) {
1824 if (params.columns == 2)
1825 options << "twocolumn,";
1827 options << "onecolumn,";
1830 if (!params.use_geometry
1831 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1832 options << "landscape,";
1834 // language should be a parameter to \documentclass
1836 string language_options;
1837 if (params.language->babel() == "hebrew"
1838 && default_language->babel() != "hebrew")
1839 // This seems necessary
1840 features.UsedLanguages.insert(default_language);
1842 if (lyxrc.language_use_babel ||
1843 params.language->lang() != lyxrc.default_language ||
1844 !features.UsedLanguages.empty()) {
1846 for (LaTeXFeatures::LanguageList::const_iterator cit =
1847 features.UsedLanguages.begin();
1848 cit != features.UsedLanguages.end(); ++cit)
1849 language_options += (*cit)->babel() + ',';
1850 language_options += params.language->babel();
1851 if (lyxrc.language_global_options)
1852 options << language_options << ',';
1855 // the user-defined options
1856 if (!params.options.empty()) {
1857 options << params.options << ',';
1860 string strOptions(options.str().c_str());
1861 if (!strOptions.empty()){
1862 strOptions = strip(strOptions, ',');
1863 ofs << '[' << strOptions << ']';
1867 << textclasslist.LatexnameOfClass(params.textclass)
1870 // end of \documentclass defs
1872 // font selection must be done before loading fontenc.sty
1873 // The ae package is not needed when using OT1 font encoding.
1874 if (params.fonts != "default" &&
1875 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1876 ofs << "\\usepackage{" << params.fonts << "}\n";
1878 if (params.fonts == "ae") {
1879 ofs << "\\usepackage{aecompl}\n";
1883 // this one is not per buffer
1884 if (lyxrc.fontenc != "default") {
1885 ofs << "\\usepackage[" << lyxrc.fontenc
1890 if (params.inputenc == "auto") {
1891 string const doc_encoding =
1892 params.language->encoding()->LatexName();
1894 // Create a list with all the input encodings used
1896 set<string> encodings;
1897 for (LaTeXFeatures::LanguageList::const_iterator it =
1898 features.UsedLanguages.begin();
1899 it != features.UsedLanguages.end(); ++it)
1900 if ((*it)->encoding()->LatexName() != doc_encoding)
1901 encodings.insert((*it)->encoding()->LatexName());
1903 ofs << "\\usepackage[";
1904 std::copy(encodings.begin(), encodings.end(),
1905 std::ostream_iterator<string>(ofs, ","));
1906 ofs << doc_encoding << "]{inputenc}\n";
1908 } else if (params.inputenc != "default") {
1909 ofs << "\\usepackage[" << params.inputenc
1914 // At the very beginning the text parameters.
1915 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1916 switch (params.paperpackage) {
1917 case BufferParams::PACKAGE_A4:
1918 ofs << "\\usepackage{a4}\n";
1921 case BufferParams::PACKAGE_A4WIDE:
1922 ofs << "\\usepackage{a4wide}\n";
1925 case BufferParams::PACKAGE_WIDEMARGINSA4:
1926 ofs << "\\usepackage[widemargins]{a4}\n";
1931 if (params.use_geometry) {
1932 ofs << "\\usepackage{geometry}\n";
1934 ofs << "\\geometry{verbose";
1935 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1936 ofs << ",landscape";
1937 switch (params.papersize2) {
1938 case BufferParams::VM_PAPER_CUSTOM:
1939 if (!params.paperwidth.empty())
1940 ofs << ",paperwidth="
1941 << params.paperwidth;
1942 if (!params.paperheight.empty())
1943 ofs << ",paperheight="
1944 << params.paperheight;
1946 case BufferParams::VM_PAPER_USLETTER:
1947 ofs << ",letterpaper";
1949 case BufferParams::VM_PAPER_USLEGAL:
1950 ofs << ",legalpaper";
1952 case BufferParams::VM_PAPER_USEXECUTIVE:
1953 ofs << ",executivepaper";
1955 case BufferParams::VM_PAPER_A3:
1958 case BufferParams::VM_PAPER_A4:
1961 case BufferParams::VM_PAPER_A5:
1964 case BufferParams::VM_PAPER_B3:
1967 case BufferParams::VM_PAPER_B4:
1970 case BufferParams::VM_PAPER_B5:
1974 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1975 switch (lyxrc.default_papersize) {
1976 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1977 case BufferParams::PAPER_USLETTER:
1978 ofs << ",letterpaper";
1980 case BufferParams::PAPER_LEGALPAPER:
1981 ofs << ",legalpaper";
1983 case BufferParams::PAPER_EXECUTIVEPAPER:
1984 ofs << ",executivepaper";
1986 case BufferParams::PAPER_A3PAPER:
1989 case BufferParams::PAPER_A4PAPER:
1992 case BufferParams::PAPER_A5PAPER:
1995 case BufferParams::PAPER_B5PAPER:
2000 if (!params.topmargin.empty())
2001 ofs << ",tmargin=" << params.topmargin;
2002 if (!params.bottommargin.empty())
2003 ofs << ",bmargin=" << params.bottommargin;
2004 if (!params.leftmargin.empty())
2005 ofs << ",lmargin=" << params.leftmargin;
2006 if (!params.rightmargin.empty())
2007 ofs << ",rmargin=" << params.rightmargin;
2008 if (!params.headheight.empty())
2009 ofs << ",headheight=" << params.headheight;
2010 if (!params.headsep.empty())
2011 ofs << ",headsep=" << params.headsep;
2012 if (!params.footskip.empty())
2013 ofs << ",footskip=" << params.footskip;
2017 if (features.amsstyle
2018 && !tclass.provides(LyXTextClass::amsmath)) {
2019 ofs << "\\usepackage{amsmath}\n";
2023 if (tokenPos(tclass.opt_pagestyle(),
2024 '|', params.pagestyle) >= 0) {
2025 if (params.pagestyle == "fancy") {
2026 ofs << "\\usepackage{fancyhdr}\n";
2029 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2033 // We try to load babel late, in case it interferes
2034 // with other packages.
2036 string tmp = lyxrc.language_package;
2037 if (!lyxrc.language_global_options
2038 && tmp == "\\usepackage{babel}")
2039 tmp = "\\usepackage[" +
2040 language_options + "]{babel}";
2045 if (params.secnumdepth != tclass.secnumdepth()) {
2046 ofs << "\\setcounter{secnumdepth}{"
2047 << params.secnumdepth
2051 if (params.tocdepth != tclass.tocdepth()) {
2052 ofs << "\\setcounter{tocdepth}{"
2058 if (params.paragraph_separation) {
2059 switch (params.defskip.kind()) {
2060 case VSpace::SMALLSKIP:
2061 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2063 case VSpace::MEDSKIP:
2064 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2066 case VSpace::BIGSKIP:
2067 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2069 case VSpace::LENGTH:
2070 ofs << "\\setlength\\parskip{"
2071 << params.defskip.length().asLatexString()
2074 default: // should never happen // Then delete it.
2075 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2080 ofs << "\\setlength\\parindent{0pt}\n";
2084 // Now insert the LyX specific LaTeX commands...
2086 // The optional packages;
2087 string preamble(features.getPackages());
2089 // this might be useful...
2090 preamble += "\n\\makeatletter\n";
2092 // Some macros LyX will need
2093 string tmppreamble(features.getMacros());
2095 if (!tmppreamble.empty()) {
2096 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2097 "LyX specific LaTeX commands.\n"
2098 + tmppreamble + '\n';
2101 // the text class specific preamble
2102 tmppreamble = features.getTClassPreamble();
2103 if (!tmppreamble.empty()) {
2104 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2105 "Textclass specific LaTeX commands.\n"
2106 + tmppreamble + '\n';
2109 /* the user-defined preamble */
2110 if (!params.preamble.empty()) {
2111 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2112 "User specified LaTeX commands.\n"
2113 + params.preamble + '\n';
2116 preamble += "\\makeatother\n";
2118 // Itemize bullet settings need to be last in case the user
2119 // defines their own bullets that use a package included
2120 // in the user-defined preamble -- ARRae
2121 // Actually it has to be done much later than that
2122 // since some packages like frenchb make modifications
2123 // at \begin{document} time -- JMarc
2125 for (int i = 0; i < 4; ++i) {
2126 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2127 if (bullets_def.empty())
2128 bullets_def="\\AtBeginDocument{\n";
2129 bullets_def += " \\renewcommand{\\labelitemi";
2131 // `i' is one less than the item to modify
2138 bullets_def += "ii";
2144 bullets_def += "}{" +
2145 params.user_defined_bullets[i].getText()
2150 if (!bullets_def.empty())
2151 preamble += bullets_def + "}\n\n";
2153 for (int j = countChar(preamble, '\n'); j-- ;) {
2160 ofs << "\\begin{document}\n";
2163 lyxerr.debug() << "preamble finished, now the body." << endl;
2165 if (!lyxrc.language_auto_begin) {
2166 ofs << subst(lyxrc.language_command_begin, "$$lang",
2167 params.language->babel())
2172 latexParagraphs(ofs, paragraph, 0, texrow);
2174 // add this just in case after all the paragraphs
2178 if (!lyxrc.language_auto_end) {
2179 ofs << subst(lyxrc.language_command_end, "$$lang",
2180 params.language->babel())
2186 ofs << "\\end{document}\n";
2189 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2191 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2195 // Just to be sure. (Asger)
2198 // tex_code_break_column's value is used to decide
2199 // if we are in batchmode or not (within mathed_write()
2200 // in math_write.C) so we must set it to a non-zero
2201 // value when we leave otherwise we save incorrect .lyx files.
2202 tex_code_break_column = lyxrc.ascii_linelen;
2206 lyxerr << "File was not closed properly." << endl;
2209 lyxerr.debug() << "Finished making latex file." << endl;
2214 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2216 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2217 LyXParagraph * endpar, TexRow & texrow) const
2219 bool was_title = false;
2220 bool already_title = false;
2223 while (par != endpar) {
2224 LyXLayout const & layout =
2225 textclasslist.Style(params.textclass,
2228 if (layout.intitle) {
2229 if (already_title) {
2230 lyxerr <<"Error in latexParagraphs: You"
2231 " should not mix title layouts"
2232 " with normal ones." << endl;
2235 } else if (was_title && !already_title) {
2236 ofs << "\\maketitle\n";
2238 already_title = true;
2242 if (layout.isEnvironment()) {
2243 par = par->TeXEnvironment(this, params, ofs, texrow);
2245 par = par->TeXOnePar(this, params, ofs, texrow, false);
2248 // It might be that we only have a title in this document
2249 if (was_title && !already_title) {
2250 ofs << "\\maketitle\n";
2256 bool Buffer::isLatex() const
2258 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2262 bool Buffer::isLinuxDoc() const
2264 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2268 bool Buffer::isLiterate() const
2270 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2274 bool Buffer::isDocBook() const
2276 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2280 bool Buffer::isSGML() const
2282 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2283 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2287 void Buffer::sgmlOpenTag(ostream & os, int depth,
2288 string const & latexname) const
2290 if (!latexname.empty() && latexname != "!-- --")
2291 os << string(depth, ' ') << "<" << latexname << ">\n";
2295 void Buffer::sgmlCloseTag(ostream & os, int depth,
2296 string const & latexname) const
2298 if (!latexname.empty() && latexname != "!-- --")
2299 os << string(depth, ' ') << "</" << latexname << ">\n";
2303 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2305 ofstream ofs(fname.c_str());
2308 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2312 niceFile = nice; // this will be used by included files.
2314 LyXTextClass const & tclass =
2315 textclasslist.TextClass(params.textclass);
2317 LaTeXFeatures features(params, tclass.numLayouts());
2322 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2325 string sgml_includedfiles=features.getIncludedFiles(fname);
2327 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2328 ofs << "<!doctype linuxdoc system>\n\n";
2330 ofs << "<!doctype linuxdoc system [ "
2331 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2334 if (params.options.empty())
2335 sgmlOpenTag(ofs, 0, top_element);
2337 string top = top_element;
2339 top += params.options;
2340 sgmlOpenTag(ofs, 0, top);
2344 ofs << "<!-- " << LYX_DOCVERSION
2345 << " created this file. For more info see http://www.lyx.org/"
2348 int depth = 0; // paragraph depth
2349 LyXParagraph * par = paragraph;
2351 vector<string> environment_stack(5);
2354 LyXLayout const & style =
2355 textclasslist.Style(params.textclass,
2358 // treat <toc> as a special case for compatibility with old code
2359 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2360 Inset * inset = par->GetInset(0);
2361 Inset::Code lyx_code = inset->LyxCode();
2362 if (lyx_code == Inset::TOC_CODE){
2363 string const temp = "toc";
2364 sgmlOpenTag(ofs, depth, temp);
2371 // environment tag closing
2372 for (; depth > par->params.depth(); --depth) {
2373 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2374 environment_stack[depth].erase();
2377 // write opening SGML tags
2378 switch (style.latextype) {
2379 case LATEX_PARAGRAPH:
2380 if (depth == par->params.depth()
2381 && !environment_stack[depth].empty()) {
2382 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2383 environment_stack[depth].erase();
2389 sgmlOpenTag(ofs, depth, style.latexname());
2394 LinuxDocError(par, 0,
2395 _("Error : Wrong depth for"
2396 " LatexType Command.\n"));
2398 if (!environment_stack[depth].empty()){
2399 sgmlCloseTag(ofs, depth,
2400 environment_stack[depth]);
2404 environment_stack[depth].erase();
2405 sgmlOpenTag(ofs, depth, style.latexname());
2408 case LATEX_ENVIRONMENT:
2409 case LATEX_ITEM_ENVIRONMENT:
2410 if (depth == par->params.depth()
2411 && environment_stack[depth] != style.latexname()) {
2412 sgmlCloseTag(ofs, depth,
2413 environment_stack[depth]);
2414 environment_stack[depth].erase();
2416 if (depth < par->params.depth()) {
2417 depth = par->params.depth();
2418 environment_stack[depth].erase();
2420 if (environment_stack[depth] != style.latexname()) {
2422 sgmlOpenTag(ofs, depth, "p");
2424 sgmlOpenTag(ofs, depth, style.latexname());
2426 if (environment_stack.size() == depth + 1)
2427 environment_stack.push_back("!-- --");
2428 environment_stack[depth] = style.latexname();
2431 if (style.latexparam() == "CDATA")
2434 if (style.latextype == LATEX_ENVIRONMENT) break;
2436 if (style.labeltype == LABEL_MANUAL)
2441 sgmlOpenTag(ofs, depth + 1, item_name);
2444 sgmlOpenTag(ofs, depth, style.latexname());
2448 SimpleLinuxDocOnePar(ofs, par, depth);
2453 // write closing SGML tags
2454 switch (style.latextype) {
2457 case LATEX_ENVIRONMENT:
2458 case LATEX_ITEM_ENVIRONMENT:
2459 if (style.latexparam() == "CDATA")
2463 sgmlCloseTag(ofs, depth, style.latexname());
2469 for (int i=depth; i >= 0; --i)
2470 sgmlCloseTag(ofs, depth, environment_stack[i]);
2474 sgmlCloseTag(ofs, 0, top_element);
2478 // How to check for successful close
2482 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2483 int depth, int desc_on,
2484 LyXParagraph * & par)
2486 LyXParagraph * tpar = par;
2488 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2490 tpar = tpar->next();
2493 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2494 "Caption").second) {
2495 sgmlOpenTag(os, depth + 1, inner_tag);
2497 SimpleDocBookOnePar(os, extra_par, tpar,
2498 desc_on, depth + 2);
2499 sgmlCloseTag(os, depth+1, inner_tag);
2500 if (!extra_par.empty())
2506 // checks, if newcol chars should be put into this line
2507 // writes newline, if necessary.
2510 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2511 string::size_type newcol)
2514 if (colcount > lyxrc.ascii_linelen) {
2516 colcount = newcol; // assume write after this call
2531 string tag_name(PAR_TAG const & pt) {
2533 case NONE: return "!-- --";
2534 case TT: return "tt";
2535 case SF: return "sf";
2536 case BF: return "bf";
2537 case IT: return "it";
2538 case SL: return "sl";
2539 case EM: return "em";
2546 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2548 p1 = static_cast<PAR_TAG>(p1 | p2);
2553 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2555 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2563 // Handle internal paragraph parsing -- layout already processed.
2564 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2565 LyXParagraph * par, int /*depth*/)
2567 LyXLayout const & style = textclasslist.Style(params.textclass,
2569 string::size_type char_line_count = 5; // Heuristic choice ;-)
2571 // gets paragraph main font
2574 if (style.labeltype == LABEL_MANUAL) {
2575 font_old = style.labelfont;
2578 font_old = style.font;
2582 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2583 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2584 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2587 stack < PAR_TAG > tag_state;
2588 // parsing main loop
2589 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
2591 PAR_TAG tag_close = NONE;
2592 list < PAR_TAG > tag_open;
2594 LyXFont const font = par->getFont(params, i);
2596 if (font_old.family() != font.family()) {
2597 switch (family_type) {
2598 case LyXFont::SANS_FAMILY:
2601 case LyXFont::TYPEWRITER_FAMILY:
2608 family_type = font.family();
2610 switch (family_type) {
2611 case LyXFont::SANS_FAMILY:
2612 tag_open.push_back(SF);
2614 case LyXFont::TYPEWRITER_FAMILY:
2615 tag_open.push_back(TT);
2622 if (font_old.series() != font.series()) {
2623 switch (series_type) {
2624 case LyXFont::BOLD_SERIES:
2631 series_type = font.series();
2633 switch (series_type) {
2634 case LyXFont::BOLD_SERIES:
2635 tag_open.push_back(BF);
2643 if (font_old.shape() != font.shape()) {
2644 switch (shape_type) {
2645 case LyXFont::ITALIC_SHAPE:
2648 case LyXFont::SLANTED_SHAPE:
2655 shape_type = font.shape();
2657 switch (shape_type) {
2658 case LyXFont::ITALIC_SHAPE:
2659 tag_open.push_back(IT);
2661 case LyXFont::SLANTED_SHAPE:
2662 tag_open.push_back(SL);
2669 if (font_old.emph() != font.emph()) {
2670 if (font.emph() == LyXFont::ON) {
2671 tag_open.push_back(EM);
2680 list < PAR_TAG > temp;
2681 while(!tag_state.empty() && tag_close ) {
2682 PAR_TAG k = tag_state.top();
2684 os << "</" << tag_name(k) << ">";
2691 for(list< PAR_TAG >::const_iterator j = temp.begin();
2692 j != temp.end(); ++j) {
2694 os << "<" << tag_name(*j) << ">";
2697 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2698 j != tag_open.end(); ++j) {
2700 os << "<" << tag_name(*j) << ">";
2703 char c = par->GetChar(i);
2705 if (c == LyXParagraph::META_INSET) {
2706 Inset * inset = par->GetInset(i);
2707 inset->Linuxdoc(this, os);
2712 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
2713 // "TeX"-Mode on == > SGML-Mode on.
2719 if (par->linuxDocConvertChar(c, sgml_string)
2720 && !style.free_spacing) {
2721 // in freespacing mode, spaces are
2722 // non-breaking characters
2723 if (desc_on) {// if char is ' ' then...
2726 linux_doc_line_break(os, char_line_count, 6);
2730 linux_doc_line_break(os, char_line_count, 1);
2735 char_line_count += sgml_string.length();
2741 while (!tag_state.empty()) {
2742 os << "</" << tag_name(tag_state.top()) << ">";
2746 // resets description flag correctly
2748 // <tag> not closed...
2749 linux_doc_line_break(os, char_line_count, 6);
2755 // Print an error message.
2756 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2757 string const & message)
2759 // insert an error marker in text
2760 InsetError * new_inset = new InsetError(message);
2761 par->InsertInset(pos, new_inset);
2765 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2767 ofstream ofs(fname.c_str());
2769 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2773 LyXParagraph * par = paragraph;
2775 niceFile = nice; // this will be used by Insetincludes.
2777 LyXTextClass const & tclass =
2778 textclasslist.TextClass(params.textclass);
2780 LaTeXFeatures features(params, tclass.numLayouts());
2785 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2788 string sgml_includedfiles = features.getIncludedFiles(fname);
2790 ofs << "<!doctype " << top_element
2791 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2793 if (params.preamble.empty() && sgml_includedfiles.empty())
2796 ofs << "\n [ " << params.preamble
2797 << sgml_includedfiles << " \n]>\n\n";
2800 string top = top_element;
2802 top += params.language->code();
2805 if (!params.options.empty()) {
2807 top += params.options;
2809 sgmlOpenTag(ofs, 0, top);
2811 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2812 << "\n See http://www.lyx.org/ for more information -->\n";
2814 vector<string> environment_stack(10);
2815 vector<string> environment_inner(10);
2816 vector<string> command_stack(10);
2818 bool command_flag = false;
2819 int command_depth = 0;
2820 int command_base = 0;
2822 int depth = 0; // paragraph depth
2825 string command_name;
2831 int desc_on = 0; // description mode
2833 LyXLayout const & style =
2834 textclasslist.Style(params.textclass,
2837 // environment tag closing
2838 for (; depth > par->params.depth(); --depth) {
2839 if (environment_inner[depth] != "!-- --") {
2840 item_name = "listitem";
2841 sgmlCloseTag(ofs, command_depth + depth,
2843 if (environment_inner[depth] == "varlistentry")
2844 sgmlCloseTag(ofs, depth+command_depth,
2845 environment_inner[depth]);
2847 sgmlCloseTag(ofs, depth + command_depth,
2848 environment_stack[depth]);
2849 environment_stack[depth].erase();
2850 environment_inner[depth].erase();
2853 if (depth == par->params.depth()
2854 && environment_stack[depth] != style.latexname()
2855 && !environment_stack[depth].empty()) {
2856 if (environment_inner[depth] != "!-- --") {
2857 item_name= "listitem";
2858 sgmlCloseTag(ofs, command_depth+depth,
2860 if (environment_inner[depth] == "varlistentry")
2862 depth + command_depth,
2863 environment_inner[depth]);
2866 sgmlCloseTag(ofs, depth + command_depth,
2867 environment_stack[depth]);
2869 environment_stack[depth].erase();
2870 environment_inner[depth].erase();
2873 // Write opening SGML tags.
2874 switch (style.latextype) {
2875 case LATEX_PARAGRAPH:
2876 sgmlOpenTag(ofs, depth + command_depth,
2882 LinuxDocError(par, 0,
2883 _("Error : Wrong depth for "
2884 "LatexType Command.\n"));
2886 command_name = style.latexname();
2888 sgmlparam = style.latexparam();
2889 c_params = split(sgmlparam, c_depth,'|');
2891 cmd_depth = lyx::atoi(c_depth);
2894 if (cmd_depth < command_base) {
2895 for (int j = command_depth; j >= command_base; --j)
2896 sgmlCloseTag(ofs, j, command_stack[j]);
2897 command_depth = command_base = cmd_depth;
2898 } else if (cmd_depth <= command_depth) {
2899 for (int j = command_depth; j >= cmd_depth; --j)
2900 sgmlCloseTag(ofs, j, command_stack[j]);
2901 command_depth = cmd_depth;
2903 command_depth = cmd_depth;
2905 command_depth = command_base = cmd_depth;
2906 command_flag = true;
2908 if (command_stack.size() == command_depth + 1)
2909 command_stack.push_back("");
2910 command_stack[command_depth] = command_name;
2912 // treat label as a special case for
2913 // more WYSIWYM handling.
2914 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2915 Inset * inset = par->GetInset(0);
2916 Inset::Code lyx_code = inset->LyxCode();
2917 if (lyx_code == Inset::LABEL_CODE){
2918 command_name += " id=\"";
2919 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2920 command_name += "\"";
2925 sgmlOpenTag(ofs, depth + command_depth, command_name);
2926 if (c_params.empty())
2927 item_name = "title";
2929 item_name = c_params;
2930 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2933 case LATEX_ENVIRONMENT:
2934 case LATEX_ITEM_ENVIRONMENT:
2935 if (depth < par->params.depth()) {
2936 depth = par->params.depth();
2937 environment_stack[depth].erase();
2940 if (environment_stack[depth] != style.latexname()) {
2941 if(environment_stack.size() == depth + 1) {
2942 environment_stack.push_back("!-- --");
2943 environment_inner.push_back("!-- --");
2945 environment_stack[depth] = style.latexname();
2946 environment_inner[depth] = "!-- --";
2947 sgmlOpenTag(ofs, depth + command_depth,
2948 environment_stack[depth]);
2950 if (environment_inner[depth] != "!-- --") {
2951 item_name= "listitem";
2953 command_depth + depth,
2955 if (environment_inner[depth] == "varlistentry")
2957 depth + command_depth,
2958 environment_inner[depth]);
2962 if (style.latextype == LATEX_ENVIRONMENT) {
2963 if (!style.latexparam().empty()) {
2964 if(style.latexparam() == "CDATA")
2967 sgmlOpenTag(ofs, depth + command_depth,
2968 style.latexparam());
2973 desc_on = (style.labeltype == LABEL_MANUAL);
2976 environment_inner[depth]= "varlistentry";
2978 environment_inner[depth]= "listitem";
2980 sgmlOpenTag(ofs, depth + 1 + command_depth,
2981 environment_inner[depth]);
2985 sgmlOpenTag(ofs, depth + 1 + command_depth,
2989 sgmlOpenTag(ofs, depth + 1 + command_depth,
2994 sgmlOpenTag(ofs, depth + command_depth,
3000 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3001 depth + 1 + command_depth);
3005 // write closing SGML tags
3006 switch (style.latextype) {
3008 if (c_params.empty())
3012 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3014 case LATEX_ENVIRONMENT:
3015 if (!style.latexparam().empty()) {
3016 if(style.latexparam() == "CDATA")
3019 sgmlCloseTag(ofs, depth + command_depth,
3020 style.latexparam());
3023 case LATEX_ITEM_ENVIRONMENT:
3024 if (desc_on == 1) break;
3026 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3028 case LATEX_PARAGRAPH:
3029 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3032 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3038 for (; depth >= 0; --depth) {
3039 if (!environment_stack[depth].empty()) {
3040 if (environment_inner[depth] != "!-- --") {
3041 item_name = "listitem";
3042 sgmlCloseTag(ofs, command_depth + depth,
3044 if (environment_inner[depth] == "varlistentry")
3045 sgmlCloseTag(ofs, depth + command_depth,
3046 environment_inner[depth]);
3049 sgmlCloseTag(ofs, depth + command_depth,
3050 environment_stack[depth]);
3054 for (int j = command_depth; j >= command_base; --j)
3055 if (!command_stack[j].empty())
3056 sgmlCloseTag(ofs, j, command_stack[j]);
3059 sgmlCloseTag(ofs, 0, top_element);
3062 // How to check for successful close
3066 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3067 LyXParagraph * par, int & desc_on,
3070 bool emph_flag = false;
3072 LyXLayout const & style = textclasslist.Style(params.textclass,
3075 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3077 int char_line_count = depth;
3078 if (!style.free_spacing)
3079 os << string(depth,' ');
3081 // parsing main loop
3082 for (LyXParagraph::size_type i = 0;
3083 i < par->size(); ++i) {
3084 LyXFont font = par->getFont(params, i);
3086 // handle <emphasis> tag
3087 if (font_old.emph() != font.emph()) {
3088 if (font.emph() == LyXFont::ON) {
3092 os << "</emphasis>";
3097 char c = par->GetChar(i);
3099 if (c == LyXParagraph::META_INSET) {
3100 Inset * inset = par->GetInset(i);
3101 std::ostringstream ost;
3102 inset->DocBook(this, ost);
3103 string tmp_out = ost.str().c_str();
3106 // This code needs some explanation:
3107 // Two insets are treated specially
3108 // label if it is the first element in a command paragraph
3110 // graphics inside tables or figure floats can't go on
3111 // title (the equivalente in latex for this case is caption
3112 // and title should come first
3115 if (desc_on!= 3 || i!= 0) {
3116 if (!tmp_out.empty() && tmp_out[0] == '@') {
3118 extra += frontStrip(tmp_out, '@');
3120 os << frontStrip(tmp_out, '@');
3125 } else if (font.latex() == LyXFont::ON) {
3126 // "TeX"-Mode on ==> SGML-Mode on.
3132 if (par->linuxDocConvertChar(c, sgml_string)
3133 && !style.free_spacing) { // in freespacing
3135 // non-breaking characters
3139 os << "\n</term><listitem><para>";
3152 os << "</emphasis>";
3155 // resets description flag correctly
3157 // <term> not closed...
3164 // This should be enabled when the Chktex class is implemented. (Asger)
3165 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3166 // Other flags: -wall -v0 -x
3167 int Buffer::runChktex()
3169 if (!users->text) return 0;
3171 ProhibitInput(users);
3173 // get LaTeX-Filename
3174 string const name = getLatexName();
3175 string path = OnlyPath(filename);
3177 string const org_path = path;
3178 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3182 Path p(path); // path to LaTeX file
3183 users->owner()->message(_("Running chktex..."));
3185 // Remove all error insets
3186 bool const removedErrorInsets = users->removeAutoInsets();
3188 // Generate the LaTeX file if neccessary
3189 makeLaTeXFile(name, org_path, false);
3192 Chktex chktex(lyxrc.chktex_command, name, filepath);
3193 int res = chktex.run(terr); // run chktex
3196 WriteAlert(_("chktex did not work!"),
3197 _("Could not run with file:"), name);
3198 } else if (res > 0) {
3199 // Insert all errors as errors boxes
3200 users->insertErrors(terr);
3203 // if we removed error insets before we ran chktex or if we inserted
3204 // error insets after we ran chktex, this must be run:
3205 if (removedErrorInsets || res){
3207 users->fitCursor(users->text);
3215 void Buffer::validate(LaTeXFeatures & features) const
3217 LyXParagraph * par = paragraph;
3218 LyXTextClass const & tclass =
3219 textclasslist.TextClass(params.textclass);
3221 // AMS Style is at document level
3223 features.amsstyle = (params.use_amsmath ||
3224 tclass.provides(LyXTextClass::amsmath));
3227 // We don't use "lyxerr.debug" because of speed. (Asger)
3228 if (lyxerr.debugging(Debug::LATEX))
3229 lyxerr << "Paragraph: " << par << endl;
3231 // Now just follow the list of paragraphs and run
3232 // validate on each of them.
3233 par->validate(features);
3235 // and then the next paragraph
3239 // the bullet shapes are buffer level not paragraph level
3240 // so they are tested here
3241 for (int i = 0; i < 4; ++i) {
3242 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3243 int const font = params.user_defined_bullets[i].getFont();
3245 int const c = params
3246 .user_defined_bullets[i]
3253 features.latexsym = true;
3255 } else if (font == 1) {
3256 features.amssymb = true;
3257 } else if ((font >= 2 && font <= 5)) {
3258 features.pifont = true;
3263 if (lyxerr.debugging(Debug::LATEX)) {
3264 features.showStruct();
3269 void Buffer::setPaperStuff()
3271 params.papersize = BufferParams::PAPER_DEFAULT;
3272 char const c1 = params.paperpackage;
3273 if (c1 == BufferParams::PACKAGE_NONE) {
3274 char const c2 = params.papersize2;
3275 if (c2 == BufferParams::VM_PAPER_USLETTER)
3276 params.papersize = BufferParams::PAPER_USLETTER;
3277 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3278 params.papersize = BufferParams::PAPER_LEGALPAPER;
3279 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3280 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3281 else if (c2 == BufferParams::VM_PAPER_A3)
3282 params.papersize = BufferParams::PAPER_A3PAPER;
3283 else if (c2 == BufferParams::VM_PAPER_A4)
3284 params.papersize = BufferParams::PAPER_A4PAPER;
3285 else if (c2 == BufferParams::VM_PAPER_A5)
3286 params.papersize = BufferParams::PAPER_A5PAPER;
3287 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3288 (c2 == BufferParams::VM_PAPER_B5))
3289 params.papersize = BufferParams::PAPER_B5PAPER;
3290 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3291 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3292 params.papersize = BufferParams::PAPER_A4PAPER;
3296 // This function should be in Buffer because it's a buffer's property (ale)
3297 string const Buffer::getIncludeonlyList(char delim)
3300 for (inset_iterator it = inset_iterator_begin();
3301 it != inset_iterator_end(); ++it) {
3302 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3303 InsetInclude * insetinc =
3304 static_cast<InsetInclude *>(*it);
3305 if (insetinc->isIncludeOnly()) {
3308 lst += insetinc->getRelFileBaseName();
3312 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3317 vector<string> const Buffer::getLabelList()
3319 /// if this is a child document and the parent is already loaded
3320 /// Use the parent's list instead [ale990407]
3321 if (!params.parentname.empty()
3322 && bufferlist.exists(params.parentname)) {
3323 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3325 return tmp->getLabelList();
3328 vector<string> label_list;
3329 for (inset_iterator it = inset_iterator_begin();
3330 it != inset_iterator_end(); ++it) {
3331 vector<string> const l = (*it)->getLabelList();
3332 label_list.insert(label_list.end(), l.begin(), l.end());
3338 Buffer::Lists const Buffer::getLists() const
3341 LyXParagraph * par = paragraph;
3343 LyXTextClassList::size_type cap;
3344 boost::tie(found, cap) = textclasslist
3345 .NumberOfLayout(params.textclass, "Caption");
3348 char const labeltype =
3349 textclasslist.Style(params.textclass,
3350 par->GetLayout()).labeltype;
3352 if (labeltype >= LABEL_COUNTER_CHAPTER
3353 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3354 // insert this into the table of contents
3355 SingleList & item = l["TOC"];
3358 textclasslist.TextClass(params.textclass).maxcounter());
3359 item.push_back(TocItem(par, depth, par->String(this, true)));
3361 // For each paragrph, traverse its insets and look for
3365 LyXParagraph::inset_iterator it =
3366 par->inset_iterator_begin();
3367 LyXParagraph::inset_iterator end =
3368 par->inset_iterator_end();
3370 for (; it != end; ++it) {
3371 if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3373 static_cast<InsetFloat*>(*it);
3375 string const type = il->type();
3377 // Now find the caption in the float...
3378 // We now tranverse the paragraphs of
3380 LyXParagraph * tmp = il->inset.par;
3382 if (tmp->layout == cap) {
3383 SingleList & item = l[type];
3385 tostr(item.size()+1) + ". " + tmp->String(this, false);
3386 item.push_back(TocItem(tmp, 0 , str));
3393 lyxerr << "caption not found" << endl;
3402 // This is also a buffer property (ale)
3403 vector<pair<string, string> > const Buffer::getBibkeyList()
3405 /// if this is a child document and the parent is already loaded
3406 /// Use the parent's list instead [ale990412]
3407 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3408 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3410 return tmp->getBibkeyList();
3413 vector<pair<string, string> > keys;
3414 LyXParagraph * par = paragraph;
3417 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3418 par->String(this, false)));
3422 // Might be either using bibtex or a child has bibliography
3424 for (inset_iterator it = inset_iterator_begin();
3425 it != inset_iterator_end(); ++it) {
3426 // Search for Bibtex or Include inset
3427 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3428 vector<pair<string,string> > tmp =
3429 static_cast<InsetBibtex*>(*it)->getKeys(this);
3430 keys.insert(keys.end(), tmp.begin(), tmp.end());
3431 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3432 vector<pair<string,string> > const tmp =
3433 static_cast<InsetInclude*>(*it)->getKeys();
3434 keys.insert(keys.end(), tmp.begin(), tmp.end());
3443 bool Buffer::isDepClean(string const & name) const
3445 DEPCLEAN * item = dep_clean;
3446 while (item && item->master != name)
3448 if (!item) return true;
3453 void Buffer::markDepClean(string const & name)
3456 dep_clean = new DEPCLEAN;
3457 dep_clean->clean = true;
3458 dep_clean->master = name;
3459 dep_clean->next = 0;
3461 DEPCLEAN * item = dep_clean;
3462 while (item && item->master != name)
3467 item = new DEPCLEAN;
3469 item->master = name;
3476 bool Buffer::Dispatch(string const & command)
3478 // Split command string into command and argument
3480 string line = frontStrip(command);
3481 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3483 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3487 bool Buffer::Dispatch(int action, string const & argument)
3489 bool dispatched = true;
3492 Exporter::Export(this, argument, false);
3502 void Buffer::resize()
3504 /// resize the BufferViews!
3510 void Buffer::resizeInsets(BufferView * bv)
3512 /// then remove all LyXText in text-insets
3513 LyXParagraph * par = paragraph;
3514 for (; par; par = par->next()) {
3515 par->resizeInsetsLyXText(bv);
3520 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3523 LyXParagraph * par = paragraph;
3525 par->ChangeLanguage(params, from, to);
3531 bool Buffer::isMultiLingual()
3533 LyXParagraph * par = paragraph;
3535 if (par->isMultiLingual(params))
3543 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3544 LyXParagraph::size_type pos)
3547 it = par->InsetIterator(pos);
3548 if (it == par->inset_iterator_end()) {
3555 void Buffer::inset_iterator::SetParagraph()
3558 it = par->inset_iterator_begin();
3559 if (it != par->inset_iterator_end())
3564 // We maintain an invariant that whenever par = 0 then it = 0