1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2001 The LyX Team.
9 * This file is Copyright 1996-2001
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 "mathed/formula.h"
53 #include "insets/inset.h"
54 #include "insets/inseterror.h"
55 #include "insets/insetlabel.h"
56 #include "insets/insetref.h"
57 #include "insets/inseturl.h"
58 #include "insets/insetinfo.h"
59 #include "insets/insetquotes.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetbib.h"
62 #include "insets/insetcite.h"
63 #include "insets/insetexternal.h"
64 #include "insets/insetindex.h"
65 #include "insets/insetinclude.h"
66 #include "insets/insettoc.h"
67 #include "insets/insetparent.h"
68 #include "insets/insetspecialchar.h"
69 #include "insets/figinset.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetminipage.h"
76 #include "insets/insetfloat.h"
77 #include "insets/insetlist.h"
78 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82 #include "support/filetools.h"
83 #include "support/path.h"
84 #include "support/os.h"
89 #include "LaTeXFeatures.h"
90 #include "support/syscall.h"
91 #include "support/lyxlib.h"
92 #include "support/FileInfo.h"
93 #include "support/lyxmanip.h"
97 #include "lyx_gui_misc.h" // WarnReadonly()
98 #include "frontends/Dialogs.h"
100 #include "exporter.h"
101 #include "Lsstream.h"
102 #include "converter.h"
103 #include "BufferView.h"
104 #include "ParagraphParameters.h"
106 using std::stringstream;
115 using std::make_pair;
123 // all these externs should eventually be removed.
124 extern BufferList bufferlist;
126 extern LyXAction lyxaction;
130 const int LYX_FORMAT = 218;
134 extern int tex_code_break_column;
137 Buffer::Buffer(string const & file, bool ronly)
139 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
141 filepath = OnlyPath(file);
150 if (read_only || (lyxrc.use_tempdir)) {
151 tmppath = CreateBufferTmpDir();
152 } else tmppath.erase();
158 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
159 // here the buffer should take care that it is
160 // saved properly, before it goes into the void.
162 // make sure that views using this buffer
167 if (!tmppath.empty()) {
168 DestroyBufferTmpDir(tmppath);
171 Paragraph * par = paragraph;
174 tmppar = par->next();
182 string const Buffer::getLatexName(bool no_path) const
184 string name = ChangeExtension(MakeLatexName(filename), ".tex");
186 return OnlyFilename(name);
192 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
194 string const filename = getLatexName(false);
196 if (filename.empty())
197 return make_pair(Buffer::latexlog, string());
199 string path = OnlyPath(filename);
201 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
204 string const fname = AddName(path,
205 OnlyFilename(ChangeExtension(filename,
208 AddName(path, OnlyFilename(
209 ChangeExtension(filename,
210 formats.Extension("literate") + ".out")));
212 // If no Latex log or Build log is newer, show Build log
214 FileInfo const f_fi(fname);
215 FileInfo const b_fi(bname);
218 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
219 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
220 return make_pair(Buffer::buildlog, bname);
222 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
223 return make_pair(Buffer::latexlog, fname);
227 void Buffer::setReadonly(bool flag)
229 if (read_only != flag) {
232 users->owner()->getDialogs()->updateBufferDependent(false);
235 WarnReadonly(filename);
240 bool Buffer::saveParamsAsDefaults() // const
242 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
244 Buffer defaults = Buffer(fname);
246 // Use the current buffer's parameters as default
247 defaults.params = params;
249 // add an empty paragraph. Is this enough?
250 defaults.paragraph = new Paragraph;
252 return defaults.writeFile(defaults.filename, false);
256 /// Update window titles of all users
257 // Should work on a list
258 void Buffer::updateTitles() const
260 if (users) users->owner()->updateWindowTitle();
264 /// Reset autosave timer of all users
265 // Should work on a list
266 void Buffer::resetAutosaveTimers() const
268 if (users) users->owner()->resetAutosaveTimer();
272 void Buffer::setFileName(string const & newfile)
274 filename = MakeAbsPath(newfile);
275 filepath = OnlyPath(filename);
276 setReadonly(IsFileWriteable(filename) == 0);
281 // candidate for move to BufferView
282 // (at least some parts in the beginning of the func)
285 // changed to be public and have one parameter
286 // if par = 0 normal behavior
287 // else insert behavior
288 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
289 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
292 Paragraph::depth_type depth = 0;
293 bool the_end_read = false;
295 Paragraph * return_par = 0;
296 LyXFont font(LyXFont::ALL_INHERIT, params.language);
297 if (file_format < 216 && params.language->lang() == "hebrew")
298 font.setLanguage(default_language);
299 // If we are inserting, we cheat and get a token in advance
300 bool has_token = false;
306 // We are inserting into an existing document
307 users->text->breakParagraph(users);
308 return_par = users->text->firstParagraph();
311 // We don't want to adopt the parameters from the
312 // document we insert, so we skip until the text begins:
315 pretoken = lex.GetString();
316 if (pretoken == "\\layout") {
328 pretoken = lex.GetString();
331 if (pretoken.empty()) continue;
334 parseSingleLyXformat2Token(lex, par, return_par,
335 pretoken, pos, depth,
343 paragraph = return_par;
349 // We'll remove this later. (Lgb)
352 string last_inset_read;
358 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
359 Paragraph *& return_par,
360 string const & token, int & pos,
361 Paragraph::depth_type & depth,
365 bool the_end_read = false;
367 static string inset_ert_contents;
369 #ifndef NO_PEXTRA_REALLY
370 // This is super temporary but is needed to get the compability
371 // mode for minipages work correctly together with new tabulars.
372 static int call_depth;
374 bool checkminipage = false;
375 static Paragraph * minipar;
376 static Paragraph * parBeforeMinipage;
379 if (token[0] != '\\') {
380 for (string::const_iterator cit = token.begin();
381 cit != token.end(); ++cit) {
382 par->insertChar(pos, (*cit), font);
385 checkminipage = true;
386 } else if (token == "\\i") {
387 Inset * inset = new InsetLatexAccent;
388 inset->read(this, lex);
389 par->insertInset(pos, inset, font);
391 } else if (token == "\\layout") {
394 if (!inset_ert_contents.empty()) {
395 Inset * inset = new InsetERT(inset_ert_contents);
396 par->insertInset(pos, inset, font);
398 inset_ert_contents.erase();
402 string const layoutname = lex.GetString();
403 pair<bool, LyXTextClass::LayoutList::size_type> pp
404 = textclasslist.NumberOfLayout(params.textclass,
408 // The is the compability reading of layout caption.
409 // It can be removed in LyX version 1.3.0. (Lgb)
410 if (compare_no_case(layoutname, "caption") == 0) {
411 // We expect that the par we are now working on is
412 // really inside a InsetText inside a InsetFloat.
413 // We also know that captions can only be
414 // one paragraph. (Lgb)
416 // We should now read until the next "\layout"
418 // This is probably not good enough, what if the
419 // caption is the last par in the document (Lgb)
420 istream & ist = lex.getStream();
426 if (prefixIs(line, "\\layout")) {
430 if (prefixIs(line, "\\begin_inset"))
432 if (prefixIs(line, "\\end_inset")) {
443 // Now we should have the whole layout in ss
444 // we should now be able to give this to the
446 ss << "\\end_inset\n";
448 // This seems like a bug in stringstream.
449 // We really should be able to use ss
451 istringstream is(ss.str());
453 tmplex.setStream(is);
454 Inset * inset = new InsetCaption;
455 inset->Read(this, tmplex);
456 par->InsertInset(pos, inset, font);
463 par = new Paragraph(par);
467 par->layout = pp.second;
470 // use default layout "Standard" (0)
473 // Test whether the layout is obsolete.
474 LyXLayout const & layout =
475 textclasslist.Style(params.textclass,
477 if (!layout.obsoleted_by().empty())
478 par->layout = textclasslist
479 .NumberOfLayout(params.textclass,
480 layout.obsoleted_by())
482 par->params().depth(depth);
483 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
484 if (file_format < 216
485 && params.language->lang() == "hebrew")
486 font.setLanguage(default_language);
491 } else if (token == "\\begin_float") {
492 // This is the compability reader. It can be removed in
493 // LyX version 1.3.0. (Lgb)
495 string const tmptok = lex.GetString();
496 //lyxerr << "old float: " << tmptok << endl;
499 stringstream old_float;
501 if (tmptok == "footnote") {
502 inset = new InsetFoot;
503 } else if (tmptok == "margin") {
504 inset = new InsetMarginal;
505 } else if (tmptok == "fig") {
506 inset = new InsetFloat("figure");
507 old_float << "placement htbp\n"
509 } else if (tmptok == "tab") {
510 inset = new InsetFloat("table");
511 old_float << "placement htbp\n"
513 } else if (tmptok == "alg") {
514 inset = new InsetFloat("algorithm");
515 old_float << "placement htbp\n"
517 } else if (tmptok == "wide-fig") {
518 inset = new InsetFloat("figure");
519 //InsetFloat * tmp = new InsetFloat("figure");
522 old_float << "placement htbp\n"
524 } else if (tmptok == "wide-tab") {
525 inset = new InsetFloat("table");
526 //InsetFloat * tmp = new InsetFloat("table");
529 old_float << "placement htbp\n"
535 return false; // no end read yet
538 old_float << "collapsed true\n";
540 // Here we need to check for \end_deeper and handle that
541 // before we do the footnote parsing.
542 // This _is_ a hack! (Lgb)
545 string const tmp = lex.GetString();
546 if (tmp == "\\end_deeper") {
547 //lyxerr << "\\end_deeper caught!" << endl;
549 lex.printError("\\end_deeper: "
550 "depth is already null");
555 old_float << tmp << ' ';
560 old_float << lex.getLongString("\\end_float")
561 << "\n\\end_inset\n";
562 //lyxerr << "Float Body:\n" << old_float.str() << endl;
563 // That this does not work seems like a bug
564 // in stringstream. (Lgb)
565 istringstream istr(old_float.str());
567 nylex.setStream(istr);
568 inset->read(this, nylex);
569 par->insertInset(pos, inset, font);
571 } else if (token == "\\begin_deeper") {
573 } else if (token == "\\end_deeper") {
575 lex.printError("\\end_deeper: "
576 "depth is already null");
580 } else if (token == "\\begin_preamble") {
581 params.readPreamble(lex);
582 } else if (token == "\\textclass") {
584 pair<bool, LyXTextClassList::size_type> pp =
585 textclasslist.NumberOfClass(lex.GetString());
587 params.textclass = pp.second;
589 WriteAlert(string(_("Textclass error")),
590 string(_("The document uses an unknown textclass \"")) +
591 lex.GetString() + string("\"."),
592 string(_("LyX will not be able to produce output correctly.")));
593 params.textclass = 0;
595 if (!textclasslist.Load(params.textclass)) {
596 // if the textclass wasn't loaded properly
597 // we need to either substitute another
598 // or stop loading the file.
599 // I can substitute but I don't see how I can
600 // stop loading... ideas?? ARRae980418
601 WriteAlert(_("Textclass Loading Error!"),
602 string(_("Can't load textclass ")) +
603 textclasslist.NameOfClass(params.textclass),
604 _("-- substituting default"));
605 params.textclass = 0;
607 } else if (token == "\\options") {
609 params.options = lex.GetString();
610 } else if (token == "\\language") {
611 params.readLanguage(lex);
612 } else if (token == "\\fontencoding") {
614 } else if (token == "\\inputencoding") {
616 params.inputenc = lex.GetString();
617 } else if (token == "\\graphics") {
618 params.readGraphicsDriver(lex);
619 } else if (token == "\\fontscheme") {
621 params.fonts = lex.GetString();
622 } else if (token == "\\noindent") {
623 par->params().noindent(true);
624 } else if (token == "\\fill_top") {
625 par->params().spaceTop(VSpace(VSpace::VFILL));
626 } else if (token == "\\fill_bottom") {
627 par->params().spaceBottom(VSpace(VSpace::VFILL));
628 } else if (token == "\\line_top") {
629 par->params().lineTop(true);
630 } else if (token == "\\line_bottom") {
631 par->params().lineBottom(true);
632 } else if (token == "\\pagebreak_top") {
633 par->params().pagebreakTop(true);
634 } else if (token == "\\pagebreak_bottom") {
635 par->params().pagebreakBottom(true);
636 } else if (token == "\\start_of_appendix") {
637 par->params().startOfAppendix(true);
638 } else if (token == "\\paragraph_separation") {
639 int tmpret = lex.FindToken(string_paragraph_separation);
640 if (tmpret == -1) ++tmpret;
641 if (tmpret != LYX_LAYOUT_DEFAULT)
642 params.paragraph_separation =
643 static_cast<BufferParams::PARSEP>(tmpret);
644 } else if (token == "\\defskip") {
646 params.defskip = VSpace(lex.GetString());
647 } else if (token == "\\epsfig") { // obsolete
648 // Indeed it is obsolete, but we HAVE to be backwards
649 // compatible until 0.14, because otherwise all figures
650 // in existing documents are irretrivably lost. (Asger)
651 params.readGraphicsDriver(lex);
652 } else if (token == "\\quotes_language") {
653 int tmpret = lex.FindToken(string_quotes_language);
654 if (tmpret == -1) ++tmpret;
655 if (tmpret != LYX_LAYOUT_DEFAULT) {
656 InsetQuotes::quote_language tmpl =
657 InsetQuotes::EnglishQ;
660 tmpl = InsetQuotes::EnglishQ;
663 tmpl = InsetQuotes::SwedishQ;
666 tmpl = InsetQuotes::GermanQ;
669 tmpl = InsetQuotes::PolishQ;
672 tmpl = InsetQuotes::FrenchQ;
675 tmpl = InsetQuotes::DanishQ;
678 params.quotes_language = tmpl;
680 } else if (token == "\\quotes_times") {
682 switch (lex.GetInteger()) {
684 params.quotes_times = InsetQuotes::SingleQ;
687 params.quotes_times = InsetQuotes::DoubleQ;
690 } else if (token == "\\papersize") {
691 int tmpret = lex.FindToken(string_papersize);
695 params.papersize2 = tmpret;
696 } else if (token == "\\paperpackage") {
697 int tmpret = lex.FindToken(string_paperpackages);
700 params.paperpackage = BufferParams::PACKAGE_NONE;
702 params.paperpackage = tmpret;
703 } else if (token == "\\use_geometry") {
705 params.use_geometry = lex.GetInteger();
706 } else if (token == "\\use_amsmath") {
708 params.use_amsmath = lex.GetInteger();
709 } else if (token == "\\paperorientation") {
710 int tmpret = lex.FindToken(string_orientation);
711 if (tmpret == -1) ++tmpret;
712 if (tmpret != LYX_LAYOUT_DEFAULT)
713 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
714 } else if (token == "\\paperwidth") {
716 params.paperwidth = lex.GetString();
717 } else if (token == "\\paperheight") {
719 params.paperheight = lex.GetString();
720 } else if (token == "\\leftmargin") {
722 params.leftmargin = lex.GetString();
723 } else if (token == "\\topmargin") {
725 params.topmargin = lex.GetString();
726 } else if (token == "\\rightmargin") {
728 params.rightmargin = lex.GetString();
729 } else if (token == "\\bottommargin") {
731 params.bottommargin = lex.GetString();
732 } else if (token == "\\headheight") {
734 params.headheight = lex.GetString();
735 } else if (token == "\\headsep") {
737 params.headsep = lex.GetString();
738 } else if (token == "\\footskip") {
740 params.footskip = lex.GetString();
741 } else if (token == "\\paperfontsize") {
743 params.fontsize = strip(lex.GetString());
744 } else if (token == "\\papercolumns") {
746 params.columns = lex.GetInteger();
747 } else if (token == "\\papersides") {
749 switch (lex.GetInteger()) {
751 case 1: params.sides = LyXTextClass::OneSide; break;
752 case 2: params.sides = LyXTextClass::TwoSides; break;
754 } else if (token == "\\paperpagestyle") {
756 params.pagestyle = strip(lex.GetString());
757 } else if (token == "\\bullet") {
759 int const index = lex.GetInteger();
761 int temp_int = lex.GetInteger();
762 params.user_defined_bullets[index].setFont(temp_int);
763 params.temp_bullets[index].setFont(temp_int);
765 temp_int = lex.GetInteger();
766 params.user_defined_bullets[index].setCharacter(temp_int);
767 params.temp_bullets[index].setCharacter(temp_int);
769 temp_int = lex.GetInteger();
770 params.user_defined_bullets[index].setSize(temp_int);
771 params.temp_bullets[index].setSize(temp_int);
773 string const temp_str = lex.GetString();
774 if (temp_str != "\\end_bullet") {
775 // this element isn't really necessary for
776 // parsing but is easier for humans
777 // to understand bullets. Put it back and
778 // set a debug message?
779 lex.printError("\\end_bullet expected, got" + temp_str);
780 //how can I put it back?
782 } else if (token == "\\bulletLaTeX") {
784 int const index = lex.GetInteger();
786 string temp_str = lex.GetString();
788 while (temp_str != "\\end_bullet") {
789 // this loop structure is needed when user
790 // enters an empty string since the first
791 // thing returned will be the \\end_bullet
793 // if the LaTeX entry has spaces. Each element
794 // therefore needs to be read in turn
797 temp_str = lex.GetString();
799 params.user_defined_bullets[index].setText(sum_str);
800 params.temp_bullets[index].setText(sum_str);
801 } else if (token == "\\secnumdepth") {
803 params.secnumdepth = lex.GetInteger();
804 } else if (token == "\\tocdepth") {
806 params.tocdepth = lex.GetInteger();
807 } else if (token == "\\spacing") {
809 string const tmp = strip(lex.GetString());
810 Spacing::Space tmp_space = Spacing::Default;
812 if (tmp == "single") {
813 tmp_space = Spacing::Single;
814 } else if (tmp == "onehalf") {
815 tmp_space = Spacing::Onehalf;
816 } else if (tmp == "double") {
817 tmp_space = Spacing::Double;
818 } else if (tmp == "other") {
820 tmp_space = Spacing::Other;
821 tmp_val = lex.GetFloat();
823 lex.printError("Unknown spacing token: '$$Token'");
825 // Small hack so that files written with klyx will be
828 par->params().spacing(Spacing(tmp_space, tmp_val));
830 params.spacing.set(tmp_space, tmp_val);
832 } else if (token == "\\paragraph_spacing") {
834 string const tmp = strip(lex.GetString());
835 if (tmp == "single") {
836 par->params().spacing(Spacing(Spacing::Single));
837 } else if (tmp == "onehalf") {
838 par->params().spacing(Spacing(Spacing::Onehalf));
839 } else if (tmp == "double") {
840 par->params().spacing(Spacing(Spacing::Double));
841 } else if (tmp == "other") {
843 par->params().spacing(Spacing(Spacing::Other,
846 lex.printError("Unknown spacing token: '$$Token'");
848 } else if (token == "\\float_placement") {
850 params.float_placement = lex.GetString();
851 } else if (token == "\\family") {
853 font.setLyXFamily(lex.GetString());
854 } else if (token == "\\series") {
856 font.setLyXSeries(lex.GetString());
857 } else if (token == "\\shape") {
859 font.setLyXShape(lex.GetString());
860 } else if (token == "\\size") {
862 font.setLyXSize(lex.GetString());
865 #warning compatability hack needed
867 } else if (token == "\\latex") {
869 string const tok = lex.GetString();
870 // This is dirty, but gone with LyX3. (Asger)
871 if (tok == "no_latex")
872 font.setLatex(LyXFont::OFF);
873 else if (tok == "latex")
874 font.setLatex(LyXFont::ON);
875 else if (tok == "default")
876 font.setLatex(LyXFont::INHERIT);
878 lex.printError("Unknown LaTeX font flag "
881 } else if (token == "\\latex") {
883 string const tok = lex.GetString();
884 if (tok == "no_latex") {
886 } else if (tok == "latex") {
888 } else if (tok == "default") {
891 lex.printError("Unknown LaTeX font flag "
895 } else if (token == "\\lang") {
897 string const tok = lex.GetString();
898 Language const * lang = languages.getLanguage(tok);
900 font.setLanguage(lang);
902 font.setLanguage(params.language);
903 lex.printError("Unknown language `$$Token'");
905 } else if (token == "\\numeric") {
907 font.setNumber(font.setLyXMisc(lex.GetString()));
908 } else if (token == "\\emph") {
910 font.setEmph(font.setLyXMisc(lex.GetString()));
911 } else if (token == "\\bar") {
913 string const tok = lex.GetString();
914 // This is dirty, but gone with LyX3. (Asger)
916 font.setUnderbar(LyXFont::ON);
917 else if (tok == "no")
918 font.setUnderbar(LyXFont::OFF);
919 else if (tok == "default")
920 font.setUnderbar(LyXFont::INHERIT);
922 lex.printError("Unknown bar font flag "
924 } else if (token == "\\noun") {
926 font.setNoun(font.setLyXMisc(lex.GetString()));
927 } else if (token == "\\color") {
929 font.setLyXColor(lex.GetString());
930 } else if (token == "\\align") {
931 int tmpret = lex.FindToken(string_align);
932 if (tmpret == -1) ++tmpret;
933 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
934 int const tmpret2 = int(pow(2.0, tmpret));
935 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
936 par->params().align(LyXAlignment(tmpret2));
938 } else if (token == "\\added_space_top") {
940 par->params().spaceTop(VSpace(lex.GetString()));
941 } else if (token == "\\added_space_bottom") {
943 par->params().spaceBottom(VSpace(lex.GetString()));
944 #ifndef NO_PEXTRA_REALLY
945 } else if (token == "\\pextra_type") {
947 par->params().pextraType(lex.GetInteger());
948 } else if (token == "\\pextra_width") {
950 par->params().pextraWidth(lex.GetString());
951 } else if (token == "\\pextra_widthp") {
953 par->params().pextraWidthp(lex.GetString());
954 } else if (token == "\\pextra_alignment") {
956 par->params().pextraAlignment(lex.GetInteger());
957 } else if (token == "\\pextra_hfill") {
959 par->params().pextraHfill(lex.GetInteger());
960 } else if (token == "\\pextra_start_minipage") {
962 par->params().pextraStartMinipage(lex.GetInteger());
964 } else if (token == "\\labelwidthstring") {
966 par->params().labelWidthString(lex.GetString());
967 // do not delete this token, it is still needed!
968 } else if (token == "\\end_inset") {
969 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
970 << "Last inset read was: " << last_inset_read
972 // Simply ignore this. The insets do not have
974 // But insets should read it, it is a part of
975 // the inset isn't it? Lgb.
976 } else if (token == "\\begin_inset") {
977 readInset(lex, par, pos, font);
978 } else if (token == "\\SpecialChar") {
979 LyXLayout const & layout =
980 textclasslist.Style(params.textclass,
983 // Insets don't make sense in a free-spacing context! ---Kayvan
984 if (layout.free_spacing) {
987 string next_token = lex.GetString();
988 if (next_token == "\\-") {
989 par->insertChar(pos, '-', font);
990 } else if (next_token == "\\protected_separator"
991 || next_token == "~") {
992 par->insertChar(pos, ' ', font);
994 lex.printError("Token `$$Token' "
996 "paragraph layout!");
1001 Inset * inset = new InsetSpecialChar;
1002 inset->read(this, lex);
1003 par->insertInset(pos, inset, font);
1006 } else if (token == "\\newline") {
1007 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1009 } else if (token == "\\LyXTable") {
1010 Inset * inset = new InsetTabular(*this);
1011 inset->read(this, lex);
1012 par->insertInset(pos, inset, font);
1014 // because of OLD_TABULAR_READ where tabulars have been
1016 checkminipage = true;
1017 } else if (token == "\\hfill") {
1018 par->insertChar(pos, Paragraph::META_HFILL, font);
1020 } else if (token == "\\protected_separator") { // obsolete
1021 // This is a backward compability thingie. (Lgb)
1022 // Remove it later some time...introduced with fileformat
1024 LyXLayout const & layout =
1025 textclasslist.Style(params.textclass,
1028 if (layout.free_spacing) {
1029 par->insertChar(pos, ' ', font);
1031 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1032 par->insertInset(pos, inset, font);
1035 } else if (token == "\\bibitem") { // ale970302
1037 InsetCommandParams p("bibitem", "dummy");
1038 par->bibkey = new InsetBibKey(p);
1040 par->bibkey->read(this, lex);
1041 } else if (token == "\\backslash") {
1042 par->insertChar(pos, '\\', font);
1044 } else if (token == "\\the_end") {
1045 the_end_read = true;
1046 minipar = parBeforeMinipage = 0;
1048 // This should be insurance for the future: (Asger)
1049 lex.printError("Unknown token `$$Token'. "
1050 "Inserting as text.");
1051 string::const_iterator cit = token.begin();
1052 string::const_iterator end = token.end();
1053 for (; cit != end; ++cit) {
1054 par->insertChar(pos, (*cit), font);
1058 #ifndef NO_PEXTRA_REALLY
1059 // now check if we have a minipage paragraph as at this
1060 // point we already read all the necessary data!
1061 // this cannot be done in layout because there we did
1062 // not read yet the paragraph PEXTRA-params (Jug)
1064 // BEGIN pextra_minipage compability
1065 // This should be removed in 1.3.x (Lgb)
1067 // This compability code is not perfect. In a couple
1068 // of rand cases it fails. When the minipage par is
1069 // the first par in the document, and when there are
1070 // none or only one regular paragraphs after the
1071 // minipage. Currently I am not investing any effort
1072 // in fixing those cases.
1074 //lyxerr << "Call depth: " << call_depth << endl;
1075 if (checkminipage && (call_depth == 1)) {
1076 checkminipage = false;
1077 if (minipar && (minipar != par) &&
1078 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1080 lyxerr << "minipages in a row" << endl;
1081 if (par->params().pextraStartMinipage()) {
1082 lyxerr << "start new minipage" << endl;
1083 // minipages in a row
1084 par->previous()->next(0);
1087 Paragraph * tmp = minipar;
1089 tmp->params().pextraType(0);
1090 tmp->params().pextraWidth(string());
1091 tmp->params().pextraWidthp(string());
1092 tmp->params().pextraAlignment(0);
1093 tmp->params().pextraHfill(false);
1094 tmp->params().pextraStartMinipage(false);
1097 // create a new paragraph to insert the
1098 // minipages in the following case
1099 if (par->params().pextraStartMinipage() &&
1100 !par->params().pextraHfill())
1102 Paragraph * p = new Paragraph;
1104 p->previous(parBeforeMinipage);
1105 parBeforeMinipage->next(p);
1107 p->params().depth(parBeforeMinipage->params().depth());
1108 parBeforeMinipage = p;
1110 InsetMinipage * mini = new InsetMinipage;
1111 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1112 mini->width(par->params().pextraWidth());
1113 if (!par->params().pextraWidthp().empty()) {
1114 lyxerr << "WP:" << mini->width() << endl;
1115 mini->width(tostr(par->params().pextraWidthp())+"%");
1117 mini->inset.paragraph(par);
1118 // Insert the minipage last in the
1119 // previous paragraph.
1120 if (par->params().pextraHfill()) {
1121 parBeforeMinipage->insertChar
1122 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1124 parBeforeMinipage->insertInset
1125 (parBeforeMinipage->size(), mini);
1129 lyxerr << "new minipage par" << endl;
1130 //nothing to do just continue reading
1133 } else if (minipar && (minipar != par)) {
1134 lyxerr << "last minipage par read" << endl;
1135 // The last paragraph read was not part of a
1136 // minipage but the par linked list is...
1137 // So we need to remove the last par from the
1139 if (par->previous())
1140 par->previous()->next(0);
1141 par->previous(parBeforeMinipage);
1142 parBeforeMinipage->next(par);
1143 Paragraph * tmp = minipar;
1145 tmp->params().pextraType(0);
1146 tmp->params().pextraWidth(string());
1147 tmp->params().pextraWidthp(string());
1148 tmp->params().pextraAlignment(0);
1149 tmp->params().pextraHfill(false);
1150 tmp->params().pextraStartMinipage(false);
1153 depth = parBeforeMinipage->params().depth();
1154 minipar = parBeforeMinipage = 0;
1155 } else if (!minipar &&
1156 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1158 // par is the first paragraph in a minipage
1159 lyxerr << "begin minipage" << endl;
1160 // To minimize problems for
1161 // the users we will insert
1162 // the first minipage in
1163 // a sequence of minipages
1164 // in its own paragraph.
1165 Paragraph * p = new Paragraph;
1167 p->previous(par->previous());
1169 p->params().depth(depth);
1170 par->params().depth(0);
1172 if (par->previous())
1173 par->previous()->next(p);
1175 parBeforeMinipage = p;
1177 if (!return_par || (return_par == par))
1180 InsetMinipage * mini = new InsetMinipage;
1181 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1182 mini->width(minipar->params().pextraWidth());
1183 if (!par->params().pextraWidthp().empty()) {
1184 lyxerr << "WP:" << mini->width() << endl;
1185 mini->width(tostr(par->params().pextraWidthp())+"%");
1187 mini->inset.paragraph(minipar);
1189 // Insert the minipage last in the
1190 // previous paragraph.
1191 if (minipar->params().pextraHfill()) {
1192 parBeforeMinipage->insertChar
1193 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1195 parBeforeMinipage->insertInset
1196 (parBeforeMinipage->size(), mini);
1199 // End of pextra_minipage compability
1202 return the_end_read;
1206 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1207 int & pos, LyXFont & font)
1209 // consistency check
1210 if (lex.GetString() != "\\begin_inset") {
1211 lyxerr << "Buffer::readInset: Consistency check failed."
1218 string const tmptok = lex.GetString();
1219 last_inset_read = tmptok;
1221 // test the different insets
1222 if (tmptok == "LatexCommand") {
1223 InsetCommandParams inscmd;
1226 string const cmdName = inscmd.getCmdName();
1228 if (cmdName == "cite") {
1229 inset = new InsetCitation(inscmd);
1230 } else if (cmdName == "bibitem") {
1231 lex.printError("Wrong place for bibitem");
1232 inset = new InsetBibKey(inscmd);
1233 } else if (cmdName == "BibTeX") {
1234 inset = new InsetBibtex(inscmd);
1235 } else if (cmdName == "index") {
1236 inset = new InsetIndex(inscmd);
1237 } else if (cmdName == "include") {
1238 inset = new InsetInclude(inscmd, *this);
1239 } else if (cmdName == "label") {
1240 inset = new InsetLabel(inscmd);
1241 } else if (cmdName == "url"
1242 || cmdName == "htmlurl") {
1243 inset = new InsetUrl(inscmd);
1244 } else if (cmdName == "ref"
1245 || cmdName == "pageref"
1246 || cmdName == "vref"
1247 || cmdName == "vpageref"
1248 || cmdName == "prettyref") {
1249 if (!inscmd.getOptions().empty()
1250 || !inscmd.getContents().empty()) {
1251 inset = new InsetRef(inscmd, *this);
1253 } else if (cmdName == "tableofcontents") {
1254 inset = new InsetTOC(inscmd);
1255 } else if (cmdName == "listofalgorithms") {
1256 inset = new InsetFloatList("algorithm");
1257 } else if (cmdName == "listoffigures") {
1258 inset = new InsetFloatList("figure");
1259 } else if (cmdName == "listoftables") {
1260 inset = new InsetFloatList("table");
1261 } else if (cmdName == "printindex") {
1262 inset = new InsetPrintIndex(inscmd);
1263 } else if (cmdName == "lyxparent") {
1264 inset = new InsetParent(inscmd, *this);
1267 if (tmptok == "Quotes") {
1268 inset = new InsetQuotes;
1269 } else if (tmptok == "External") {
1270 inset = new InsetExternal;
1271 } else if (tmptok == "FormulaMacro") {
1272 inset = new InsetFormulaMacro;
1273 } else if (tmptok == "Formula") {
1274 inset = new InsetFormula;
1275 } else if (tmptok == "Figure") {
1276 inset = new InsetFig(100, 100, *this);
1277 } else if (tmptok == "Info") {
1278 inset = new InsetInfo;
1279 } else if (tmptok == "Include") {
1280 InsetCommandParams p( "Include" );
1281 inset = new InsetInclude(p, *this);
1282 } else if (tmptok == "ERT") {
1283 inset = new InsetERT;
1284 } else if (tmptok == "Tabular") {
1285 inset = new InsetTabular(*this);
1286 } else if (tmptok == "Text") {
1287 inset = new InsetText;
1288 } else if (tmptok == "Foot") {
1289 inset = new InsetFoot;
1290 } else if (tmptok == "Marginal") {
1291 inset = new InsetMarginal;
1292 } else if (tmptok == "Minipage") {
1293 inset = new InsetMinipage;
1294 } else if (tmptok == "Float") {
1296 string tmptok = lex.GetString();
1297 inset = new InsetFloat(tmptok);
1298 } else if (tmptok == "List") {
1299 inset = new InsetList;
1300 } else if (tmptok == "Theorem") {
1301 inset = new InsetList;
1302 } else if (tmptok == "Caption") {
1303 inset = new InsetCaption;
1304 } else if (tmptok == "GRAPHICS") {
1305 inset = new InsetGraphics;
1306 } else if (tmptok == "FloatList") {
1307 inset = new InsetFloatList;
1310 if (inset) inset->read(this, lex);
1314 par->insertInset(pos, inset, font);
1320 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1324 string const token(lex.GetString());
1325 if (token == "\\lyxformat") { // the first token _must_ be...
1327 string tmp_format = lex.GetString();
1328 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1329 // if present remove ".," from string.
1330 string::size_type dot = tmp_format.find_first_of(".,");
1331 //lyxerr << " dot found at " << dot << endl;
1332 if (dot != string::npos)
1333 tmp_format.erase(dot, 1);
1334 file_format = strToInt(tmp_format);
1335 if (file_format == LYX_FORMAT) {
1337 } else if (file_format > LYX_FORMAT) {
1339 WriteAlert(_("Warning!"),
1340 _("LyX file format is newer that what"),
1341 _("is supported in this LyX version. Expect some problems."));
1343 } else if (file_format < LYX_FORMAT) {
1345 if (file_format < 200) {
1346 WriteAlert(_("ERROR!"),
1347 _("Old LyX file format found. "
1348 "Use LyX 0.10.x to read this!"));
1352 bool the_end = readLyXformat2(lex, par);
1354 // the_end was added in 213
1355 if (file_format < 213)
1359 WriteAlert(_("Warning!"),
1360 _("Reading of document is not complete"),
1361 _("Maybe the document is truncated"));
1363 } else { // "\\lyxformat" not found
1364 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1367 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1372 // Should probably be moved to somewhere else: BufferView? LyXView?
1373 bool Buffer::save() const
1375 // We don't need autosaves in the immediate future. (Asger)
1376 resetAutosaveTimers();
1380 if (lyxrc.make_backup) {
1381 s = fileName() + '~';
1382 if (!lyxrc.backupdir_path.empty())
1383 s = AddName(lyxrc.backupdir_path,
1384 subst(os::slashify_path(s),'/','!'));
1386 // Rename is the wrong way of making a backup,
1387 // this is the correct way.
1388 /* truss cp fil fil2:
1389 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1390 stat("LyXVC.lyx", 0xEFFFF688) = 0
1391 open("LyXVC.lyx", O_RDONLY) = 3
1392 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1393 fstat(4, 0xEFFFF508) = 0
1394 fstat(3, 0xEFFFF508) = 0
1395 read(3, " # T h i s f i l e w".., 8192) = 5579
1396 write(4, " # T h i s f i l e w".., 5579) = 5579
1397 read(3, 0xEFFFD4A0, 8192) = 0
1400 chmod("LyXVC3.lyx", 0100644) = 0
1401 lseek(0, 0, SEEK_CUR) = 46440
1405 // Should probably have some more error checking here.
1406 // Should be cleaned up in 0.13, at least a bit.
1407 // Doing it this way, also makes the inodes stay the same.
1408 // This is still not a very good solution, in particular we
1409 // might loose the owner of the backup.
1410 FileInfo finfo(fileName());
1411 if (finfo.exist()) {
1412 mode_t fmode = finfo.getMode();
1413 struct utimbuf times = {
1414 finfo.getAccessTime(),
1415 finfo.getModificationTime() };
1417 ifstream ifs(fileName().c_str());
1418 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1423 ::chmod(s.c_str(), fmode);
1425 if (::utime(s.c_str(), ×)) {
1426 lyxerr << "utime error." << endl;
1429 lyxerr << "LyX was not able to make "
1430 "backup copy. Beware." << endl;
1435 if (writeFile(fileName(), false)) {
1437 removeAutosaveFile(fileName());
1439 // Saving failed, so backup is not backup
1440 if (lyxrc.make_backup) {
1441 lyx::rename(s, fileName());
1449 // Returns false if unsuccesful
1450 bool Buffer::writeFile(string const & fname, bool flag) const
1452 // if flag is false writeFile will not create any GUI
1453 // warnings, only cerr.
1454 // Needed for autosave in background or panic save (Matthias 120496)
1456 if (read_only && (fname == filename)) {
1457 // Here we should come with a question if we should
1458 // perform the write anyway.
1460 lyxerr << _("Error! Document is read-only: ")
1463 WriteAlert(_("Error! Document is read-only: "),
1468 FileInfo finfo(fname);
1469 if (finfo.exist() && !finfo.writable()) {
1470 // Here we should come with a question if we should
1471 // try to do the save anyway. (i.e. do a chmod first)
1473 lyxerr << _("Error! Cannot write file: ")
1476 WriteFSAlert(_("Error! Cannot write file: "),
1481 ofstream ofs(fname.c_str());
1484 lyxerr << _("Error! Cannot open file: ")
1487 WriteFSAlert(_("Error! Cannot open file: "),
1493 // Use the standard "C" locale for file output.
1494 ofs.imbue(std::locale::classic());
1497 // The top of the file should not be written by params.
1499 // write out a comment in the top of the file
1500 ofs << '#' << LYX_DOCVERSION
1501 << " created this file. For more info see http://www.lyx.org/\n"
1502 << "\\lyxformat " << LYX_FORMAT << "\n";
1504 // now write out the buffer paramters.
1505 params.writeFile(ofs);
1507 Paragraph::depth_type depth = 0;
1509 // this will write out all the paragraphs
1510 // using recursive descent.
1511 paragraph->writeFile(this, ofs, params, depth);
1513 // Write marker that shows file is complete
1514 ofs << "\n\\the_end" << endl;
1518 // how to check if close went ok?
1519 // Following is an attempt... (BE 20001011)
1521 // good() returns false if any error occured, including some
1522 // formatting error.
1523 // bad() returns true if something bad happened in the buffer,
1524 // which should include file system full errors.
1531 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1533 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1543 string const Buffer::asciiParagraph(Paragraph const * par,
1544 unsigned int linelen) const
1546 ostringstream buffer;
1547 Paragraph::depth_type depth = 0;
1549 Paragraph::depth_type ltype_depth = 0;
1550 unsigned int currlinelen = 0;
1551 bool ref_printed = false;
1555 if (!par->previous()) {
1556 // begins or ends a deeper area ?
1557 if (depth != par->params().depth()) {
1558 if (par->params().depth() > depth) {
1559 while (par->params().depth() > depth) {
1563 while (par->params().depth() < depth) {
1569 // First write the layout
1570 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1571 if (tmp == "Itemize") {
1573 ltype_depth = depth + 1;
1574 } else if (tmp == "Enumerate") {
1576 ltype_depth = depth + 1;
1577 } else if (contains(tmp, "ection")) {
1579 ltype_depth = depth + 1;
1580 } else if (contains(tmp, "aragraph")) {
1582 ltype_depth = depth + 1;
1583 } else if (tmp == "Description") {
1585 ltype_depth = depth + 1;
1586 } else if (tmp == "Abstract") {
1589 } else if (tmp == "Bibliography") {
1597 /* maybe some vertical spaces */
1599 /* the labelwidthstring used in lists */
1603 /* some pagebreaks? */
1607 /* what about the alignment */
1609 lyxerr << "Should this ever happen?" << endl;
1613 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1615 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1616 if (!i && !noparbreak) {
1619 for (Paragraph::depth_type j = 0; j < depth; ++j)
1621 currlinelen = depth * 2;
1624 case 4: // (Sub)Paragraph
1625 case 5: // Description
1629 buffer << "Abstract\n\n";
1631 buffer << "Abstract: ";
1633 case 7: // Bibliography
1636 buffer << "References\n\n";
1638 buffer << "References: ";
1643 buffer << par->params().labelString() << " ";
1646 if (ltype_depth > depth) {
1647 for (Paragraph::depth_type j = ltype_depth - 1;
1650 currlinelen += (ltype_depth-depth)*2;
1654 LyXFont const font2 = par->getFontSettings(params, i);
1655 if (font1.latex() != font2.latex()) {
1656 if (font2.latex() == LyXFont::OFF)
1665 char c = par->getUChar(params, i);
1669 case Paragraph::META_INSET:
1671 Inset const * inset = par->getInset(i);
1673 if (!inset->ascii(this, buffer)) {
1676 rsplit(buffer.str().c_str(),
1678 currlinelen += s.length();
1680 // to be sure it breaks paragraph
1681 currlinelen += linelen;
1687 case Paragraph::META_NEWLINE:
1690 for (Paragraph::depth_type j = 0;
1694 currlinelen = depth * 2;
1695 if (ltype_depth > depth) {
1696 for (Paragraph::depth_type j = ltype_depth;
1699 currlinelen += (ltype_depth - depth) * 2;
1703 case Paragraph::META_HFILL:
1712 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1713 (c == ' ') && ((i + 2) < par->size()))
1716 for (Paragraph::depth_type j = 0;
1719 currlinelen = depth * 2;
1720 if (ltype_depth > depth) {
1721 for (Paragraph::depth_type j = ltype_depth;
1724 currlinelen += (ltype_depth-depth)*2;
1726 } else if (c != '\0')
1729 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1734 return buffer.str().c_str();
1738 void Buffer::writeFileAscii(string const & fname, int linelen)
1740 ofstream ofs(fname.c_str());
1742 WriteFSAlert(_("Error: Cannot write file:"), fname);
1745 writeFileAscii(ofs, linelen);
1749 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1751 Paragraph * par = paragraph;
1753 ofs << asciiParagraph(par, linelen);
1761 void Buffer::makeLaTeXFile(string const & fname,
1762 string const & original_path,
1763 bool nice, bool only_body)
1765 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1767 niceFile = nice; // this will be used by Insetincludes.
1769 tex_code_break_column = lyxrc.ascii_linelen;
1771 LyXTextClass const & tclass =
1772 textclasslist.TextClass(params.textclass);
1774 ofstream ofs(fname.c_str());
1776 WriteFSAlert(_("Error: Cannot open file: "), fname);
1780 // validate the buffer.
1781 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1782 LaTeXFeatures features(params, tclass.numLayouts());
1784 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1787 // The starting paragraph of the coming rows is the
1788 // first paragraph of the document. (Asger)
1789 texrow.start(paragraph, 0);
1791 if (!only_body && nice) {
1792 ofs << "%% " LYX_DOCVERSION " created this file. "
1793 "For more info, see http://www.lyx.org/.\n"
1794 "%% Do not edit unless you really know what "
1799 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1800 // There are a few differences between nice LaTeX and usual files:
1801 // usual is \batchmode and has a
1802 // special input@path to allow the including of figures
1803 // with either \input or \includegraphics (what figinsets do).
1804 // batchmode is not set if there is a tex_code_break_column.
1805 // In this case somebody is interested in the generated LaTeX,
1806 // so this is OK. input@path is set when the actual parameter
1807 // original_path is set. This is done for usual tex-file, but not
1808 // for nice-latex-file. (Matthias 250696)
1811 // code for usual, NOT nice-latex-file
1812 ofs << "\\batchmode\n"; // changed
1813 // from \nonstopmode
1816 if (!original_path.empty()) {
1817 ofs << "\\makeatletter\n"
1818 << "\\def\\input@path{{"
1819 << os::external_path(original_path) << "/}}\n"
1820 << "\\makeatother\n";
1826 ofs << "\\documentclass";
1828 ostringstream options; // the document class options.
1830 if (tokenPos(tclass.opt_fontsize(),
1831 '|', params.fontsize) >= 0) {
1832 // only write if existing in list (and not default)
1833 options << params.fontsize << "pt,";
1837 if (!params.use_geometry &&
1838 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1839 switch (params.papersize) {
1840 case BufferParams::PAPER_A4PAPER:
1841 options << "a4paper,";
1843 case BufferParams::PAPER_USLETTER:
1844 options << "letterpaper,";
1846 case BufferParams::PAPER_A5PAPER:
1847 options << "a5paper,";
1849 case BufferParams::PAPER_B5PAPER:
1850 options << "b5paper,";
1852 case BufferParams::PAPER_EXECUTIVEPAPER:
1853 options << "executivepaper,";
1855 case BufferParams::PAPER_LEGALPAPER:
1856 options << "legalpaper,";
1862 if (params.sides != tclass.sides()) {
1863 switch (params.sides) {
1864 case LyXTextClass::OneSide:
1865 options << "oneside,";
1867 case LyXTextClass::TwoSides:
1868 options << "twoside,";
1874 if (params.columns != tclass.columns()) {
1875 if (params.columns == 2)
1876 options << "twocolumn,";
1878 options << "onecolumn,";
1881 if (!params.use_geometry
1882 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1883 options << "landscape,";
1885 // language should be a parameter to \documentclass
1887 ostringstream language_options;
1888 if (params.language->babel() == "hebrew"
1889 && default_language->babel() != "hebrew")
1890 // This seems necessary
1891 features.UsedLanguages.insert(default_language);
1893 if (lyxrc.language_use_babel ||
1894 params.language->lang() != lyxrc.default_language ||
1895 !features.UsedLanguages.empty()) {
1897 for (LaTeXFeatures::LanguageList::const_iterator cit =
1898 features.UsedLanguages.begin();
1899 cit != features.UsedLanguages.end(); ++cit)
1900 language_options << (*cit)->babel() << ',';
1901 language_options << params.language->babel();
1902 if (lyxrc.language_global_options)
1903 options << language_options.str() << ',';
1906 // the user-defined options
1907 if (!params.options.empty()) {
1908 options << params.options << ',';
1911 string strOptions(options.str().c_str());
1912 if (!strOptions.empty()){
1913 strOptions = strip(strOptions, ',');
1914 ofs << '[' << strOptions << ']';
1918 << textclasslist.LatexnameOfClass(params.textclass)
1921 // end of \documentclass defs
1923 // font selection must be done before loading fontenc.sty
1924 // The ae package is not needed when using OT1 font encoding.
1925 if (params.fonts != "default" &&
1926 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1927 ofs << "\\usepackage{" << params.fonts << "}\n";
1929 if (params.fonts == "ae") {
1930 ofs << "\\usepackage{aecompl}\n";
1934 // this one is not per buffer
1935 if (lyxrc.fontenc != "default") {
1936 ofs << "\\usepackage[" << lyxrc.fontenc
1941 if (params.inputenc == "auto") {
1942 string const doc_encoding =
1943 params.language->encoding()->LatexName();
1945 // Create a list with all the input encodings used
1947 set<string> encodings;
1948 for (LaTeXFeatures::LanguageList::const_iterator it =
1949 features.UsedLanguages.begin();
1950 it != features.UsedLanguages.end(); ++it)
1951 if ((*it)->encoding()->LatexName() != doc_encoding)
1952 encodings.insert((*it)->encoding()->LatexName());
1954 ofs << "\\usepackage[";
1955 std::copy(encodings.begin(), encodings.end(),
1956 std::ostream_iterator<string>(ofs, ","));
1957 ofs << doc_encoding << "]{inputenc}\n";
1959 } else if (params.inputenc != "default") {
1960 ofs << "\\usepackage[" << params.inputenc
1965 // At the very beginning the text parameters.
1966 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1967 switch (params.paperpackage) {
1968 case BufferParams::PACKAGE_A4:
1969 ofs << "\\usepackage{a4}\n";
1972 case BufferParams::PACKAGE_A4WIDE:
1973 ofs << "\\usepackage{a4wide}\n";
1976 case BufferParams::PACKAGE_WIDEMARGINSA4:
1977 ofs << "\\usepackage[widemargins]{a4}\n";
1982 if (params.use_geometry) {
1983 ofs << "\\usepackage{geometry}\n";
1985 ofs << "\\geometry{verbose";
1986 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1987 ofs << ",landscape";
1988 switch (params.papersize2) {
1989 case BufferParams::VM_PAPER_CUSTOM:
1990 if (!params.paperwidth.empty())
1991 ofs << ",paperwidth="
1992 << params.paperwidth;
1993 if (!params.paperheight.empty())
1994 ofs << ",paperheight="
1995 << params.paperheight;
1997 case BufferParams::VM_PAPER_USLETTER:
1998 ofs << ",letterpaper";
2000 case BufferParams::VM_PAPER_USLEGAL:
2001 ofs << ",legalpaper";
2003 case BufferParams::VM_PAPER_USEXECUTIVE:
2004 ofs << ",executivepaper";
2006 case BufferParams::VM_PAPER_A3:
2009 case BufferParams::VM_PAPER_A4:
2012 case BufferParams::VM_PAPER_A5:
2015 case BufferParams::VM_PAPER_B3:
2018 case BufferParams::VM_PAPER_B4:
2021 case BufferParams::VM_PAPER_B5:
2025 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2026 switch (lyxrc.default_papersize) {
2027 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2028 case BufferParams::PAPER_USLETTER:
2029 ofs << ",letterpaper";
2031 case BufferParams::PAPER_LEGALPAPER:
2032 ofs << ",legalpaper";
2034 case BufferParams::PAPER_EXECUTIVEPAPER:
2035 ofs << ",executivepaper";
2037 case BufferParams::PAPER_A3PAPER:
2040 case BufferParams::PAPER_A4PAPER:
2043 case BufferParams::PAPER_A5PAPER:
2046 case BufferParams::PAPER_B5PAPER:
2051 if (!params.topmargin.empty())
2052 ofs << ",tmargin=" << params.topmargin;
2053 if (!params.bottommargin.empty())
2054 ofs << ",bmargin=" << params.bottommargin;
2055 if (!params.leftmargin.empty())
2056 ofs << ",lmargin=" << params.leftmargin;
2057 if (!params.rightmargin.empty())
2058 ofs << ",rmargin=" << params.rightmargin;
2059 if (!params.headheight.empty())
2060 ofs << ",headheight=" << params.headheight;
2061 if (!params.headsep.empty())
2062 ofs << ",headsep=" << params.headsep;
2063 if (!params.footskip.empty())
2064 ofs << ",footskip=" << params.footskip;
2068 if (features.amsstyle
2069 && !tclass.provides(LyXTextClass::amsmath)) {
2070 ofs << "\\usepackage{amsmath}\n";
2074 if (tokenPos(tclass.opt_pagestyle(),
2075 '|', params.pagestyle) >= 0) {
2076 if (params.pagestyle == "fancy") {
2077 ofs << "\\usepackage{fancyhdr}\n";
2080 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2084 // We try to load babel late, in case it interferes
2085 // with other packages.
2087 string tmp = lyxrc.language_package;
2088 if (!lyxrc.language_global_options
2089 && tmp == "\\usepackage{babel}")
2090 tmp = string("\\usepackage[") +
2091 language_options.str().c_str() +
2097 if (params.secnumdepth != tclass.secnumdepth()) {
2098 ofs << "\\setcounter{secnumdepth}{"
2099 << params.secnumdepth
2103 if (params.tocdepth != tclass.tocdepth()) {
2104 ofs << "\\setcounter{tocdepth}{"
2110 if (params.paragraph_separation) {
2111 switch (params.defskip.kind()) {
2112 case VSpace::SMALLSKIP:
2113 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2115 case VSpace::MEDSKIP:
2116 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2118 case VSpace::BIGSKIP:
2119 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2121 case VSpace::LENGTH:
2122 ofs << "\\setlength\\parskip{"
2123 << params.defskip.length().asLatexString()
2126 default: // should never happen // Then delete it.
2127 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2132 ofs << "\\setlength\\parindent{0pt}\n";
2136 // Now insert the LyX specific LaTeX commands...
2138 // The optional packages;
2139 string preamble(features.getPackages());
2141 // this might be useful...
2142 preamble += "\n\\makeatletter\n";
2144 // Some macros LyX will need
2145 string tmppreamble(features.getMacros());
2147 if (!tmppreamble.empty()) {
2148 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2149 "LyX specific LaTeX commands.\n"
2150 + tmppreamble + '\n';
2153 // the text class specific preamble
2154 tmppreamble = features.getTClassPreamble();
2155 if (!tmppreamble.empty()) {
2156 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2157 "Textclass specific LaTeX commands.\n"
2158 + tmppreamble + '\n';
2161 /* the user-defined preamble */
2162 if (!params.preamble.empty()) {
2163 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2164 "User specified LaTeX commands.\n"
2165 + params.preamble + '\n';
2168 preamble += "\\makeatother\n";
2170 // Itemize bullet settings need to be last in case the user
2171 // defines their own bullets that use a package included
2172 // in the user-defined preamble -- ARRae
2173 // Actually it has to be done much later than that
2174 // since some packages like frenchb make modifications
2175 // at \begin{document} time -- JMarc
2177 for (int i = 0; i < 4; ++i) {
2178 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2179 if (bullets_def.empty())
2180 bullets_def="\\AtBeginDocument{\n";
2181 bullets_def += " \\renewcommand{\\labelitemi";
2183 // `i' is one less than the item to modify
2190 bullets_def += "ii";
2196 bullets_def += "}{" +
2197 params.user_defined_bullets[i].getText()
2202 if (!bullets_def.empty())
2203 preamble += bullets_def + "}\n\n";
2205 for (int j = countChar(preamble, '\n'); j-- ;) {
2212 ofs << "\\begin{document}\n";
2215 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2217 if (!lyxrc.language_auto_begin) {
2218 ofs << subst(lyxrc.language_command_begin, "$$lang",
2219 params.language->babel())
2224 latexParagraphs(ofs, paragraph, 0, texrow);
2226 // add this just in case after all the paragraphs
2230 if (!lyxrc.language_auto_end) {
2231 ofs << subst(lyxrc.language_command_end, "$$lang",
2232 params.language->babel())
2238 ofs << "\\end{document}\n";
2241 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2243 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2247 // Just to be sure. (Asger)
2250 // tex_code_break_column's value is used to decide
2251 // if we are in batchmode or not (within mathed_write()
2252 // in math_write.C) so we must set it to a non-zero
2253 // value when we leave otherwise we save incorrect .lyx files.
2254 tex_code_break_column = lyxrc.ascii_linelen;
2258 lyxerr << "File was not closed properly." << endl;
2261 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2266 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2268 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2269 Paragraph * endpar, TexRow & texrow) const
2271 bool was_title = false;
2272 bool already_title = false;
2275 while (par != endpar) {
2276 LyXLayout const & layout =
2277 textclasslist.Style(params.textclass,
2280 if (layout.intitle) {
2281 if (already_title) {
2282 lyxerr <<"Error in latexParagraphs: You"
2283 " should not mix title layouts"
2284 " with normal ones." << endl;
2287 } else if (was_title && !already_title) {
2288 ofs << "\\maketitle\n";
2290 already_title = true;
2294 if (layout.isEnvironment()) {
2295 par = par->TeXEnvironment(this, params, ofs, texrow);
2297 par = par->TeXOnePar(this, params, ofs, texrow, false);
2300 // It might be that we only have a title in this document
2301 if (was_title && !already_title) {
2302 ofs << "\\maketitle\n";
2308 bool Buffer::isLatex() const
2310 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2314 bool Buffer::isLinuxDoc() const
2316 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2320 bool Buffer::isLiterate() const
2322 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2326 bool Buffer::isDocBook() const
2328 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2332 bool Buffer::isSGML() const
2334 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2335 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2339 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2340 string const & latexname) const
2342 if (!latexname.empty() && latexname != "!-- --")
2343 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2344 //os << string(depth, ' ') << "<" << latexname << ">\n";
2348 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2349 string const & latexname) const
2351 if (!latexname.empty() && latexname != "!-- --")
2352 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2353 //os << string(depth, ' ') << "</" << latexname << ">\n";
2357 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2359 ofstream ofs(fname.c_str());
2362 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2366 niceFile = nice; // this will be used by included files.
2368 LyXTextClass const & tclass =
2369 textclasslist.TextClass(params.textclass);
2371 LaTeXFeatures features(params, tclass.numLayouts());
2376 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2379 string sgml_includedfiles=features.getIncludedFiles(fname);
2381 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2382 ofs << "<!doctype linuxdoc system>\n\n";
2384 ofs << "<!doctype linuxdoc system [ "
2385 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2388 if (params.options.empty())
2389 sgmlOpenTag(ofs, 0, top_element);
2391 string top = top_element;
2393 top += params.options;
2394 sgmlOpenTag(ofs, 0, top);
2398 ofs << "<!-- " << LYX_DOCVERSION
2399 << " created this file. For more info see http://www.lyx.org/"
2402 Paragraph::depth_type depth = 0; // paragraph depth
2403 Paragraph * par = paragraph;
2405 vector<string> environment_stack(5);
2408 LyXLayout const & style =
2409 textclasslist.Style(params.textclass,
2412 // treat <toc> as a special case for compatibility with old code
2413 if (par->getChar(0) == Paragraph::META_INSET) {
2414 Inset * inset = par->getInset(0);
2415 Inset::Code lyx_code = inset->lyxCode();
2416 if (lyx_code == Inset::TOC_CODE){
2417 string const temp = "toc";
2418 sgmlOpenTag(ofs, depth, temp);
2425 // environment tag closing
2426 for (; depth > par->params().depth(); --depth) {
2427 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2428 environment_stack[depth].erase();
2431 // write opening SGML tags
2432 switch (style.latextype) {
2433 case LATEX_PARAGRAPH:
2434 if (depth == par->params().depth()
2435 && !environment_stack[depth].empty()) {
2436 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2437 environment_stack[depth].erase();
2443 sgmlOpenTag(ofs, depth, style.latexname());
2448 linuxDocError(par, 0,
2449 _("Error : Wrong depth for"
2450 " LatexType Command.\n"));
2452 if (!environment_stack[depth].empty()){
2453 sgmlCloseTag(ofs, depth,
2454 environment_stack[depth]);
2458 environment_stack[depth].erase();
2459 sgmlOpenTag(ofs, depth, style.latexname());
2462 case LATEX_ENVIRONMENT:
2463 case LATEX_ITEM_ENVIRONMENT:
2464 if (depth == par->params().depth()
2465 && environment_stack[depth] != style.latexname()) {
2466 sgmlCloseTag(ofs, depth,
2467 environment_stack[depth]);
2468 environment_stack[depth].erase();
2470 if (depth < par->params().depth()) {
2471 depth = par->params().depth();
2472 environment_stack[depth].erase();
2474 if (environment_stack[depth] != style.latexname()) {
2476 sgmlOpenTag(ofs, depth, "p");
2478 sgmlOpenTag(ofs, depth, style.latexname());
2480 if (environment_stack.size() == depth + 1)
2481 environment_stack.push_back("!-- --");
2482 environment_stack[depth] = style.latexname();
2485 if (style.latexparam() == "CDATA")
2488 if (style.latextype == LATEX_ENVIRONMENT) break;
2490 if (style.labeltype == LABEL_MANUAL)
2495 sgmlOpenTag(ofs, depth + 1, item_name);
2498 sgmlOpenTag(ofs, depth, style.latexname());
2502 simpleLinuxDocOnePar(ofs, par, depth);
2507 // write closing SGML tags
2508 switch (style.latextype) {
2511 case LATEX_ENVIRONMENT:
2512 case LATEX_ITEM_ENVIRONMENT:
2513 if (style.latexparam() == "CDATA")
2517 sgmlCloseTag(ofs, depth, style.latexname());
2523 for (int i=depth; i >= 0; --i)
2524 sgmlCloseTag(ofs, depth, environment_stack[i]);
2528 sgmlCloseTag(ofs, 0, top_element);
2532 // How to check for successful close
2536 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2537 Paragraph::depth_type depth, int desc_on,
2540 Paragraph * tpar = par;
2542 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2544 tpar = tpar->next();
2547 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2548 "Caption").second) {
2549 sgmlOpenTag(os, depth + 1, inner_tag);
2551 simpleDocBookOnePar(os, extra_par, tpar,
2552 desc_on, depth + 2);
2553 sgmlCloseTag(os, depth+1, inner_tag);
2554 if (!extra_par.empty())
2560 // checks, if newcol chars should be put into this line
2561 // writes newline, if necessary.
2564 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2565 string::size_type newcol)
2568 if (colcount > lyxrc.ascii_linelen) {
2570 colcount = newcol; // assume write after this call
2585 string tag_name(PAR_TAG const & pt) {
2587 case NONE: return "!-- --";
2588 case TT: return "tt";
2589 case SF: return "sf";
2590 case BF: return "bf";
2591 case IT: return "it";
2592 case SL: return "sl";
2593 case EM: return "em";
2600 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2602 p1 = static_cast<PAR_TAG>(p1 | p2);
2607 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2609 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2617 // Handle internal paragraph parsing -- layout already processed.
2618 void Buffer::simpleLinuxDocOnePar(ostream & os,
2620 Paragraph::depth_type /*depth*/)
2622 LyXLayout const & style = textclasslist.Style(params.textclass,
2624 string::size_type char_line_count = 5; // Heuristic choice ;-)
2626 // gets paragraph main font
2629 if (style.labeltype == LABEL_MANUAL) {
2630 font_old = style.labelfont;
2633 font_old = style.font;
2637 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2638 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2639 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2642 stack < PAR_TAG > tag_state;
2643 // parsing main loop
2644 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2646 PAR_TAG tag_close = NONE;
2647 list < PAR_TAG > tag_open;
2649 LyXFont const font = par->getFont(params, i);
2651 if (font_old.family() != font.family()) {
2652 switch (family_type) {
2653 case LyXFont::SANS_FAMILY:
2656 case LyXFont::TYPEWRITER_FAMILY:
2663 family_type = font.family();
2665 switch (family_type) {
2666 case LyXFont::SANS_FAMILY:
2667 tag_open.push_back(SF);
2669 case LyXFont::TYPEWRITER_FAMILY:
2670 tag_open.push_back(TT);
2677 if (font_old.series() != font.series()) {
2678 switch (series_type) {
2679 case LyXFont::BOLD_SERIES:
2686 series_type = font.series();
2688 switch (series_type) {
2689 case LyXFont::BOLD_SERIES:
2690 tag_open.push_back(BF);
2698 if (font_old.shape() != font.shape()) {
2699 switch (shape_type) {
2700 case LyXFont::ITALIC_SHAPE:
2703 case LyXFont::SLANTED_SHAPE:
2710 shape_type = font.shape();
2712 switch (shape_type) {
2713 case LyXFont::ITALIC_SHAPE:
2714 tag_open.push_back(IT);
2716 case LyXFont::SLANTED_SHAPE:
2717 tag_open.push_back(SL);
2724 if (font_old.emph() != font.emph()) {
2725 if (font.emph() == LyXFont::ON) {
2726 tag_open.push_back(EM);
2735 list < PAR_TAG > temp;
2736 while(!tag_state.empty() && tag_close ) {
2737 PAR_TAG k = tag_state.top();
2739 os << "</" << tag_name(k) << ">";
2746 for(list< PAR_TAG >::const_iterator j = temp.begin();
2747 j != temp.end(); ++j) {
2749 os << "<" << tag_name(*j) << ">";
2752 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2753 j != tag_open.end(); ++j) {
2755 os << "<" << tag_name(*j) << ">";
2758 char c = par->getChar(i);
2760 if (c == Paragraph::META_INSET) {
2761 Inset * inset = par->getInset(i);
2762 inset->linuxdoc(this, os);
2769 font.latex() == LyXFont::ON ||
2771 style.latexparam() == "CDATA") {
2772 // "TeX"-Mode on == > SGML-Mode on.
2778 if (par->linuxDocConvertChar(c, sgml_string)
2779 && !style.free_spacing) {
2780 // in freespacing mode, spaces are
2781 // non-breaking characters
2782 if (desc_on) {// if char is ' ' then...
2785 linux_doc_line_break(os, char_line_count, 6);
2789 linux_doc_line_break(os, char_line_count, 1);
2794 char_line_count += sgml_string.length();
2800 while (!tag_state.empty()) {
2801 os << "</" << tag_name(tag_state.top()) << ">";
2805 // resets description flag correctly
2807 // <tag> not closed...
2808 linux_doc_line_break(os, char_line_count, 6);
2814 // Print an error message.
2815 void Buffer::linuxDocError(Paragraph * par, int pos,
2816 string const & message)
2818 // insert an error marker in text
2819 InsetError * new_inset = new InsetError(message);
2820 par->insertInset(pos, new_inset);
2824 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2826 ofstream ofs(fname.c_str());
2828 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2832 Paragraph * par = paragraph;
2834 niceFile = nice; // this will be used by Insetincludes.
2836 LyXTextClass const & tclass =
2837 textclasslist.TextClass(params.textclass);
2839 LaTeXFeatures features(params, tclass.numLayouts());
2844 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2847 string sgml_includedfiles = features.getIncludedFiles(fname);
2849 ofs << "<!doctype " << top_element
2850 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2852 if (params.preamble.empty() && sgml_includedfiles.empty())
2855 ofs << "\n [ " << params.preamble
2856 << sgml_includedfiles << " \n]>\n\n";
2859 string top = top_element;
2861 top += params.language->code();
2864 if (!params.options.empty()) {
2866 top += params.options;
2868 sgmlOpenTag(ofs, 0, top);
2870 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2871 << "\n See http://www.lyx.org/ for more information -->\n";
2873 vector<string> environment_stack(10);
2874 vector<string> environment_inner(10);
2875 vector<string> command_stack(10);
2877 bool command_flag = false;
2878 Paragraph::depth_type command_depth = 0;
2879 Paragraph::depth_type command_base = 0;
2880 Paragraph::depth_type cmd_depth = 0;
2881 Paragraph::depth_type depth = 0; // paragraph depth
2884 string command_name;
2890 int desc_on = 0; // description mode
2892 LyXLayout const & style =
2893 textclasslist.Style(params.textclass,
2896 // environment tag closing
2897 for (; depth > par->params().depth(); --depth) {
2898 if (environment_inner[depth] != "!-- --") {
2899 item_name = "listitem";
2900 sgmlCloseTag(ofs, command_depth + depth,
2902 if (environment_inner[depth] == "varlistentry")
2903 sgmlCloseTag(ofs, depth+command_depth,
2904 environment_inner[depth]);
2906 sgmlCloseTag(ofs, depth + command_depth,
2907 environment_stack[depth]);
2908 environment_stack[depth].erase();
2909 environment_inner[depth].erase();
2912 if (depth == par->params().depth()
2913 && environment_stack[depth] != style.latexname()
2914 && !environment_stack[depth].empty()) {
2915 if (environment_inner[depth] != "!-- --") {
2916 item_name= "listitem";
2917 sgmlCloseTag(ofs, command_depth+depth,
2919 if (environment_inner[depth] == "varlistentry")
2921 depth + command_depth,
2922 environment_inner[depth]);
2925 sgmlCloseTag(ofs, depth + command_depth,
2926 environment_stack[depth]);
2928 environment_stack[depth].erase();
2929 environment_inner[depth].erase();
2932 // Write opening SGML tags.
2933 switch (style.latextype) {
2934 case LATEX_PARAGRAPH:
2935 sgmlOpenTag(ofs, depth + command_depth,
2941 linuxDocError(par, 0,
2942 _("Error : Wrong depth for "
2943 "LatexType Command.\n"));
2945 command_name = style.latexname();
2947 sgmlparam = style.latexparam();
2948 c_params = split(sgmlparam, c_depth,'|');
2950 cmd_depth = lyx::atoi(c_depth);
2953 if (cmd_depth < command_base) {
2954 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
2955 sgmlCloseTag(ofs, j, command_stack[j]);
2956 command_depth = command_base = cmd_depth;
2957 } else if (cmd_depth <= command_depth) {
2958 for (int j = command_depth; j >= int(cmd_depth); --j)
2959 sgmlCloseTag(ofs, j, command_stack[j]);
2960 command_depth = cmd_depth;
2962 command_depth = cmd_depth;
2964 command_depth = command_base = cmd_depth;
2965 command_flag = true;
2967 if (command_stack.size() == command_depth + 1)
2968 command_stack.push_back(string());
2969 command_stack[command_depth] = command_name;
2971 // treat label as a special case for
2972 // more WYSIWYM handling.
2973 if (par->getChar(0) == Paragraph::META_INSET) {
2974 Inset * inset = par->getInset(0);
2975 Inset::Code lyx_code = inset->lyxCode();
2976 if (lyx_code == Inset::LABEL_CODE){
2977 command_name += " id=\"";
2978 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2979 command_name += "\"";
2984 sgmlOpenTag(ofs, depth + command_depth, command_name);
2985 if (c_params.empty())
2986 item_name = "title";
2988 item_name = c_params;
2989 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2992 case LATEX_ENVIRONMENT:
2993 case LATEX_ITEM_ENVIRONMENT:
2994 if (depth < par->params().depth()) {
2995 depth = par->params().depth();
2996 environment_stack[depth].erase();
2999 if (environment_stack[depth] != style.latexname()) {
3000 if(environment_stack.size() == depth + 1) {
3001 environment_stack.push_back("!-- --");
3002 environment_inner.push_back("!-- --");
3004 environment_stack[depth] = style.latexname();
3005 environment_inner[depth] = "!-- --";
3006 sgmlOpenTag(ofs, depth + command_depth,
3007 environment_stack[depth]);
3009 if (environment_inner[depth] != "!-- --") {
3010 item_name= "listitem";
3012 command_depth + depth,
3014 if (environment_inner[depth] == "varlistentry")
3016 depth + command_depth,
3017 environment_inner[depth]);
3021 if (style.latextype == LATEX_ENVIRONMENT) {
3022 if (!style.latexparam().empty()) {
3023 if(style.latexparam() == "CDATA")
3026 sgmlOpenTag(ofs, depth + command_depth,
3027 style.latexparam());
3032 desc_on = (style.labeltype == LABEL_MANUAL);
3035 environment_inner[depth]= "varlistentry";
3037 environment_inner[depth]= "listitem";
3039 sgmlOpenTag(ofs, depth + 1 + command_depth,
3040 environment_inner[depth]);
3044 sgmlOpenTag(ofs, depth + 1 + command_depth,
3048 sgmlOpenTag(ofs, depth + 1 + command_depth,
3053 sgmlOpenTag(ofs, depth + command_depth,
3059 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3060 depth + 1 + command_depth);
3064 // write closing SGML tags
3065 switch (style.latextype) {
3067 if (c_params.empty())
3071 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3073 case LATEX_ENVIRONMENT:
3074 if (!style.latexparam().empty()) {
3075 if(style.latexparam() == "CDATA")
3078 sgmlCloseTag(ofs, depth + command_depth,
3079 style.latexparam());
3082 case LATEX_ITEM_ENVIRONMENT:
3083 if (desc_on == 1) break;
3085 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3087 case LATEX_PARAGRAPH:
3088 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3091 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3097 for (int d = depth; d >= 0; --d) {
3098 if (!environment_stack[depth].empty()) {
3099 if (environment_inner[depth] != "!-- --") {
3100 item_name = "listitem";
3101 sgmlCloseTag(ofs, command_depth + depth,
3103 if (environment_inner[depth] == "varlistentry")
3104 sgmlCloseTag(ofs, depth + command_depth,
3105 environment_inner[depth]);
3108 sgmlCloseTag(ofs, depth + command_depth,
3109 environment_stack[depth]);
3113 for (int j = command_depth; j >= 0 ; --j)
3114 if (!command_stack[j].empty())
3115 sgmlCloseTag(ofs, j, command_stack[j]);
3118 sgmlCloseTag(ofs, 0, top_element);
3121 // How to check for successful close
3125 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3126 Paragraph * par, int & desc_on,
3127 Paragraph::depth_type depth) const
3129 bool emph_flag = false;
3131 LyXLayout const & style = textclasslist.Style(params.textclass,
3134 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3136 int char_line_count = depth;
3137 //if (!style.free_spacing)
3138 // os << string(depth,' ');
3140 // parsing main loop
3141 for (Paragraph::size_type i = 0;
3142 i < par->size(); ++i) {
3143 LyXFont font = par->getFont(params, i);
3145 // handle <emphasis> tag
3146 if (font_old.emph() != font.emph()) {
3147 if (font.emph() == LyXFont::ON) {
3151 os << "</emphasis>";
3156 char c = par->getChar(i);
3158 if (c == Paragraph::META_INSET) {
3159 Inset * inset = par->getInset(i);
3160 std::ostringstream ost;
3161 inset->docBook(this, ost);
3162 string tmp_out = ost.str().c_str();
3165 // This code needs some explanation:
3166 // Two insets are treated specially
3167 // label if it is the first element in a command paragraph
3169 // graphics inside tables or figure floats can't go on
3170 // title (the equivalente in latex for this case is caption
3171 // and title should come first
3174 if (desc_on!= 3 || i!= 0) {
3175 if (!tmp_out.empty() && tmp_out[0] == '@') {
3177 extra += frontStrip(tmp_out, '@');
3179 os << frontStrip(tmp_out, '@');
3185 } else if (font.latex() == LyXFont::ON) {
3186 // "TeX"-Mode on ==> SGML-Mode on.
3193 if (par->linuxDocConvertChar(c, sgml_string)
3194 && !style.free_spacing) { // in freespacing
3196 // non-breaking characters
3200 os << "\n</term><listitem><para>";
3213 os << "</emphasis>";
3216 // resets description flag correctly
3218 // <term> not closed...
3221 if(style.free_spacing) os << '\n';
3225 // This should be enabled when the Chktex class is implemented. (Asger)
3226 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3227 // Other flags: -wall -v0 -x
3228 int Buffer::runChktex()
3230 if (!users->text) return 0;
3232 users->owner()->prohibitInput();
3234 // get LaTeX-Filename
3235 string const name = getLatexName();
3236 string path = OnlyPath(filename);
3238 string const org_path = path;
3239 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3243 Path p(path); // path to LaTeX file
3244 users->owner()->message(_("Running chktex..."));
3246 // Remove all error insets
3247 bool const removedErrorInsets = users->removeAutoInsets();
3249 // Generate the LaTeX file if neccessary
3250 makeLaTeXFile(name, org_path, false);
3253 Chktex chktex(lyxrc.chktex_command, name, filepath);
3254 int res = chktex.run(terr); // run chktex
3257 WriteAlert(_("chktex did not work!"),
3258 _("Could not run with file:"), name);
3259 } else if (res > 0) {
3260 // Insert all errors as errors boxes
3261 users->insertErrors(terr);
3264 // if we removed error insets before we ran chktex or if we inserted
3265 // error insets after we ran chktex, this must be run:
3266 if (removedErrorInsets || res){
3268 users->fitCursor(users->text);
3270 users->owner()->allowInput();
3276 void Buffer::validate(LaTeXFeatures & features) const
3278 Paragraph * par = paragraph;
3279 LyXTextClass const & tclass =
3280 textclasslist.TextClass(params.textclass);
3282 // AMS Style is at document level
3284 features.amsstyle = (params.use_amsmath ||
3285 tclass.provides(LyXTextClass::amsmath));
3288 // We don't use "lyxerr.debug" because of speed. (Asger)
3289 if (lyxerr.debugging(Debug::LATEX))
3290 lyxerr << "Paragraph: " << par << endl;
3292 // Now just follow the list of paragraphs and run
3293 // validate on each of them.
3294 par->validate(features);
3296 // and then the next paragraph
3300 // the bullet shapes are buffer level not paragraph level
3301 // so they are tested here
3302 for (int i = 0; i < 4; ++i) {
3303 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3304 int const font = params.user_defined_bullets[i].getFont();
3306 int const c = params
3307 .user_defined_bullets[i]
3314 features.latexsym = true;
3316 } else if (font == 1) {
3317 features.amssymb = true;
3318 } else if ((font >= 2 && font <= 5)) {
3319 features.pifont = true;
3324 if (lyxerr.debugging(Debug::LATEX)) {
3325 features.showStruct();
3330 void Buffer::setPaperStuff()
3332 params.papersize = BufferParams::PAPER_DEFAULT;
3333 char const c1 = params.paperpackage;
3334 if (c1 == BufferParams::PACKAGE_NONE) {
3335 char const c2 = params.papersize2;
3336 if (c2 == BufferParams::VM_PAPER_USLETTER)
3337 params.papersize = BufferParams::PAPER_USLETTER;
3338 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3339 params.papersize = BufferParams::PAPER_LEGALPAPER;
3340 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3341 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3342 else if (c2 == BufferParams::VM_PAPER_A3)
3343 params.papersize = BufferParams::PAPER_A3PAPER;
3344 else if (c2 == BufferParams::VM_PAPER_A4)
3345 params.papersize = BufferParams::PAPER_A4PAPER;
3346 else if (c2 == BufferParams::VM_PAPER_A5)
3347 params.papersize = BufferParams::PAPER_A5PAPER;
3348 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3349 (c2 == BufferParams::VM_PAPER_B5))
3350 params.papersize = BufferParams::PAPER_B5PAPER;
3351 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3352 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3353 params.papersize = BufferParams::PAPER_A4PAPER;
3357 // This function should be in Buffer because it's a buffer's property (ale)
3358 string const Buffer::getIncludeonlyList(char delim)
3361 for (inset_iterator it = inset_iterator_begin();
3362 it != inset_iterator_end(); ++it) {
3363 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3364 InsetInclude * insetinc =
3365 static_cast<InsetInclude *>(*it);
3366 if (insetinc->isIncludeOnly()) {
3369 lst += insetinc->getRelFileBaseName();
3373 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3378 vector<string> const Buffer::getLabelList()
3380 /// if this is a child document and the parent is already loaded
3381 /// Use the parent's list instead [ale990407]
3382 if (!params.parentname.empty()
3383 && bufferlist.exists(params.parentname)) {
3384 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3386 return tmp->getLabelList();
3389 vector<string> label_list;
3390 for (inset_iterator it = inset_iterator_begin();
3391 it != inset_iterator_end(); ++it) {
3392 vector<string> const l = (*it)->getLabelList();
3393 label_list.insert(label_list.end(), l.begin(), l.end());
3399 Buffer::Lists const Buffer::getLists() const
3402 Paragraph * par = paragraph;
3404 LyXTextClassList::size_type cap;
3405 boost::tie(found, cap) = textclasslist
3406 .NumberOfLayout(params.textclass, "Caption");
3409 char const labeltype =
3410 textclasslist.Style(params.textclass,
3411 par->getLayout()).labeltype;
3413 if (labeltype >= LABEL_COUNTER_CHAPTER
3414 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3415 // insert this into the table of contents
3416 SingleList & item = l["TOC"];
3419 textclasslist.TextClass(params.textclass).maxcounter());
3420 item.push_back(TocItem(par, depth, par->asString(this, true)));
3422 // For each paragrph, traverse its insets and look for
3426 Paragraph::inset_iterator it =
3427 par->inset_iterator_begin();
3428 Paragraph::inset_iterator end =
3429 par->inset_iterator_end();
3431 for (; it != end; ++it) {
3432 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3434 static_cast<InsetFloat*>(*it);
3436 string const type = il->type();
3438 // Now find the caption in the float...
3439 // We now tranverse the paragraphs of
3441 Paragraph * tmp = il->inset.paragraph();
3443 if (tmp->layout == cap) {
3444 SingleList & item = l[type];
3446 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3447 item.push_back(TocItem(tmp, 0 , str));
3454 lyxerr << "caption not found" << endl;
3463 // This is also a buffer property (ale)
3464 vector<pair<string, string> > const Buffer::getBibkeyList()
3466 /// if this is a child document and the parent is already loaded
3467 /// Use the parent's list instead [ale990412]
3468 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3469 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3471 return tmp->getBibkeyList();
3474 vector<pair<string, string> > keys;
3475 Paragraph * par = paragraph;
3478 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3479 par->asString(this, false)));
3483 // Might be either using bibtex or a child has bibliography
3485 for (inset_iterator it = inset_iterator_begin();
3486 it != inset_iterator_end(); ++it) {
3487 // Search for Bibtex or Include inset
3488 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3489 vector<pair<string,string> > tmp =
3490 static_cast<InsetBibtex*>(*it)->getKeys(this);
3491 keys.insert(keys.end(), tmp.begin(), tmp.end());
3492 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3493 vector<pair<string,string> > const tmp =
3494 static_cast<InsetInclude*>(*it)->getKeys();
3495 keys.insert(keys.end(), tmp.begin(), tmp.end());
3504 bool Buffer::isDepClean(string const & name) const
3506 DEPCLEAN * item = dep_clean;
3507 while (item && item->master != name)
3509 if (!item) return true;
3514 void Buffer::markDepClean(string const & name)
3517 dep_clean = new DEPCLEAN;
3518 dep_clean->clean = true;
3519 dep_clean->master = name;
3520 dep_clean->next = 0;
3522 DEPCLEAN * item = dep_clean;
3523 while (item && item->master != name)
3528 item = new DEPCLEAN;
3530 item->master = name;
3537 bool Buffer::dispatch(string const & command)
3539 // Split command string into command and argument
3541 string line = frontStrip(command);
3542 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3544 return dispatch(lyxaction.LookupFunc(cmd), arg);
3548 bool Buffer::dispatch(int action, string const & argument)
3550 bool dispatched = true;
3553 Exporter::Export(this, argument, false);
3563 void Buffer::resizeInsets(BufferView * bv)
3565 /// then remove all LyXText in text-insets
3566 Paragraph * par = paragraph;
3567 for (; par; par = par->next()) {
3568 par->resizeInsetsLyXText(bv);
3573 void Buffer::redraw()
3576 users->fitCursor(users->text);
3580 void Buffer::changeLanguage(Language const * from, Language const * to)
3583 Paragraph * par = paragraph;
3585 par->changeLanguage(params, from, to);
3591 bool Buffer::isMultiLingual()
3593 Paragraph * par = paragraph;
3595 if (par->isMultiLingual(params))
3603 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3604 Paragraph::size_type pos)
3607 it = par->InsetIterator(pos);
3608 if (it == par->inset_iterator_end()) {
3615 void Buffer::inset_iterator::setParagraph()
3618 it = par->inset_iterator_begin();
3619 if (it != par->inset_iterator_end())
3624 // We maintain an invariant that whenever par = 0 then it = 0
3628 Inset * Buffer::getInsetFromID(int id_arg) const
3630 for (inset_iterator it = inset_const_iterator_begin();
3631 it != inset_const_iterator_end(); ++it)
3633 if ((*it)->id() == id_arg)
3635 Inset * in = (*it)->getInsetFromID(id_arg);