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 "support/filetools.h"
81 #include "support/path.h"
86 #include "LaTeXFeatures.h"
87 #include "support/syscall.h"
88 #include "support/lyxlib.h"
89 #include "support/FileInfo.h"
90 #include "support/lyxmanip.h"
94 #include "lyx_gui_misc.h" // WarnReadonly()
95 #include "frontends/Dialogs.h"
99 #include "converter.h"
101 using std::stringstream;
110 using std::make_pair;
118 // all these externs should eventually be removed.
119 extern BufferList bufferlist;
121 extern LyXAction lyxaction;
125 const int LYX_FORMAT = 218;
129 extern int tex_code_break_column;
132 Buffer::Buffer(string const & file, bool ronly)
134 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
136 filepath = OnlyPath(file);
145 if (read_only || (lyxrc.use_tempdir)) {
146 tmppath = CreateBufferTmpDir();
147 } else tmppath.erase();
153 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
154 // here the buffer should take care that it is
155 // saved properly, before it goes into the void.
157 // make sure that views using this buffer
162 if (!tmppath.empty()) {
163 DestroyBufferTmpDir(tmppath);
166 LyXParagraph * par = paragraph;
167 LyXParagraph * tmppar;
169 tmppar = par->next();
177 string const Buffer::getLatexName(bool no_path) const
180 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
183 return ChangeExtension(MakeLatexName(filename),
188 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
190 string const filename = getLatexName(false);
192 if (filename.empty())
193 return make_pair(Buffer::latexlog, string());
195 string path = OnlyPath(filename);
197 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
200 string const fname = AddName(path,
201 OnlyFilename(ChangeExtension(filename,
204 AddName(path, OnlyFilename(
205 ChangeExtension(filename,
206 formats.Extension("literate") + ".out")));
208 // If no Latex log or Build log is newer, show Build log
210 FileInfo const f_fi(fname);
211 FileInfo const b_fi(bname);
214 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
215 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
216 return make_pair(Buffer::buildlog, bname);
218 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
219 return make_pair(Buffer::latexlog, fname);
223 void Buffer::setReadonly(bool flag)
225 if (read_only != flag) {
228 users->owner()->getDialogs()->updateBufferDependent(false);
231 WarnReadonly(filename);
236 bool Buffer::saveParamsAsDefaults() // const
238 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
240 Buffer defaults = Buffer(fname);
242 // Use the current buffer's parameters as default
243 defaults.params = params;
245 // add an empty paragraph. Is this enough?
246 defaults.paragraph = new LyXParagraph;
248 return defaults.writeFile(defaults.filename, false);
252 /// Update window titles of all users
253 // Should work on a list
254 void Buffer::updateTitles() const
256 if (users) users->owner()->updateWindowTitle();
260 /// Reset autosave timer of all users
261 // Should work on a list
262 void Buffer::resetAutosaveTimers() const
264 if (users) users->owner()->resetAutosaveTimer();
268 void Buffer::setFileName(string const & newfile)
270 filename = MakeAbsPath(newfile);
271 filepath = OnlyPath(filename);
272 setReadonly(IsFileWriteable(filename) == 0);
277 // candidate for move to BufferView
278 // (at least some parts in the beginning of the func)
281 // changed to be public and have one parameter
282 // if par = 0 normal behavior
283 // else insert behavior
284 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
285 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
288 char depth = 0; // signed or unsigned?
289 bool the_end_read = false;
291 LyXParagraph * return_par = 0;
292 LyXFont font(LyXFont::ALL_INHERIT, params.language);
293 if (file_format < 216 && params.language->lang() == "hebrew")
294 font.setLanguage(default_language);
295 // If we are inserting, we cheat and get a token in advance
296 bool has_token = false;
300 par = new LyXParagraph;
302 users->text->BreakParagraph(users);
303 return_par = users->text->FirstParagraph();
306 // We don't want to adopt the parameters from the
307 // document we insert, so we skip until the text begins:
310 pretoken = lex.GetString();
311 if (pretoken == "\\layout") {
323 pretoken = lex.GetString();
326 if (pretoken.empty()) continue;
329 parseSingleLyXformat2Token(lex, par, return_par,
330 pretoken, pos, depth,
338 paragraph = return_par;
344 // We'll remove this later. (Lgb)
347 string last_inset_read;
353 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
354 LyXParagraph *& return_par,
355 string const & token, int & pos,
356 char & depth, LyXFont & font
359 bool the_end_read = false;
360 #ifndef NO_PEXTRA_REALLY
361 // This is super temporary but is needed to get the compability
362 // mode for minipages work correctly together with new tabulars.
363 static int call_depth = 0;
365 bool checkminipage = false;
366 static LyXParagraph * minipar = 0;
367 static LyXParagraph * parBeforeMinipage = 0;
370 if (token[0] != '\\') {
371 for (string::const_iterator cit = token.begin();
372 cit != token.end(); ++cit)
374 par->InsertChar(pos, (*cit), font);
377 checkminipage = true;
378 } else if (token == "\\i") {
379 Inset * inset = new InsetLatexAccent;
380 inset->Read(this, lex);
381 par->InsertInset(pos, inset, font);
383 } else if (token == "\\layout") {
385 string const layoutname = lex.GetString();
386 pair<bool, LyXTextClass::LayoutList::size_type> pp
387 = textclasslist.NumberOfLayout(params.textclass,
391 // The is the compability reading of layout caption.
392 // It can be removed in LyX version 1.3.0. (Lgb)
393 if (compare_no_case(layoutname, "caption") == 0) {
394 // We expect that the par we are now working on is
395 // really inside a InsetText inside a InsetFloat.
396 // We also know that captions can only be
397 // one paragraph. (Lgb)
399 // We should now read until the next "\layout"
401 // This is probably not good enough, what if the
402 // caption is the last par in the document (Lgb)
403 istream & ist = lex.getStream();
409 if (prefixIs(line, "\\layout")) {
413 if (prefixIs(line, "\\begin_inset"))
415 if (prefixIs(line, "\\end_inset")) {
426 // Now we should have the whole layout in ss
427 // we should now be able to give this to the
429 ss << "\\end_inset\n";
431 // This seems like a bug in stringstream.
432 // We really should be able to use ss
434 istringstream is(ss.str());
436 tmplex.setStream(is);
437 Inset * inset = new InsetCaption;
438 inset->Read(this, tmplex);
439 par->InsertInset(pos, inset, font);
447 par = new LyXParagraph(par);
451 par->layout = pp.second;
454 // use default layout "Standard" (0)
457 // Test whether the layout is obsolete.
458 LyXLayout const & layout =
459 textclasslist.Style(params.textclass,
461 if (!layout.obsoleted_by().empty())
462 par->layout = textclasslist
463 .NumberOfLayout(params.textclass,
464 layout.obsoleted_by())
466 par->params.depth(depth);
467 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
468 if (file_format < 216
469 && params.language->lang() == "hebrew")
470 font.setLanguage(default_language);
475 } else if (token == "\\begin_float") {
476 // This is the compability reader. It can be removed in
477 // LyX version 1.3.0. (Lgb)
479 string const tmptok = lex.GetString();
480 //lyxerr << "old float: " << tmptok << endl;
483 stringstream old_float;
485 if (tmptok == "footnote") {
486 inset = new InsetFoot;
487 } else if (tmptok == "margin") {
488 inset = new InsetMarginal;
489 } else if (tmptok == "fig") {
490 inset = new InsetFloat("figure");
491 old_float << "placement htbp\n";
492 } else if (tmptok == "tab") {
493 inset = new InsetFloat("table");
494 old_float << "placement htbp\n";
495 } else if (tmptok == "alg") {
496 inset = new InsetFloat("algorithm");
497 old_float << "placement htbp\n";
498 } else if (tmptok == "wide-fig") {
499 InsetFloat * tmp = new InsetFloat("figure");
502 old_float << "placement htbp\n";
503 } else if (tmptok == "wide-tab") {
504 InsetFloat * tmp = new InsetFloat("table");
507 old_float << "placement htbp\n";
512 return false; // no end read yet
515 old_float << "collapsed true\n";
517 // Here we need to check for \end_deeper and handle that
518 // before we do the footnote parsing.
519 // This _is_ a hack! (Lgb)
522 string const tmp = lex.GetString();
523 if (tmp == "\\end_deeper") {
524 //lyxerr << "\\end_deeper caught!" << endl;
526 lex.printError("\\end_deeper: "
527 "depth is already null");
532 old_float << tmp << ' ';
537 old_float << lex.getLongString("\\end_float")
538 << "\n\\end_inset\n";
539 //lyxerr << "Float Body:\n" << old_float.str() << endl;
540 // That this does not work seems like a bug
541 // in stringstream. (Lgb)
542 istringstream istr(old_float.str());
544 nylex.setStream(istr);
545 inset->Read(this, nylex);
546 par->InsertInset(pos, inset, font);
548 } else if (token == "\\begin_deeper") {
550 } else if (token == "\\end_deeper") {
552 lex.printError("\\end_deeper: "
553 "depth is already null");
557 } else if (token == "\\begin_preamble") {
558 params.readPreamble(lex);
559 } else if (token == "\\textclass") {
561 pair<bool, LyXTextClassList::size_type> pp =
562 textclasslist.NumberOfClass(lex.GetString());
564 params.textclass = pp.second;
566 WriteAlert(string(_("Textclass error")),
567 string(_("The document uses an unknown textclass \"")) +
568 lex.GetString() + string("\"."),
569 string(_("LyX will not be able to produce output correctly.")));
570 params.textclass = 0;
572 if (!textclasslist.Load(params.textclass)) {
573 // if the textclass wasn't loaded properly
574 // we need to either substitute another
575 // or stop loading the file.
576 // I can substitute but I don't see how I can
577 // stop loading... ideas?? ARRae980418
578 WriteAlert(_("Textclass Loading Error!"),
579 string(_("Can't load textclass ")) +
580 textclasslist.NameOfClass(params.textclass),
581 _("-- substituting default"));
582 params.textclass = 0;
584 } else if (token == "\\options") {
586 params.options = lex.GetString();
587 } else if (token == "\\language") {
588 params.readLanguage(lex);
589 } else if (token == "\\fontencoding") {
591 } else if (token == "\\inputencoding") {
593 params.inputenc = lex.GetString();
594 } else if (token == "\\graphics") {
595 params.readGraphicsDriver(lex);
596 } else if (token == "\\fontscheme") {
598 params.fonts = lex.GetString();
599 } else if (token == "\\noindent") {
600 par->params.noindent(true);
601 } else if (token == "\\fill_top") {
602 par->params.spaceTop(VSpace(VSpace::VFILL));
603 } else if (token == "\\fill_bottom") {
604 par->params.spaceBottom(VSpace(VSpace::VFILL));
605 } else if (token == "\\line_top") {
606 par->params.lineTop(true);
607 } else if (token == "\\line_bottom") {
608 par->params.lineBottom(true);
609 } else if (token == "\\pagebreak_top") {
610 par->params.pagebreakTop(true);
611 } else if (token == "\\pagebreak_bottom") {
612 par->params.pagebreakBottom(true);
613 } else if (token == "\\start_of_appendix") {
614 par->params.startOfAppendix(true);
615 } else if (token == "\\paragraph_separation") {
616 int tmpret = lex.FindToken(string_paragraph_separation);
617 if (tmpret == -1) ++tmpret;
618 if (tmpret != LYX_LAYOUT_DEFAULT)
619 params.paragraph_separation =
620 static_cast<BufferParams::PARSEP>(tmpret);
621 } else if (token == "\\defskip") {
623 params.defskip = VSpace(lex.GetString());
624 } else if (token == "\\epsfig") { // obsolete
625 // Indeed it is obsolete, but we HAVE to be backwards
626 // compatible until 0.14, because otherwise all figures
627 // in existing documents are irretrivably lost. (Asger)
628 params.readGraphicsDriver(lex);
629 } else if (token == "\\quotes_language") {
630 int tmpret = lex.FindToken(string_quotes_language);
631 if (tmpret == -1) ++tmpret;
632 if (tmpret != LYX_LAYOUT_DEFAULT) {
633 InsetQuotes::quote_language tmpl =
634 InsetQuotes::EnglishQ;
637 tmpl = InsetQuotes::EnglishQ;
640 tmpl = InsetQuotes::SwedishQ;
643 tmpl = InsetQuotes::GermanQ;
646 tmpl = InsetQuotes::PolishQ;
649 tmpl = InsetQuotes::FrenchQ;
652 tmpl = InsetQuotes::DanishQ;
655 params.quotes_language = tmpl;
657 } else if (token == "\\quotes_times") {
659 switch (lex.GetInteger()) {
661 params.quotes_times = InsetQuotes::SingleQ;
664 params.quotes_times = InsetQuotes::DoubleQ;
667 } else if (token == "\\papersize") {
668 int tmpret = lex.FindToken(string_papersize);
672 params.papersize2 = tmpret;
673 } else if (token == "\\paperpackage") {
674 int tmpret = lex.FindToken(string_paperpackages);
677 params.paperpackage = BufferParams::PACKAGE_NONE;
679 params.paperpackage = tmpret;
680 } else if (token == "\\use_geometry") {
682 params.use_geometry = lex.GetInteger();
683 } else if (token == "\\use_amsmath") {
685 params.use_amsmath = lex.GetInteger();
686 } else if (token == "\\paperorientation") {
687 int tmpret = lex.FindToken(string_orientation);
688 if (tmpret == -1) ++tmpret;
689 if (tmpret != LYX_LAYOUT_DEFAULT)
690 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
691 } else if (token == "\\paperwidth") {
693 params.paperwidth = lex.GetString();
694 } else if (token == "\\paperheight") {
696 params.paperheight = lex.GetString();
697 } else if (token == "\\leftmargin") {
699 params.leftmargin = lex.GetString();
700 } else if (token == "\\topmargin") {
702 params.topmargin = lex.GetString();
703 } else if (token == "\\rightmargin") {
705 params.rightmargin = lex.GetString();
706 } else if (token == "\\bottommargin") {
708 params.bottommargin = lex.GetString();
709 } else if (token == "\\headheight") {
711 params.headheight = lex.GetString();
712 } else if (token == "\\headsep") {
714 params.headsep = lex.GetString();
715 } else if (token == "\\footskip") {
717 params.footskip = lex.GetString();
718 } else if (token == "\\paperfontsize") {
720 params.fontsize = strip(lex.GetString());
721 } else if (token == "\\papercolumns") {
723 params.columns = lex.GetInteger();
724 } else if (token == "\\papersides") {
726 switch (lex.GetInteger()) {
728 case 1: params.sides = LyXTextClass::OneSide; break;
729 case 2: params.sides = LyXTextClass::TwoSides; break;
731 } else if (token == "\\paperpagestyle") {
733 params.pagestyle = strip(lex.GetString());
734 } else if (token == "\\bullet") {
736 int const index = lex.GetInteger();
738 int temp_int = lex.GetInteger();
739 params.user_defined_bullets[index].setFont(temp_int);
740 params.temp_bullets[index].setFont(temp_int);
742 temp_int = lex.GetInteger();
743 params.user_defined_bullets[index].setCharacter(temp_int);
744 params.temp_bullets[index].setCharacter(temp_int);
746 temp_int = lex.GetInteger();
747 params.user_defined_bullets[index].setSize(temp_int);
748 params.temp_bullets[index].setSize(temp_int);
750 string const temp_str = lex.GetString();
751 if (temp_str != "\\end_bullet") {
752 // this element isn't really necessary for
753 // parsing but is easier for humans
754 // to understand bullets. Put it back and
755 // set a debug message?
756 lex.printError("\\end_bullet expected, got" + temp_str);
757 //how can I put it back?
759 } else if (token == "\\bulletLaTeX") {
761 int const index = lex.GetInteger();
763 string temp_str = lex.GetString();
765 while (temp_str != "\\end_bullet") {
766 // this loop structure is needed when user
767 // enters an empty string since the first
768 // thing returned will be the \\end_bullet
770 // if the LaTeX entry has spaces. Each element
771 // therefore needs to be read in turn
774 temp_str = lex.GetString();
776 params.user_defined_bullets[index].setText(sum_str);
777 params.temp_bullets[index].setText(sum_str);
778 } else if (token == "\\secnumdepth") {
780 params.secnumdepth = lex.GetInteger();
781 } else if (token == "\\tocdepth") {
783 params.tocdepth = lex.GetInteger();
784 } else if (token == "\\spacing") {
786 string const tmp = strip(lex.GetString());
787 Spacing::Space tmp_space = Spacing::Default;
789 if (tmp == "single") {
790 tmp_space = Spacing::Single;
791 } else if (tmp == "onehalf") {
792 tmp_space = Spacing::Onehalf;
793 } else if (tmp == "double") {
794 tmp_space = Spacing::Double;
795 } else if (tmp == "other") {
797 tmp_space = Spacing::Other;
798 tmp_val = lex.GetFloat();
800 lex.printError("Unknown spacing token: '$$Token'");
802 // Small hack so that files written with klyx will be
805 par->params.spacing(Spacing(tmp_space, tmp_val));
807 params.spacing.set(tmp_space, tmp_val);
809 } else if (token == "\\paragraph_spacing") {
811 string const tmp = strip(lex.GetString());
812 if (tmp == "single") {
813 par->params.spacing(Spacing(Spacing::Single));
814 } else if (tmp == "onehalf") {
815 par->params.spacing(Spacing(Spacing::Onehalf));
816 } else if (tmp == "double") {
817 par->params.spacing(Spacing(Spacing::Double));
818 } else if (tmp == "other") {
820 par->params.spacing(Spacing(Spacing::Other,
823 lex.printError("Unknown spacing token: '$$Token'");
825 } else if (token == "\\float_placement") {
827 params.float_placement = lex.GetString();
828 } else if (token == "\\family") {
830 font.setLyXFamily(lex.GetString());
831 } else if (token == "\\series") {
833 font.setLyXSeries(lex.GetString());
834 } else if (token == "\\shape") {
836 font.setLyXShape(lex.GetString());
837 } else if (token == "\\size") {
839 font.setLyXSize(lex.GetString());
840 } else if (token == "\\latex") {
842 string const tok = lex.GetString();
843 // This is dirty, but gone with LyX3. (Asger)
844 if (tok == "no_latex")
845 font.setLatex(LyXFont::OFF);
846 else if (tok == "latex")
847 font.setLatex(LyXFont::ON);
848 else if (tok == "default")
849 font.setLatex(LyXFont::INHERIT);
851 lex.printError("Unknown LaTeX font flag "
853 } else if (token == "\\lang") {
855 string const tok = lex.GetString();
856 Language const * lang = languages.getLanguage(tok);
858 font.setLanguage(lang);
860 font.setLanguage(params.language);
861 lex.printError("Unknown language `$$Token'");
863 } else if (token == "\\numeric") {
865 font.setNumber(font.setLyXMisc(lex.GetString()));
866 } else if (token == "\\emph") {
868 font.setEmph(font.setLyXMisc(lex.GetString()));
869 } else if (token == "\\bar") {
871 string const tok = lex.GetString();
872 // This is dirty, but gone with LyX3. (Asger)
874 font.setUnderbar(LyXFont::ON);
875 else if (tok == "no")
876 font.setUnderbar(LyXFont::OFF);
877 else if (tok == "default")
878 font.setUnderbar(LyXFont::INHERIT);
880 lex.printError("Unknown bar font flag "
882 } else if (token == "\\noun") {
884 font.setNoun(font.setLyXMisc(lex.GetString()));
885 } else if (token == "\\color") {
887 font.setLyXColor(lex.GetString());
888 } else if (token == "\\align") {
889 int tmpret = lex.FindToken(string_align);
890 if (tmpret == -1) ++tmpret;
891 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
892 int const tmpret2 = int(pow(2.0, tmpret));
893 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
894 par->params.align(LyXAlignment(tmpret2));
896 } else if (token == "\\added_space_top") {
898 par->params.spaceTop(VSpace(lex.GetString()));
899 } else if (token == "\\added_space_bottom") {
901 par->params.spaceBottom(VSpace(lex.GetString()));
902 #ifndef NO_PEXTRA_REALLY
903 } else if (token == "\\pextra_type") {
905 par->params.pextraType(lex.GetInteger());
906 } else if (token == "\\pextra_width") {
908 par->params.pextraWidth(lex.GetString());
909 } else if (token == "\\pextra_widthp") {
911 par->params.pextraWidthp(lex.GetString());
912 } else if (token == "\\pextra_alignment") {
914 par->params.pextraAlignment(lex.GetInteger());
915 } else if (token == "\\pextra_hfill") {
917 par->params.pextraHfill(lex.GetInteger());
918 } else if (token == "\\pextra_start_minipage") {
920 par->params.pextraStartMinipage(lex.GetInteger());
922 } else if (token == "\\labelwidthstring") {
924 par->params.labelWidthString(lex.GetString());
925 // do not delete this token, it is still needed!
926 } else if (token == "\\end_inset") {
927 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
928 << "Last inset read was: " << last_inset_read
930 // Simply ignore this. The insets do not have
932 // But insets should read it, it is a part of
933 // the inset isn't it? Lgb.
934 } else if (token == "\\begin_inset") {
935 readInset(lex, par, pos, font);
936 } else if (token == "\\SpecialChar") {
937 LyXLayout const & layout =
938 textclasslist.Style(params.textclass,
941 // Insets don't make sense in a free-spacing context! ---Kayvan
942 if (layout.free_spacing) {
945 string next_token = lex.GetString();
946 if (next_token == "\\-") {
947 par->InsertChar(pos, '-', font);
948 } else if (next_token == "\\protected_separator"
949 || next_token == "~") {
950 par->InsertChar(pos, ' ', font);
952 lex.printError("Token `$$Token' "
954 "paragraph layout!");
959 Inset * inset = new InsetSpecialChar;
960 inset->Read(this, lex);
961 par->InsertInset(pos, inset, font);
964 } else if (token == "\\newline") {
965 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
967 } else if (token == "\\LyXTable") {
968 Inset * inset = new InsetTabular(*this);
969 inset->Read(this, lex);
970 par->InsertInset(pos, inset, font);
972 // because of OLD_TABULAR_READ where tabulars have been
974 checkminipage = true;
975 } else if (token == "\\hfill") {
976 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
978 } else if (token == "\\protected_separator") { // obsolete
979 // This is a backward compability thingie. (Lgb)
980 // Remove it later some time...introduced with fileformat
982 LyXLayout const & layout =
983 textclasslist.Style(params.textclass,
986 if (layout.free_spacing) {
987 par->InsertChar(pos, ' ', font);
989 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
990 par->InsertInset(pos, inset, font);
993 } else if (token == "\\bibitem") { // ale970302
995 InsetCommandParams p("bibitem", "dummy");
996 par->bibkey = new InsetBibKey(p);
998 par->bibkey->Read(this, lex);
999 } else if (token == "\\backslash") {
1000 par->InsertChar(pos, '\\', font);
1002 } else if (token == "\\the_end") {
1003 the_end_read = true;
1004 minipar = parBeforeMinipage = 0;
1006 // This should be insurance for the future: (Asger)
1007 lex.printError("Unknown token `$$Token'. "
1008 "Inserting as text.");
1009 string::const_iterator cit = token.begin();
1010 string::const_iterator end = token.end();
1011 for (; cit != end; ++cit) {
1012 par->InsertChar(pos, (*cit), font);
1016 #ifndef NO_PEXTRA_REALLY
1017 // now check if we have a minipage paragraph as at this
1018 // point we already read all the necessary data!
1019 // this cannot be done in layout because there we did
1020 // not read yet the paragraph PEXTRA-params (Jug)
1022 // BEGIN pextra_minipage compability
1023 // This should be removed in 1.3.x (Lgb)
1025 // This compability code is not perfect. In a couple
1026 // of rand cases it fails. When the minipage par is
1027 // the first par in the document, and when there are
1028 // none or only one regular paragraphs after the
1029 // minipage. Currently I am not investing any effort
1030 // in fixing those cases.
1032 //lyxerr << "Call depth: " << call_depth << endl;
1033 if (checkminipage && (call_depth == 1)) {
1034 checkminipage = false;
1035 if (minipar && (minipar != par) &&
1036 (par->params.pextraType()==LyXParagraph::PEXTRA_MINIPAGE))
1038 lyxerr << "minipages in a row" << endl;
1039 if (par->params.pextraStartMinipage()) {
1040 lyxerr << "start new minipage" << endl;
1041 // minipages in a row
1042 par->previous()->next(0);
1045 LyXParagraph * tmp = minipar;
1047 tmp->params.pextraType(0);
1048 tmp->params.pextraWidth(string());
1049 tmp->params.pextraWidthp(string());
1050 tmp->params.pextraAlignment(0);
1051 tmp->params.pextraHfill(false);
1052 tmp->params.pextraStartMinipage(false);
1055 // create a new paragraph to insert the
1056 // minipages in the following case
1057 if (par->params.pextraStartMinipage() &&
1058 !par->params.pextraHfill())
1060 LyXParagraph * p = new LyXParagraph;
1062 p->previous(parBeforeMinipage);
1063 parBeforeMinipage->next(p);
1065 p->params.depth(parBeforeMinipage->params.depth());
1066 parBeforeMinipage = p;
1068 InsetMinipage * mini = new InsetMinipage;
1069 mini->pos(static_cast<InsetMinipage::Position>(par->params.pextraAlignment()));
1070 mini->width(par->params.pextraWidth());
1071 if (!par->params.pextraWidthp().empty()) {
1072 lyxerr << "WP:" << mini->width() << endl;
1073 mini->width(tostr(par->params.pextraWidthp())+"%");
1075 mini->inset.par = par;
1076 // Insert the minipage last in the
1077 // previous paragraph.
1078 if (par->params.pextraHfill()) {
1079 parBeforeMinipage->InsertChar
1080 (parBeforeMinipage->size(), LyXParagraph::META_HFILL);
1082 parBeforeMinipage->InsertInset
1083 (parBeforeMinipage->size(), mini);
1087 lyxerr << "new minipage par" << endl;
1088 //nothing to do just continue reading
1091 } else if (minipar && (minipar != par)) {
1092 lyxerr << "last minipage par read" << endl;
1093 // The last paragraph read was not part of a
1094 // minipage but the par linked list is...
1095 // So we need to remove the last par from the
1097 if (par->previous())
1098 par->previous()->next(0);
1099 par->previous(parBeforeMinipage);
1100 parBeforeMinipage->next(par);
1101 LyXParagraph * tmp = minipar;
1103 tmp->params.pextraType(0);
1104 tmp->params.pextraWidth(string());
1105 tmp->params.pextraWidthp(string());
1106 tmp->params.pextraAlignment(0);
1107 tmp->params.pextraHfill(false);
1108 tmp->params.pextraStartMinipage(false);
1111 depth = parBeforeMinipage->params.depth();
1112 minipar = parBeforeMinipage = 0;
1113 } else if (!minipar &&
1114 (par->params.pextraType() == LyXParagraph::PEXTRA_MINIPAGE))
1116 // par is the first paragraph in a minipage
1117 lyxerr << "begin minipage" << endl;
1118 // To minimize problems for
1119 // the users we will insert
1120 // the first minipage in
1121 // a sequence of minipages
1122 // in its own paragraph.
1123 LyXParagraph * p = new LyXParagraph;
1125 p->previous(par->previous());
1127 p->params.depth(depth);
1128 par->params.depth(0);
1130 if (par->previous())
1131 par->previous()->next(p);
1133 parBeforeMinipage = p;
1135 if (!return_par || (return_par == par))
1138 InsetMinipage * mini = new InsetMinipage;
1139 mini->pos(static_cast<InsetMinipage::Position>(minipar->params.pextraAlignment()));
1140 mini->width(minipar->params.pextraWidth());
1141 if (!par->params.pextraWidthp().empty()) {
1142 lyxerr << "WP:" << mini->width() << endl;
1143 mini->width(tostr(par->params.pextraWidthp())+"%");
1145 mini->inset.par = minipar;
1147 // Insert the minipage last in the
1148 // previous paragraph.
1149 if (minipar->params.pextraHfill()) {
1150 parBeforeMinipage->InsertChar
1151 (parBeforeMinipage->size(),LyXParagraph::META_HFILL);
1153 parBeforeMinipage->InsertInset
1154 (parBeforeMinipage->size(), mini);
1157 // End of pextra_minipage compability
1160 return the_end_read;
1164 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1165 int & pos, LyXFont & font)
1167 // consistency check
1168 if (lex.GetString() != "\\begin_inset") {
1169 lyxerr << "Buffer::readInset: Consistency check failed."
1176 string const tmptok = lex.GetString();
1177 last_inset_read = tmptok;
1179 // test the different insets
1180 if (tmptok == "LatexCommand") {
1181 InsetCommandParams inscmd;
1184 if (inscmd.getCmdName() == "cite") {
1185 inset = new InsetCitation(inscmd);
1186 } else if (inscmd.getCmdName() == "bibitem") {
1187 lex.printError("Wrong place for bibitem");
1188 inset = new InsetBibKey(inscmd);
1189 } else if (inscmd.getCmdName() == "BibTeX") {
1190 inset = new InsetBibtex(inscmd);
1191 } else if (inscmd.getCmdName() == "index") {
1192 inset = new InsetIndex(inscmd);
1193 } else if (inscmd.getCmdName() == "include") {
1194 inset = new InsetInclude(inscmd, *this);
1195 } else if (inscmd.getCmdName() == "label") {
1196 inset = new InsetLabel(inscmd);
1197 } else if (inscmd.getCmdName() == "url"
1198 || inscmd.getCmdName() == "htmlurl") {
1199 inset = new InsetUrl(inscmd);
1200 } else if (inscmd.getCmdName() == "ref"
1201 || inscmd.getCmdName() == "pageref"
1202 || inscmd.getCmdName() == "vref"
1203 || inscmd.getCmdName() == "vpageref"
1204 || inscmd.getCmdName() == "prettyref") {
1205 if (!inscmd.getOptions().empty()
1206 || !inscmd.getContents().empty()) {
1207 inset = new InsetRef(inscmd, *this);
1209 } else if (inscmd.getCmdName() == "tableofcontents"
1210 || inscmd.getCmdName() == "listofalgorithms"
1211 || inscmd.getCmdName() == "listoffigures"
1212 || inscmd.getCmdName() == "listoftables"
1213 || inscmd.getCmdName() == "listof{algorithm}{List of Algorithms}") {
1214 inset = new InsetTOC(inscmd);
1215 } else if (inscmd.getCmdName() == "printindex") {
1216 inset = new InsetPrintIndex(inscmd);
1217 } else if (inscmd.getCmdName() == "lyxparent") {
1218 inset = new InsetParent(inscmd, *this);
1221 if (tmptok == "Quotes") {
1222 inset = new InsetQuotes;
1223 } else if (tmptok == "External") {
1224 inset = new InsetExternal;
1225 } else if (tmptok == "FormulaMacro") {
1226 inset = new InsetFormulaMacro;
1227 } else if (tmptok == "Formula") {
1228 inset = new InsetFormula;
1229 } else if (tmptok == "Figure") {
1230 inset = new InsetFig(100, 100, *this);
1231 } else if (tmptok == "Info") {
1232 inset = new InsetInfo;
1233 } else if (tmptok == "Include") {
1234 InsetCommandParams p( "Include" );
1235 inset = new InsetInclude(p, *this);
1236 } else if (tmptok == "ERT") {
1237 inset = new InsetERT;
1238 } else if (tmptok == "Tabular") {
1239 inset = new InsetTabular(*this);
1240 } else if (tmptok == "Text") {
1241 inset = new InsetText;
1242 } else if (tmptok == "Foot") {
1243 inset = new InsetFoot;
1244 } else if (tmptok == "Marginal") {
1245 inset = new InsetMarginal;
1246 } else if (tmptok == "Minipage") {
1247 inset = new InsetMinipage;
1248 } else if (tmptok == "Float") {
1250 string tmptok = lex.GetString();
1251 inset = new InsetFloat(tmptok);
1252 } else if (tmptok == "List") {
1253 inset = new InsetList;
1254 } else if (tmptok == "Theorem") {
1255 inset = new InsetList;
1256 } else if (tmptok == "Caption") {
1257 inset = new InsetCaption;
1258 } else if (tmptok == "GRAPHICS") {
1259 inset = new InsetGraphics;
1262 if (inset) inset->Read(this, lex);
1266 par->InsertInset(pos, inset, font);
1272 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1276 string const token(lex.GetString());
1277 if (token == "\\lyxformat") { // the first token _must_ be...
1279 string tmp_format = lex.GetString();
1280 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1281 // if present remove ".," from string.
1282 string::size_type dot = tmp_format.find_first_of(".,");
1283 //lyxerr << " dot found at " << dot << endl;
1284 if (dot != string::npos)
1285 tmp_format.erase(dot, 1);
1286 file_format = strToInt(tmp_format);
1287 if (file_format == LYX_FORMAT) {
1289 } else if (file_format > LYX_FORMAT) {
1291 WriteAlert(_("Warning!"),
1292 _("LyX file format is newer that what"),
1293 _("is supported in this LyX version. Expect some problems."));
1295 } else if (file_format < LYX_FORMAT) {
1297 if (file_format < 200) {
1298 WriteAlert(_("ERROR!"),
1299 _("Old LyX file format found. "
1300 "Use LyX 0.10.x to read this!"));
1304 bool the_end = readLyXformat2(lex, par);
1306 // the_end was added in 213
1307 if (file_format < 213)
1311 WriteAlert(_("Warning!"),
1312 _("Reading of document is not complete"),
1313 _("Maybe the document is truncated"));
1315 } else { // "\\lyxformat" not found
1316 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1319 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1325 // Should probably be moved to somewhere else: BufferView? LyXView?
1326 bool Buffer::save() const
1328 // We don't need autosaves in the immediate future. (Asger)
1329 resetAutosaveTimers();
1333 if (lyxrc.make_backup) {
1334 s = fileName() + '~';
1335 if (!lyxrc.backupdir_path.empty())
1336 s = AddName(lyxrc.backupdir_path,
1337 subst(CleanupPath(s),'/','!'));
1339 // Rename is the wrong way of making a backup,
1340 // this is the correct way.
1341 /* truss cp fil fil2:
1342 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1343 stat("LyXVC.lyx", 0xEFFFF688) = 0
1344 open("LyXVC.lyx", O_RDONLY) = 3
1345 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1346 fstat(4, 0xEFFFF508) = 0
1347 fstat(3, 0xEFFFF508) = 0
1348 read(3, " # T h i s f i l e w".., 8192) = 5579
1349 write(4, " # T h i s f i l e w".., 5579) = 5579
1350 read(3, 0xEFFFD4A0, 8192) = 0
1353 chmod("LyXVC3.lyx", 0100644) = 0
1354 lseek(0, 0, SEEK_CUR) = 46440
1358 // Should proabaly have some more error checking here.
1359 // Should be cleaned up in 0.13, at least a bit.
1360 // Doing it this way, also makes the inodes stay the same.
1361 // This is still not a very good solution, in particular we
1362 // might loose the owner of the backup.
1363 FileInfo finfo(fileName());
1364 if (finfo.exist()) {
1365 mode_t fmode = finfo.getMode();
1366 struct utimbuf times = {
1367 finfo.getAccessTime(),
1368 finfo.getModificationTime() };
1370 ifstream ifs(fileName().c_str());
1371 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1376 ::chmod(s.c_str(), fmode);
1378 if (::utime(s.c_str(), ×)) {
1379 lyxerr << "utime error." << endl;
1382 lyxerr << "LyX was not able to make "
1383 "backupcopy. Beware." << endl;
1388 if (writeFile(fileName(), false)) {
1390 removeAutosaveFile(fileName());
1392 // Saving failed, so backup is not backup
1393 if (lyxrc.make_backup) {
1394 lyx::rename(s, fileName());
1402 // Returns false if unsuccesful
1403 bool Buffer::writeFile(string const & fname, bool flag) const
1405 // if flag is false writeFile will not create any GUI
1406 // warnings, only cerr.
1407 // Needed for autosave in background or panic save (Matthias 120496)
1409 if (read_only && (fname == filename)) {
1410 // Here we should come with a question if we should
1411 // perform the write anyway.
1413 lyxerr << _("Error! Document is read-only: ")
1416 WriteAlert(_("Error! Document is read-only: "),
1421 FileInfo finfo(fname);
1422 if (finfo.exist() && !finfo.writable()) {
1423 // Here we should come with a question if we should
1424 // try to do the save anyway. (i.e. do a chmod first)
1426 lyxerr << _("Error! Cannot write file: ")
1429 WriteFSAlert(_("Error! Cannot write file: "),
1434 ofstream ofs(fname.c_str());
1437 lyxerr << _("Error! Cannot open file: ")
1440 WriteFSAlert(_("Error! Cannot open file: "),
1446 // Use the standard "C" locale for file output.
1447 ofs.imbue(std::locale::classic());
1450 // The top of the file should not be written by params.
1452 // write out a comment in the top of the file
1453 ofs << '#' << LYX_DOCVERSION
1454 << " created this file. For more info see http://www.lyx.org/\n"
1455 << "\\lyxformat " << LYX_FORMAT << "\n";
1457 // now write out the buffer paramters.
1458 params.writeFile(ofs);
1460 char footnoteflag = 0;
1463 // this will write out all the paragraphs
1464 // using recursive descent.
1465 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1467 // Write marker that shows file is complete
1468 ofs << "\n\\the_end" << endl;
1472 // how to check if close went ok?
1473 // Following is an attempt... (BE 20001011)
1475 // good() returns false if any error occured, including some
1476 // formatting error.
1477 // bad() returns true if something bad happened in the buffer,
1478 // which should include file system full errors.
1485 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1487 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1497 string const Buffer::asciiParagraph(LyXParagraph const * par,
1498 unsigned int linelen) const
1500 ostringstream buffer;
1503 Inset const * inset;
1507 int ltype_depth = 0;
1508 unsigned int currlinelen = 0;
1509 bool ref_printed = false;
1513 if (!par->previous()) {
1514 /* begins or ends a deeper area ?*/
1515 if (depth != par->params.depth()) {
1516 if (par->params.depth() > depth) {
1517 while (par->params.depth() > depth) {
1521 while (par->params.depth() < depth) {
1527 /* First write the layout */
1528 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1529 if (tmp == "Itemize") {
1531 ltype_depth = depth + 1;
1532 } else if (tmp == "Enumerate") {
1534 ltype_depth = depth + 1;
1535 } else if (strstr(tmp.c_str(), "ection")) {
1537 ltype_depth = depth + 1;
1538 } else if (strstr(tmp.c_str(), "aragraph")) {
1540 ltype_depth = depth + 1;
1541 } else if (tmp == "Description") {
1543 ltype_depth = depth + 1;
1544 } else if (tmp == "Abstract") {
1547 } else if (tmp == "Bibliography") {
1555 /* maybe some vertical spaces */
1557 /* the labelwidthstring used in lists */
1561 /* some pagebreaks? */
1565 /* what about the alignment */
1567 lyxerr << "Should this ever happen?" << endl;
1570 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1571 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1572 if (!i && !noparbreak) {
1575 for (char j = 0; j < depth; ++j)
1577 currlinelen = depth * 2;
1579 case 0: /* Standard */
1580 case 4: /* (Sub)Paragraph */
1581 case 5: /* Description */
1583 case 6: /* Abstract */
1585 buffer << "Abstract\n\n";
1587 buffer << "Abstract: ";
1589 case 7: /* Bibliography */
1592 buffer << "References\n\n";
1594 buffer << "References: ";
1599 buffer << par->params.labelString() << " ";
1602 if (ltype_depth > depth) {
1603 for (char j = ltype_depth - 1; j > depth; --j)
1605 currlinelen += (ltype_depth-depth)*2;
1608 font2 = par->GetFontSettings(params, i);
1609 if (font1.latex() != font2.latex()) {
1610 if (font2.latex() == LyXFont::OFF)
1617 c = par->GetUChar(params, i);
1621 case LyXParagraph::META_INSET:
1622 if ((inset = par->GetInset(i))) {
1623 if (!inset->Ascii(this, buffer)) {
1625 string s = rsplit(buffer.str().c_str(),
1627 currlinelen += s.length();
1629 // to be sure it breaks paragraph
1630 currlinelen += linelen;
1634 case LyXParagraph::META_NEWLINE:
1637 for (char j = 0; j < depth; ++j)
1640 currlinelen = depth * 2;
1641 if (ltype_depth > depth) {
1642 for (char j = ltype_depth;
1645 currlinelen += (ltype_depth - depth) * 2;
1648 case LyXParagraph::META_HFILL:
1655 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1656 (c == ' ') && ((i + 2) < par->size()))
1659 for (char j = 0; j < depth; ++j)
1661 currlinelen = depth * 2;
1662 if (ltype_depth > depth) {
1663 for (char j = ltype_depth;
1666 currlinelen += (ltype_depth-depth)*2;
1668 } else if (c != '\0')
1671 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1676 return buffer.str().c_str();
1680 void Buffer::writeFileAscii(string const & fname, int linelen)
1682 ofstream ofs(fname.c_str());
1684 WriteFSAlert(_("Error: Cannot write file:"), fname);
1687 writeFileAscii(ofs, linelen);
1691 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1693 LyXParagraph * par = paragraph;
1695 ofs << asciiParagraph(par, linelen);
1703 void Buffer::makeLaTeXFile(string const & fname,
1704 string const & original_path,
1705 bool nice, bool only_body)
1707 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1709 niceFile = nice; // this will be used by Insetincludes.
1711 tex_code_break_column = lyxrc.ascii_linelen;
1713 LyXTextClass const & tclass =
1714 textclasslist.TextClass(params.textclass);
1716 ofstream ofs(fname.c_str());
1718 WriteFSAlert(_("Error: Cannot open file: "), fname);
1722 // validate the buffer.
1723 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1724 LaTeXFeatures features(params, tclass.numLayouts());
1726 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1729 // The starting paragraph of the coming rows is the
1730 // first paragraph of the document. (Asger)
1731 texrow.start(paragraph, 0);
1733 if (!only_body && nice) {
1734 ofs << "%% " LYX_DOCVERSION " created this file. "
1735 "For more info, see http://www.lyx.org/.\n"
1736 "%% Do not edit unless you really know what "
1741 lyxerr.debug() << "lyx header finished" << endl;
1742 // There are a few differences between nice LaTeX and usual files:
1743 // usual is \batchmode and has a
1744 // special input@path to allow the including of figures
1745 // with either \input or \includegraphics (what figinsets do).
1746 // batchmode is not set if there is a tex_code_break_column.
1747 // In this case somebody is interested in the generated LaTeX,
1748 // so this is OK. input@path is set when the actual parameter
1749 // original_path is set. This is done for usual tex-file, but not
1750 // for nice-latex-file. (Matthias 250696)
1753 // code for usual, NOT nice-latex-file
1754 ofs << "\\batchmode\n"; // changed
1755 // from \nonstopmode
1758 if (!original_path.empty()) {
1759 ofs << "\\makeatletter\n"
1760 << "\\def\\input@path{{"
1761 << original_path << "/}}\n"
1762 << "\\makeatother\n";
1768 ofs << "\\documentclass";
1770 string options; // the document class options.
1772 if (tokenPos(tclass.opt_fontsize(),
1773 '|', params.fontsize) >= 0) {
1774 // only write if existing in list (and not default)
1775 options += params.fontsize;
1780 if (!params.use_geometry &&
1781 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1782 switch (params.papersize) {
1783 case BufferParams::PAPER_A4PAPER:
1784 options += "a4paper,";
1786 case BufferParams::PAPER_USLETTER:
1787 options += "letterpaper,";
1789 case BufferParams::PAPER_A5PAPER:
1790 options += "a5paper,";
1792 case BufferParams::PAPER_B5PAPER:
1793 options += "b5paper,";
1795 case BufferParams::PAPER_EXECUTIVEPAPER:
1796 options += "executivepaper,";
1798 case BufferParams::PAPER_LEGALPAPER:
1799 options += "legalpaper,";
1805 if (params.sides != tclass.sides()) {
1806 switch (params.sides) {
1807 case LyXTextClass::OneSide:
1808 options += "oneside,";
1810 case LyXTextClass::TwoSides:
1811 options += "twoside,";
1818 if (params.columns != tclass.columns()) {
1819 if (params.columns == 2)
1820 options += "twocolumn,";
1822 options += "onecolumn,";
1825 if (!params.use_geometry
1826 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1827 options += "landscape,";
1829 // language should be a parameter to \documentclass
1831 string language_options;
1832 if (params.language->babel() == "hebrew"
1833 && default_language->babel() != "hebrew")
1834 // This seems necessary
1835 features.UsedLanguages.insert(default_language);
1837 if (lyxrc.language_use_babel ||
1838 params.language->lang() != lyxrc.default_language ||
1839 !features.UsedLanguages.empty()) {
1841 for (LaTeXFeatures::LanguageList::const_iterator cit =
1842 features.UsedLanguages.begin();
1843 cit != features.UsedLanguages.end(); ++cit)
1844 language_options += (*cit)->babel() + ',';
1845 language_options += params.language->babel();
1846 if (lyxrc.language_global_options)
1847 options += language_options + ',';
1850 // the user-defined options
1851 if (!params.options.empty()) {
1852 options += params.options + ',';
1855 if (!options.empty()){
1856 options = strip(options, ',');
1857 ofs << '[' << options << ']';
1861 << textclasslist.LatexnameOfClass(params.textclass)
1864 // end of \documentclass defs
1866 // font selection must be done before loading fontenc.sty
1867 // The ae package is not needed when using OT1 font encoding.
1868 if (params.fonts != "default" &&
1869 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1870 ofs << "\\usepackage{" << params.fonts << "}\n";
1872 if (params.fonts == "ae") {
1873 ofs << "\\usepackage{aecompl}\n";
1877 // this one is not per buffer
1878 if (lyxrc.fontenc != "default") {
1879 ofs << "\\usepackage[" << lyxrc.fontenc
1884 if (params.inputenc == "auto") {
1885 string const doc_encoding =
1886 params.language->encoding()->LatexName();
1888 // Create a list with all the input encodings used
1890 set<string> encodings;
1891 for (LaTeXFeatures::LanguageList::const_iterator it =
1892 features.UsedLanguages.begin();
1893 it != features.UsedLanguages.end(); ++it)
1894 if ((*it)->encoding()->LatexName() != doc_encoding)
1895 encodings.insert((*it)->encoding()->LatexName());
1897 ofs << "\\usepackage[";
1898 std::copy(encodings.begin(), encodings.end(),
1899 std::ostream_iterator<string>(ofs, ","));
1900 ofs << doc_encoding << "]{inputenc}\n";
1902 } else if (params.inputenc != "default") {
1903 ofs << "\\usepackage[" << params.inputenc
1908 // At the very beginning the text parameters.
1909 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1910 switch (params.paperpackage) {
1911 case BufferParams::PACKAGE_A4:
1912 ofs << "\\usepackage{a4}\n";
1915 case BufferParams::PACKAGE_A4WIDE:
1916 ofs << "\\usepackage{a4wide}\n";
1919 case BufferParams::PACKAGE_WIDEMARGINSA4:
1920 ofs << "\\usepackage[widemargins]{a4}\n";
1925 if (params.use_geometry) {
1926 ofs << "\\usepackage{geometry}\n";
1928 ofs << "\\geometry{verbose";
1929 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1930 ofs << ",landscape";
1931 switch (params.papersize2) {
1932 case BufferParams::VM_PAPER_CUSTOM:
1933 if (!params.paperwidth.empty())
1934 ofs << ",paperwidth="
1935 << params.paperwidth;
1936 if (!params.paperheight.empty())
1937 ofs << ",paperheight="
1938 << params.paperheight;
1940 case BufferParams::VM_PAPER_USLETTER:
1941 ofs << ",letterpaper";
1943 case BufferParams::VM_PAPER_USLEGAL:
1944 ofs << ",legalpaper";
1946 case BufferParams::VM_PAPER_USEXECUTIVE:
1947 ofs << ",executivepaper";
1949 case BufferParams::VM_PAPER_A3:
1952 case BufferParams::VM_PAPER_A4:
1955 case BufferParams::VM_PAPER_A5:
1958 case BufferParams::VM_PAPER_B3:
1961 case BufferParams::VM_PAPER_B4:
1964 case BufferParams::VM_PAPER_B5:
1968 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1969 switch (lyxrc.default_papersize) {
1970 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1971 case BufferParams::PAPER_USLETTER:
1972 ofs << ",letterpaper";
1974 case BufferParams::PAPER_LEGALPAPER:
1975 ofs << ",legalpaper";
1977 case BufferParams::PAPER_EXECUTIVEPAPER:
1978 ofs << ",executivepaper";
1980 case BufferParams::PAPER_A3PAPER:
1983 case BufferParams::PAPER_A4PAPER:
1986 case BufferParams::PAPER_A5PAPER:
1989 case BufferParams::PAPER_B5PAPER:
1994 if (!params.topmargin.empty())
1995 ofs << ",tmargin=" << params.topmargin;
1996 if (!params.bottommargin.empty())
1997 ofs << ",bmargin=" << params.bottommargin;
1998 if (!params.leftmargin.empty())
1999 ofs << ",lmargin=" << params.leftmargin;
2000 if (!params.rightmargin.empty())
2001 ofs << ",rmargin=" << params.rightmargin;
2002 if (!params.headheight.empty())
2003 ofs << ",headheight=" << params.headheight;
2004 if (!params.headsep.empty())
2005 ofs << ",headsep=" << params.headsep;
2006 if (!params.footskip.empty())
2007 ofs << ",footskip=" << params.footskip;
2011 if (features.amsstyle
2012 && !tclass.provides(LyXTextClass::amsmath)) {
2013 ofs << "\\usepackage{amsmath}\n";
2017 if (tokenPos(tclass.opt_pagestyle(),
2018 '|', params.pagestyle) >= 0) {
2019 if (params.pagestyle == "fancy") {
2020 ofs << "\\usepackage{fancyhdr}\n";
2023 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2027 // We try to load babel late, in case it interferes
2028 // with other packages.
2030 string tmp = lyxrc.language_package;
2031 if (!lyxrc.language_global_options
2032 && tmp == "\\usepackage{babel}")
2033 tmp = "\\usepackage[" +
2034 language_options + "]{babel}";
2039 if (params.secnumdepth != tclass.secnumdepth()) {
2040 ofs << "\\setcounter{secnumdepth}{"
2041 << params.secnumdepth
2045 if (params.tocdepth != tclass.tocdepth()) {
2046 ofs << "\\setcounter{tocdepth}{"
2052 if (params.paragraph_separation) {
2053 switch (params.defskip.kind()) {
2054 case VSpace::SMALLSKIP:
2055 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2057 case VSpace::MEDSKIP:
2058 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2060 case VSpace::BIGSKIP:
2061 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2063 case VSpace::LENGTH:
2064 ofs << "\\setlength\\parskip{"
2065 << params.defskip.length().asLatexString()
2068 default: // should never happen // Then delete it.
2069 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2074 ofs << "\\setlength\\parindent{0pt}\n";
2078 // Now insert the LyX specific LaTeX commands...
2080 // The optional packages;
2081 string preamble(features.getPackages());
2083 // this might be useful...
2084 preamble += "\n\\makeatletter\n";
2086 // Some macros LyX will need
2087 string tmppreamble(features.getMacros());
2089 if (!tmppreamble.empty()) {
2090 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2091 "LyX specific LaTeX commands.\n"
2092 + tmppreamble + '\n';
2095 // the text class specific preamble
2096 tmppreamble = features.getTClassPreamble();
2097 if (!tmppreamble.empty()) {
2098 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2099 "Textclass specific LaTeX commands.\n"
2100 + tmppreamble + '\n';
2103 /* the user-defined preamble */
2104 if (!params.preamble.empty()) {
2105 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2106 "User specified LaTeX commands.\n"
2107 + params.preamble + '\n';
2110 preamble += "\\makeatother\n";
2112 // Itemize bullet settings need to be last in case the user
2113 // defines their own bullets that use a package included
2114 // in the user-defined preamble -- ARRae
2115 // Actually it has to be done much later than that
2116 // since some packages like frenchb make modifications
2117 // at \begin{document} time -- JMarc
2119 for (int i = 0; i < 4; ++i) {
2120 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2121 if (bullets_def.empty())
2122 bullets_def="\\AtBeginDocument{\n";
2123 bullets_def += " \\renewcommand{\\labelitemi";
2125 // `i' is one less than the item to modify
2132 bullets_def += "ii";
2138 bullets_def += "}{" +
2139 params.user_defined_bullets[i].getText()
2144 if (!bullets_def.empty())
2145 preamble += bullets_def + "}\n\n";
2147 for (int j = countChar(preamble, '\n'); j-- ;) {
2154 ofs << "\\begin{document}\n";
2157 lyxerr.debug() << "preamble finished, now the body." << endl;
2159 if (!lyxrc.language_auto_begin) {
2160 ofs << subst(lyxrc.language_command_begin, "$$lang",
2161 params.language->babel())
2166 latexParagraphs(ofs, paragraph, 0, texrow);
2168 // add this just in case after all the paragraphs
2172 if (!lyxrc.language_auto_end) {
2173 ofs << subst(lyxrc.language_command_end, "$$lang",
2174 params.language->babel())
2180 ofs << "\\end{document}\n";
2183 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2185 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2189 // Just to be sure. (Asger)
2192 // tex_code_break_column's value is used to decide
2193 // if we are in batchmode or not (within mathed_write()
2194 // in math_write.C) so we must set it to a non-zero
2195 // value when we leave otherwise we save incorrect .lyx files.
2196 tex_code_break_column = lyxrc.ascii_linelen;
2200 lyxerr << "File was not closed properly." << endl;
2203 lyxerr.debug() << "Finished making latex file." << endl;
2208 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2210 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2211 LyXParagraph * endpar, TexRow & texrow) const
2213 bool was_title = false;
2214 bool already_title = false;
2215 std::ostringstream ftnote;
2220 while (par != endpar) {
2221 LyXLayout const & layout =
2222 textclasslist.Style(params.textclass,
2225 if (layout.intitle) {
2226 if (already_title) {
2227 lyxerr <<"Error in latexParagraphs: You"
2228 " should not mix title layouts"
2229 " with normal ones." << endl;
2232 } else if (was_title && !already_title) {
2233 ofs << "\\maketitle\n";
2235 already_title = true;
2238 // We are at depth 0 so we can just use
2239 // ordinary \footnote{} generation
2240 // flag this with ftcount
2242 if (layout.isEnvironment()) {
2243 par = par->TeXEnvironment(this, params, ofs, texrow);
2245 par = par->TeXOnePar(this, params, ofs, texrow, false);
2248 // Write out what we've generated...
2251 ofs << "\\addtocounter{footnote}{-"
2255 ofs << ftnote.str();
2256 texrow += ft_texrow;
2258 // The extra .c_str() is needed when we use
2259 // lyxstring instead of the STL string class.
2260 ftnote.str(string().c_str());
2265 // It might be that we only have a title in this document
2266 if (was_title && !already_title) {
2267 ofs << "\\maketitle\n";
2273 bool Buffer::isLatex() const
2275 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2279 bool Buffer::isLinuxDoc() const
2281 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2285 bool Buffer::isLiterate() const
2287 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2291 bool Buffer::isDocBook() const
2293 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2297 bool Buffer::isSGML() const
2299 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2300 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2304 void Buffer::sgmlOpenTag(ostream & os, int depth,
2305 string const & latexname) const
2307 if (!latexname.empty() && latexname != "!-- --")
2308 os << string(depth, ' ') << "<" << latexname << ">\n";
2312 void Buffer::sgmlCloseTag(ostream & os, int depth,
2313 string const & latexname) const
2315 if (!latexname.empty() && latexname != "!-- --")
2316 os << string(depth, ' ') << "</" << latexname << ">\n";
2320 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2322 ofstream ofs(fname.c_str());
2325 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2329 niceFile = nice; // this will be used by included files.
2331 LyXTextClass const & tclass =
2332 textclasslist.TextClass(params.textclass);
2334 LaTeXFeatures features(params, tclass.numLayouts());
2339 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2342 string sgml_includedfiles=features.getIncludedFiles(fname);
2344 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2345 ofs << "<!doctype linuxdoc system>\n\n";
2347 ofs << "<!doctype linuxdoc system [ "
2348 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2351 if (params.options.empty())
2352 sgmlOpenTag(ofs, 0, top_element);
2354 string top = top_element;
2356 top += params.options;
2357 sgmlOpenTag(ofs, 0, top);
2361 ofs << "<!-- " << LYX_DOCVERSION
2362 << " created this file. For more info see http://www.lyx.org/"
2365 int depth = 0; // paragraph depth
2366 LyXParagraph * par = paragraph;
2368 vector<string> environment_stack(5);
2371 LyXLayout const & style =
2372 textclasslist.Style(params.textclass,
2375 // treat <toc> as a special case for compatibility with old code
2376 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2377 Inset * inset = par->GetInset(0);
2378 Inset::Code lyx_code = inset->LyxCode();
2379 if (lyx_code == Inset::TOC_CODE){
2380 string const temp = "toc";
2381 sgmlOpenTag(ofs, depth, temp);
2388 // environment tag closing
2389 for (; depth > par->params.depth(); --depth) {
2390 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2391 environment_stack[depth].erase();
2394 // write opening SGML tags
2395 switch (style.latextype) {
2396 case LATEX_PARAGRAPH:
2397 if (depth == par->params.depth()
2398 && !environment_stack[depth].empty()) {
2399 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2400 environment_stack[depth].erase();
2406 sgmlOpenTag(ofs, depth, style.latexname());
2411 LinuxDocError(par, 0,
2412 _("Error : Wrong depth for"
2413 " LatexType Command.\n"));
2415 if (!environment_stack[depth].empty()){
2416 sgmlCloseTag(ofs, depth,
2417 environment_stack[depth]);
2421 environment_stack[depth].erase();
2422 sgmlOpenTag(ofs, depth, style.latexname());
2425 case LATEX_ENVIRONMENT:
2426 case LATEX_ITEM_ENVIRONMENT:
2427 if (depth == par->params.depth()
2428 && environment_stack[depth] != style.latexname()) {
2429 sgmlCloseTag(ofs, depth,
2430 environment_stack[depth]);
2431 environment_stack[depth].erase();
2433 if (depth < par->params.depth()) {
2434 depth = par->params.depth();
2435 environment_stack[depth].erase();
2437 if (environment_stack[depth] != style.latexname()) {
2439 sgmlOpenTag(ofs, depth, "p");
2441 sgmlOpenTag(ofs, depth, style.latexname());
2443 if (environment_stack.size() == depth + 1)
2444 environment_stack.push_back("!-- --");
2445 environment_stack[depth] = style.latexname();
2448 if (style.latexparam() == "CDATA")
2451 if (style.latextype == LATEX_ENVIRONMENT) break;
2453 if (style.labeltype == LABEL_MANUAL)
2458 sgmlOpenTag(ofs, depth + 1, item_name);
2461 sgmlOpenTag(ofs, depth, style.latexname());
2465 SimpleLinuxDocOnePar(ofs, par, depth);
2470 // write closing SGML tags
2471 switch (style.latextype) {
2474 case LATEX_ENVIRONMENT:
2475 case LATEX_ITEM_ENVIRONMENT:
2476 if (style.latexparam() == "CDATA")
2480 sgmlCloseTag(ofs, depth, style.latexname());
2486 for (int i=depth; i >= 0; --i)
2487 sgmlCloseTag(ofs, depth, environment_stack[i]);
2491 sgmlCloseTag(ofs, 0, top_element);
2495 // How to check for successful close
2499 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2500 int depth, int desc_on,
2501 LyXParagraph * & par)
2503 LyXParagraph * tpar = par;
2505 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2507 tpar = tpar->next();
2510 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2511 "Caption").second) {
2512 sgmlOpenTag(os, depth + 1, inner_tag);
2514 SimpleDocBookOnePar(os, extra_par, tpar,
2515 desc_on, depth + 2);
2516 sgmlCloseTag(os, depth+1, inner_tag);
2517 if (!extra_par.empty())
2523 // checks, if newcol chars should be put into this line
2524 // writes newline, if necessary.
2527 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2528 string::size_type newcol)
2531 if (colcount > lyxrc.ascii_linelen) {
2533 colcount = newcol; // assume write after this call
2548 string tag_name(PAR_TAG const & pt) {
2550 case NONE: return "!-- --";
2551 case TT: return "tt";
2552 case SF: return "sf";
2553 case BF: return "bf";
2554 case IT: return "it";
2555 case SL: return "sl";
2556 case EM: return "em";
2563 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2565 p1 = static_cast<PAR_TAG>(p1 | p2);
2570 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2572 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2580 // Handle internal paragraph parsing -- layout already processed.
2581 void Buffer::SimpleLinuxDocOnePar(ostream & os,
2582 LyXParagraph * par, int /*depth*/)
2584 LyXLayout const & style = textclasslist.Style(params.textclass,
2586 string::size_type char_line_count = 5; // Heuristic choice ;-)
2588 // gets paragraph main font
2591 if (style.labeltype == LABEL_MANUAL) {
2592 font_old = style.labelfont;
2595 font_old = style.font;
2599 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2600 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2601 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2604 stack < PAR_TAG > tag_state;
2605 // parsing main loop
2606 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
2608 PAR_TAG tag_close = NONE;
2609 list < PAR_TAG > tag_open;
2611 LyXFont const font = par->getFont(params, i);
2613 if (font_old.family() != font.family()) {
2614 switch (family_type) {
2615 case LyXFont::SANS_FAMILY:
2618 case LyXFont::TYPEWRITER_FAMILY:
2625 family_type = font.family();
2627 switch (family_type) {
2628 case LyXFont::SANS_FAMILY:
2629 tag_open.push_back(SF);
2631 case LyXFont::TYPEWRITER_FAMILY:
2632 tag_open.push_back(TT);
2639 if (font_old.series() != font.series()) {
2640 switch (series_type) {
2641 case LyXFont::BOLD_SERIES:
2648 series_type = font.series();
2650 switch (series_type) {
2651 case LyXFont::BOLD_SERIES:
2652 tag_open.push_back(BF);
2660 if (font_old.shape() != font.shape()) {
2661 switch (shape_type) {
2662 case LyXFont::ITALIC_SHAPE:
2665 case LyXFont::SLANTED_SHAPE:
2672 shape_type = font.shape();
2674 switch (shape_type) {
2675 case LyXFont::ITALIC_SHAPE:
2676 tag_open.push_back(IT);
2678 case LyXFont::SLANTED_SHAPE:
2679 tag_open.push_back(SL);
2686 if (font_old.emph() != font.emph()) {
2687 if (font.emph() == LyXFont::ON) {
2688 tag_open.push_back(EM);
2697 list < PAR_TAG > temp;
2698 while(!tag_state.empty() && tag_close ) {
2699 PAR_TAG k = tag_state.top();
2701 os << "</" << tag_name(k) << ">";
2708 for(list< PAR_TAG >::const_iterator j = temp.begin();
2709 j != temp.end(); ++j) {
2711 os << "<" << tag_name(*j) << ">";
2714 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2715 j != tag_open.end(); ++j) {
2717 os << "<" << tag_name(*j) << ">";
2720 char c = par->GetChar(i);
2722 if (c == LyXParagraph::META_INSET) {
2723 Inset * inset = par->GetInset(i);
2724 inset->Linuxdoc(this, os);
2729 if (font.latex() == LyXFont::ON || style.latexparam() == "CDATA") {
2730 // "TeX"-Mode on == > SGML-Mode on.
2736 if (par->linuxDocConvertChar(c, sgml_string)
2737 && !style.free_spacing) {
2738 // in freespacing mode, spaces are
2739 // non-breaking characters
2740 if (desc_on) {// if char is ' ' then...
2743 linux_doc_line_break(os, char_line_count, 6);
2747 linux_doc_line_break(os, char_line_count, 1);
2752 char_line_count += sgml_string.length();
2758 while (!tag_state.empty()) {
2759 os << "</" << tag_name(tag_state.top()) << ">";
2763 // resets description flag correctly
2765 // <tag> not closed...
2766 linux_doc_line_break(os, char_line_count, 6);
2772 // Print an error message.
2773 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2774 string const & message)
2776 // insert an error marker in text
2777 InsetError * new_inset = new InsetError(message);
2778 par->InsertInset(pos, new_inset);
2782 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2784 ofstream ofs(fname.c_str());
2786 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2790 LyXParagraph * par = paragraph;
2792 niceFile = nice; // this will be used by Insetincludes.
2794 LyXTextClass const & tclass =
2795 textclasslist.TextClass(params.textclass);
2797 LaTeXFeatures features(params, tclass.numLayouts());
2802 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2805 string sgml_includedfiles = features.getIncludedFiles(fname);
2807 ofs << "<!doctype " << top_element
2808 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2810 if (params.preamble.empty() && sgml_includedfiles.empty())
2813 ofs << "\n [ " << params.preamble
2814 << sgml_includedfiles << " \n]>\n\n";
2817 string top = top_element;
2819 top += params.language->code();
2822 if (!params.options.empty()) {
2824 top += params.options;
2826 sgmlOpenTag(ofs, 0, top);
2828 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2829 << "\n See http://www.lyx.org/ for more information -->\n";
2831 vector<string> environment_stack(10);
2832 vector<string> environment_inner(10);
2833 vector<string> command_stack(10);
2835 bool command_flag = false;
2836 int command_depth = 0;
2837 int command_base = 0;
2839 int depth = 0; // paragraph depth
2842 string command_name;
2848 int desc_on = 0; // description mode
2850 LyXLayout const & style =
2851 textclasslist.Style(params.textclass,
2854 // environment tag closing
2855 for (; depth > par->params.depth(); --depth) {
2856 if (environment_inner[depth] != "!-- --") {
2857 item_name = "listitem";
2858 sgmlCloseTag(ofs, command_depth + depth,
2860 if (environment_inner[depth] == "varlistentry")
2861 sgmlCloseTag(ofs, depth+command_depth,
2862 environment_inner[depth]);
2864 sgmlCloseTag(ofs, depth + command_depth,
2865 environment_stack[depth]);
2866 environment_stack[depth].erase();
2867 environment_inner[depth].erase();
2870 if (depth == par->params.depth()
2871 && environment_stack[depth] != style.latexname()
2872 && !environment_stack[depth].empty()) {
2873 if (environment_inner[depth] != "!-- --") {
2874 item_name= "listitem";
2875 sgmlCloseTag(ofs, command_depth+depth,
2877 if (environment_inner[depth] == "varlistentry")
2879 depth + command_depth,
2880 environment_inner[depth]);
2883 sgmlCloseTag(ofs, depth + command_depth,
2884 environment_stack[depth]);
2886 environment_stack[depth].erase();
2887 environment_inner[depth].erase();
2890 // Write opening SGML tags.
2891 switch (style.latextype) {
2892 case LATEX_PARAGRAPH:
2893 sgmlOpenTag(ofs, depth + command_depth,
2899 LinuxDocError(par, 0,
2900 _("Error : Wrong depth for "
2901 "LatexType Command.\n"));
2903 command_name = style.latexname();
2905 sgmlparam = style.latexparam();
2906 c_params = split(sgmlparam, c_depth,'|');
2908 cmd_depth = lyx::atoi(c_depth);
2911 if (cmd_depth < command_base) {
2912 for (int j = command_depth; j >= command_base; --j)
2913 sgmlCloseTag(ofs, j, command_stack[j]);
2914 command_depth = command_base = cmd_depth;
2915 } else if (cmd_depth <= command_depth) {
2916 for (int j = command_depth; j >= cmd_depth; --j)
2917 sgmlCloseTag(ofs, j, command_stack[j]);
2918 command_depth = cmd_depth;
2920 command_depth = cmd_depth;
2922 command_depth = command_base = cmd_depth;
2923 command_flag = true;
2925 if (command_stack.size() == command_depth + 1)
2926 command_stack.push_back("");
2927 command_stack[command_depth] = command_name;
2929 // treat label as a special case for
2930 // more WYSIWYM handling.
2931 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2932 Inset * inset = par->GetInset(0);
2933 Inset::Code lyx_code = inset->LyxCode();
2934 if (lyx_code == Inset::LABEL_CODE){
2935 command_name += " id=\"";
2936 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2937 command_name += "\"";
2942 sgmlOpenTag(ofs, depth + command_depth, command_name);
2943 if (c_params.empty())
2944 item_name = "title";
2946 item_name = c_params;
2947 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2950 case LATEX_ENVIRONMENT:
2951 case LATEX_ITEM_ENVIRONMENT:
2952 if (depth < par->params.depth()) {
2953 depth = par->params.depth();
2954 environment_stack[depth].erase();
2957 if (environment_stack[depth] != style.latexname()) {
2958 if(environment_stack.size() == depth + 1) {
2959 environment_stack.push_back("!-- --");
2960 environment_inner.push_back("!-- --");
2962 environment_stack[depth] = style.latexname();
2963 environment_inner[depth] = "!-- --";
2964 sgmlOpenTag(ofs, depth + command_depth,
2965 environment_stack[depth]);
2967 if (environment_inner[depth] != "!-- --") {
2968 item_name= "listitem";
2970 command_depth + depth,
2972 if (environment_inner[depth] == "varlistentry")
2974 depth + command_depth,
2975 environment_inner[depth]);
2979 if (style.latextype == LATEX_ENVIRONMENT) {
2980 if (!style.latexparam().empty()) {
2981 if(style.latexparam() == "CDATA")
2984 sgmlOpenTag(ofs, depth + command_depth,
2985 style.latexparam());
2990 desc_on = (style.labeltype == LABEL_MANUAL);
2993 environment_inner[depth]= "varlistentry";
2995 environment_inner[depth]= "listitem";
2997 sgmlOpenTag(ofs, depth + 1 + command_depth,
2998 environment_inner[depth]);
3002 sgmlOpenTag(ofs, depth + 1 + command_depth,
3006 sgmlOpenTag(ofs, depth + 1 + command_depth,
3011 sgmlOpenTag(ofs, depth + command_depth,
3017 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3018 depth + 1 + command_depth);
3022 // write closing SGML tags
3023 switch (style.latextype) {
3025 if (c_params.empty())
3029 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3031 case LATEX_ENVIRONMENT:
3032 if (!style.latexparam().empty()) {
3033 if(style.latexparam() == "CDATA")
3036 sgmlCloseTag(ofs, depth + command_depth,
3037 style.latexparam());
3040 case LATEX_ITEM_ENVIRONMENT:
3041 if (desc_on == 1) break;
3043 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3045 case LATEX_PARAGRAPH:
3046 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3049 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3055 for (; depth >= 0; --depth) {
3056 if (!environment_stack[depth].empty()) {
3057 if (environment_inner[depth] != "!-- --") {
3058 item_name = "listitem";
3059 sgmlCloseTag(ofs, command_depth + depth,
3061 if (environment_inner[depth] == "varlistentry")
3062 sgmlCloseTag(ofs, depth + command_depth,
3063 environment_inner[depth]);
3066 sgmlCloseTag(ofs, depth + command_depth,
3067 environment_stack[depth]);
3071 for (int j = command_depth; j >= command_base; --j)
3072 if (!command_stack[j].empty())
3073 sgmlCloseTag(ofs, j, command_stack[j]);
3076 sgmlCloseTag(ofs, 0, top_element);
3079 // How to check for successful close
3083 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3084 LyXParagraph * par, int & desc_on,
3087 bool emph_flag = false;
3089 LyXLayout const & style = textclasslist.Style(params.textclass,
3092 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3094 int char_line_count = depth;
3095 if (!style.free_spacing)
3096 os << string(depth,' ');
3098 // parsing main loop
3099 for (LyXParagraph::size_type i = 0;
3100 i < par->size(); ++i) {
3101 LyXFont font = par->getFont(params, i);
3103 // handle <emphasis> tag
3104 if (font_old.emph() != font.emph()) {
3105 if (font.emph() == LyXFont::ON) {
3109 os << "</emphasis>";
3114 char c = par->GetChar(i);
3116 if (c == LyXParagraph::META_INSET) {
3117 Inset * inset = par->GetInset(i);
3118 std::ostringstream ost;
3119 inset->DocBook(this, ost);
3120 string tmp_out = ost.str().c_str();
3123 // This code needs some explanation:
3124 // Two insets are treated specially
3125 // label if it is the first element in a command paragraph
3127 // graphics inside tables or figure floats can't go on
3128 // title (the equivalente in latex for this case is caption
3129 // and title should come first
3132 if (desc_on!= 3 || i!= 0) {
3133 if (!tmp_out.empty() && tmp_out[0] == '@') {
3135 extra += frontStrip(tmp_out, '@');
3137 os << frontStrip(tmp_out, '@');
3142 } else if (font.latex() == LyXFont::ON) {
3143 // "TeX"-Mode on ==> SGML-Mode on.
3149 if (par->linuxDocConvertChar(c, sgml_string)
3150 && !style.free_spacing) { // in freespacing
3152 // non-breaking characters
3156 os << "\n</term><listitem><para>";
3169 os << "</emphasis>";
3172 // resets description flag correctly
3174 // <term> not closed...
3181 // This should be enabled when the Chktex class is implemented. (Asger)
3182 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3183 // Other flags: -wall -v0 -x
3184 int Buffer::runChktex()
3186 if (!users->text) return 0;
3188 ProhibitInput(users);
3190 // get LaTeX-Filename
3191 string const name = getLatexName();
3192 string path = OnlyPath(filename);
3194 string const org_path = path;
3195 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3199 Path p(path); // path to LaTeX file
3200 users->owner()->message(_("Running chktex..."));
3202 // Remove all error insets
3203 bool const removedErrorInsets = users->removeAutoInsets();
3205 // Generate the LaTeX file if neccessary
3206 makeLaTeXFile(name, org_path, false);
3209 Chktex chktex(lyxrc.chktex_command, name, filepath);
3210 int res = chktex.run(terr); // run chktex
3213 WriteAlert(_("chktex did not work!"),
3214 _("Could not run with file:"), name);
3215 } else if (res > 0) {
3216 // Insert all errors as errors boxes
3217 users->insertErrors(terr);
3220 // if we removed error insets before we ran chktex or if we inserted
3221 // error insets after we ran chktex, this must be run:
3222 if (removedErrorInsets || res){
3224 users->fitCursor(users->text);
3232 void Buffer::validate(LaTeXFeatures & features) const
3234 LyXParagraph * par = paragraph;
3235 LyXTextClass const & tclass =
3236 textclasslist.TextClass(params.textclass);
3238 // AMS Style is at document level
3240 features.amsstyle = (params.use_amsmath ||
3241 tclass.provides(LyXTextClass::amsmath));
3244 // We don't use "lyxerr.debug" because of speed. (Asger)
3245 if (lyxerr.debugging(Debug::LATEX))
3246 lyxerr << "Paragraph: " << par << endl;
3248 // Now just follow the list of paragraphs and run
3249 // validate on each of them.
3250 par->validate(features);
3252 // and then the next paragraph
3256 // the bullet shapes are buffer level not paragraph level
3257 // so they are tested here
3258 for (int i = 0; i < 4; ++i) {
3259 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3260 int const font = params.user_defined_bullets[i].getFont();
3262 int const c = params
3263 .user_defined_bullets[i]
3270 features.latexsym = true;
3272 } else if (font == 1) {
3273 features.amssymb = true;
3274 } else if ((font >= 2 && font <= 5)) {
3275 features.pifont = true;
3280 if (lyxerr.debugging(Debug::LATEX)) {
3281 features.showStruct();
3286 void Buffer::setPaperStuff()
3288 params.papersize = BufferParams::PAPER_DEFAULT;
3289 char const c1 = params.paperpackage;
3290 if (c1 == BufferParams::PACKAGE_NONE) {
3291 char const c2 = params.papersize2;
3292 if (c2 == BufferParams::VM_PAPER_USLETTER)
3293 params.papersize = BufferParams::PAPER_USLETTER;
3294 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3295 params.papersize = BufferParams::PAPER_LEGALPAPER;
3296 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3297 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3298 else if (c2 == BufferParams::VM_PAPER_A3)
3299 params.papersize = BufferParams::PAPER_A3PAPER;
3300 else if (c2 == BufferParams::VM_PAPER_A4)
3301 params.papersize = BufferParams::PAPER_A4PAPER;
3302 else if (c2 == BufferParams::VM_PAPER_A5)
3303 params.papersize = BufferParams::PAPER_A5PAPER;
3304 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3305 (c2 == BufferParams::VM_PAPER_B5))
3306 params.papersize = BufferParams::PAPER_B5PAPER;
3307 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3308 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3309 params.papersize = BufferParams::PAPER_A4PAPER;
3313 // This function should be in Buffer because it's a buffer's property (ale)
3314 string const Buffer::getIncludeonlyList(char delim)
3317 for (inset_iterator it = inset_iterator_begin();
3318 it != inset_iterator_end(); ++it) {
3319 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3320 InsetInclude * insetinc =
3321 static_cast<InsetInclude *>(*it);
3322 if (insetinc->isIncludeOnly()) {
3325 lst += insetinc->getRelFileBaseName();
3329 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3334 vector<string> const Buffer::getLabelList()
3336 /// if this is a child document and the parent is already loaded
3337 /// Use the parent's list instead [ale990407]
3338 if (!params.parentname.empty()
3339 && bufferlist.exists(params.parentname)) {
3340 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3342 return tmp->getLabelList();
3345 vector<string> label_list;
3346 for (inset_iterator it = inset_iterator_begin();
3347 it != inset_iterator_end(); ++it) {
3348 vector<string> const l = (*it)->getLabelList();
3349 label_list.insert(label_list.end(), l.begin(), l.end());
3355 Buffer::Lists const Buffer::getLists() const
3358 LyXParagraph * par = paragraph;
3360 LyXTextClassList::size_type cap;
3361 boost::tie(found, cap) = textclasslist
3362 .NumberOfLayout(params.textclass, "Caption");
3365 char const labeltype =
3366 textclasslist.Style(params.textclass,
3367 par->GetLayout()).labeltype;
3369 if (labeltype >= LABEL_COUNTER_CHAPTER
3370 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3371 // insert this into the table of contents
3372 SingleList & item = l["TOC"];
3375 textclasslist.TextClass(params.textclass).maxcounter());
3376 item.push_back(TocItem(par, depth, par->String(this, true)));
3378 // For each paragrph, traverse its insets and look for
3382 LyXParagraph::inset_iterator it =
3383 par->inset_iterator_begin();
3384 LyXParagraph::inset_iterator end =
3385 par->inset_iterator_end();
3387 for (; it != end; ++it) {
3388 if ((*it)->LyxCode() == Inset::FLOAT_CODE) {
3390 static_cast<InsetFloat*>(*it);
3392 string const type = il->type();
3394 // Now find the caption in the float...
3395 // We now tranverse the paragraphs of
3397 LyXParagraph * tmp = il->inset.par;
3399 if (tmp->layout == cap) {
3400 SingleList & item = l[type];
3402 tostr(item.size()+1) + ". " + tmp->String(this, false);
3403 item.push_back(TocItem(tmp, 0 , str));
3410 lyxerr << "caption not found" << endl;
3419 // This is also a buffer property (ale)
3420 vector<pair<string, string> > const Buffer::getBibkeyList()
3422 /// if this is a child document and the parent is already loaded
3423 /// Use the parent's list instead [ale990412]
3424 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3425 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3427 return tmp->getBibkeyList();
3430 vector<pair<string, string> > keys;
3431 LyXParagraph * par = paragraph;
3434 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3435 par->String(this, false)));
3439 // Might be either using bibtex or a child has bibliography
3441 for (inset_iterator it = inset_iterator_begin();
3442 it != inset_iterator_end(); ++it) {
3443 // Search for Bibtex or Include inset
3444 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3445 vector<pair<string,string> > tmp =
3446 static_cast<InsetBibtex*>(*it)->getKeys(this);
3447 keys.insert(keys.end(), tmp.begin(), tmp.end());
3448 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3449 vector<pair<string,string> > const tmp =
3450 static_cast<InsetInclude*>(*it)->getKeys();
3451 keys.insert(keys.end(), tmp.begin(), tmp.end());
3460 bool Buffer::isDepClean(string const & name) const
3462 DEPCLEAN * item = dep_clean;
3463 while (item && item->master != name)
3465 if (!item) return true;
3470 void Buffer::markDepClean(string const & name)
3473 dep_clean = new DEPCLEAN;
3474 dep_clean->clean = true;
3475 dep_clean->master = name;
3476 dep_clean->next = 0;
3478 DEPCLEAN * item = dep_clean;
3479 while (item && item->master != name)
3484 item = new DEPCLEAN;
3486 item->master = name;
3493 bool Buffer::Dispatch(string const & command)
3495 // Split command string into command and argument
3497 string line = frontStrip(command);
3498 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3500 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3504 bool Buffer::Dispatch(int action, string const & argument)
3506 bool dispatched = true;
3509 Exporter::Export(this, argument, false);
3519 void Buffer::resize()
3521 /// resize the BufferViews!
3527 void Buffer::resizeInsets(BufferView * bv)
3529 /// then remove all LyXText in text-insets
3530 LyXParagraph * par = paragraph;
3531 for (; par; par = par->next()) {
3532 par->resizeInsetsLyXText(bv);
3537 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3540 LyXParagraph * par = paragraph;
3542 par->ChangeLanguage(params, from, to);
3548 bool Buffer::isMultiLingual()
3550 LyXParagraph * par = paragraph;
3552 if (par->isMultiLingual(params))
3560 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3561 LyXParagraph::size_type pos)
3564 it = par->InsetIterator(pos);
3565 if (it == par->inset_iterator_end()) {
3572 void Buffer::inset_iterator::SetParagraph()
3575 it = par->inset_iterator_begin();
3576 if (it != par->inset_iterator_end())
3581 // We maintain an invariant that whenever par = 0 then it = 0