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/insetnote.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/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
84 #include "support/textutils.h"
85 #include "support/filetools.h"
86 #include "support/path.h"
87 #include "support/os.h"
92 #include "LaTeXFeatures.h"
93 #include "support/syscall.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
100 #include "lyx_gui_misc.h" // WarnReadonly()
101 #include "frontends/Dialogs.h"
102 #include "encoding.h"
103 #include "exporter.h"
104 #include "Lsstream.h"
105 #include "converter.h"
106 #include "BufferView.h"
107 #include "ParagraphParameters.h"
117 using std::make_pair;
125 // all these externs should eventually be removed.
126 extern BufferList bufferlist;
128 extern LyXAction lyxaction;
132 const int LYX_FORMAT = 220;
136 extern int tex_code_break_column;
139 Buffer::Buffer(string const & file, bool ronly)
141 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
143 filepath = OnlyPath(file);
152 if (read_only || (lyxrc.use_tempdir)) {
153 tmppath = CreateBufferTmpDir();
154 } else tmppath.erase();
160 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
161 // here the buffer should take care that it is
162 // saved properly, before it goes into the void.
164 // make sure that views using this buffer
169 if (!tmppath.empty()) {
170 DestroyBufferTmpDir(tmppath);
173 Paragraph * par = paragraph;
176 tmppar = par->next();
184 string const Buffer::getLatexName(bool no_path) const
186 string name = ChangeExtension(MakeLatexName(filename), ".tex");
188 return OnlyFilename(name);
194 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
196 string const filename = getLatexName(false);
198 if (filename.empty())
199 return make_pair(Buffer::latexlog, string());
201 string path = OnlyPath(filename);
203 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
206 string const fname = AddName(path,
207 OnlyFilename(ChangeExtension(filename,
210 AddName(path, OnlyFilename(
211 ChangeExtension(filename,
212 formats.Extension("literate") + ".out")));
214 // If no Latex log or Build log is newer, show Build log
216 FileInfo const f_fi(fname);
217 FileInfo const b_fi(bname);
220 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
221 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
222 return make_pair(Buffer::buildlog, bname);
224 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
225 return make_pair(Buffer::latexlog, fname);
229 void Buffer::setReadonly(bool flag)
231 if (read_only != flag) {
234 users->owner()->getDialogs()->updateBufferDependent(false);
237 WarnReadonly(filename);
242 bool Buffer::saveParamsAsDefaults() // const
244 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
246 Buffer defaults = Buffer(fname);
248 // Use the current buffer's parameters as default
249 defaults.params = params;
251 // add an empty paragraph. Is this enough?
252 defaults.paragraph = new Paragraph;
254 return defaults.writeFile(defaults.filename, false);
258 /// Update window titles of all users
259 // Should work on a list
260 void Buffer::updateTitles() const
262 if (users) users->owner()->updateWindowTitle();
266 /// Reset autosave timer of all users
267 // Should work on a list
268 void Buffer::resetAutosaveTimers() const
270 if (users) users->owner()->resetAutosaveTimer();
274 void Buffer::setFileName(string const & newfile)
276 filename = MakeAbsPath(newfile);
277 filepath = OnlyPath(filename);
278 setReadonly(IsFileWriteable(filename) == 0);
283 // We'll remove this later. (Lgb)
286 string last_inset_read;
290 ErtComp() : active(false), in_tabular(false) {
297 std::stack<ErtComp> ert_stack;
306 // candidate for move to BufferView
307 // (at least some parts in the beginning of the func)
310 // changed to be public and have one parameter
311 // if par = 0 normal behavior
312 // else insert behavior
313 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
314 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
318 ert_comp.contents.erase();
319 ert_comp.active = false;
320 ert_comp.in_tabular = false;
324 Paragraph::depth_type depth = 0;
325 bool the_end_read = false;
327 Paragraph * first_par = 0;
328 LyXFont font(LyXFont::ALL_INHERIT, params.language);
329 if (file_format < 216 && params.language->lang() == "hebrew")
330 font.setLanguage(default_language);
335 // We are inserting into an existing document
336 users->text->breakParagraph(users);
337 first_par = users->text->firstParagraph();
340 // We don't want to adopt the parameters from the
341 // document we insert, so we skip until the text begins:
344 string const pretoken = lex.GetString();
345 if (pretoken == "\\layout") {
346 lex.pushToken(pretoken);
354 string const token = lex.GetString();
356 if (token.empty()) continue;
358 lyxerr[Debug::PARSER] << "Handling token: `"
359 << token << "'" << endl;
362 parseSingleLyXformat2Token(lex, par, first_par,
370 paragraph = first_par;
372 if (unknown_layouts > 0) {
373 string s = _("Couldn't set the layout for ");
374 if (unknown_layouts == 1) {
375 s += _("one paragraph");
377 s += tostr(unknown_layouts);
378 s += _(" paragraphs");
380 WriteAlert(_("Textclass Loading Error!"), s,
381 _("When reading " + fileName()));
388 void Buffer::insertErtContents(Paragraph * par, int & pos,
389 LyXFont const & font, bool set_inactive)
391 if (!ert_comp.contents.empty()) {
392 lyxerr[Debug::INSETS] << "ERT contents:\n"
393 << ert_comp.contents << endl;
394 Inset * inset = new InsetERT(ert_comp.contents, true);
395 par->insertInset(pos++, inset, font);
396 ert_comp.contents.erase();
399 ert_comp.active = false;
405 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
406 Paragraph *& first_par,
407 string const & token, int & pos,
408 Paragraph::depth_type & depth,
412 bool the_end_read = false;
413 #ifndef NO_PEXTRA_REALLY
414 // This is super temporary but is needed to get the compability
415 // mode for minipages work correctly together with new tabulars.
416 static int call_depth;
418 bool checkminipage = false;
419 static Paragraph * minipar;
420 static Paragraph * parBeforeMinipage;
423 if (token[0] != '\\') {
425 if (ert_comp.active) {
426 ert_comp.contents += token;
429 for (string::const_iterator cit = token.begin();
430 cit != token.end(); ++cit) {
431 par->insertChar(pos, (*cit), font);
437 } else if (token == "\\i") {
438 Inset * inset = new InsetLatexAccent;
439 inset->read(this, lex);
440 par->insertInset(pos, inset, font);
442 } else if (token == "\\layout") {
444 ert_comp.in_tabular = false;
446 insertErtContents(par, pos, font);
449 string const layoutname = lex.GetString();
450 pair<bool, LyXTextClass::LayoutList::size_type> pp
451 = textclasslist.NumberOfLayout(params.textclass,
455 if (compare_no_case(layoutname, "latex") == 0) {
456 ert_comp.active = true;
460 // The is the compability reading of layout caption.
461 // It can be removed in LyX version 1.3.0. (Lgb)
462 if (compare_no_case(layoutname, "caption") == 0) {
463 // We expect that the par we are now working on is
464 // really inside a InsetText inside a InsetFloat.
465 // We also know that captions can only be
466 // one paragraph. (Lgb)
468 // We should now read until the next "\layout"
470 // This is probably not good enough, what if the
471 // caption is the last par in the document (Lgb)
472 istream & ist = lex.getStream();
478 if (prefixIs(line, "\\layout")) {
482 if (prefixIs(line, "\\begin_inset"))
484 if (prefixIs(line, "\\end_inset")) {
495 // Now we should have the whole layout in ss
496 // we should now be able to give this to the
498 ss << "\\end_inset\n";
500 // This seems like a bug in stringstream.
501 // We really should be able to use ss
503 istringstream is(ss.str());
505 tmplex.setStream(is);
506 Inset * inset = new InsetCaption;
507 inset->Read(this, tmplex);
508 par->InsertInset(pos, inset, font);
515 par = new Paragraph(par);
519 par->layout = pp.second;
522 // use default layout "Standard" (0)
525 string const s = _("Layout had to be changed from\n")
526 + layoutname + _(" to ")
527 + textclasslist.NameOfLayout(params.textclass, par->layout);
528 InsetError * new_inset = new InsetError(s);
529 par->insertInset(0, new_inset);
531 // Test whether the layout is obsolete.
532 LyXLayout const & layout =
533 textclasslist.Style(params.textclass,
535 if (!layout.obsoleted_by().empty())
536 par->layout = textclasslist
537 .NumberOfLayout(params.textclass,
538 layout.obsoleted_by())
540 par->params().depth(depth);
541 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
542 if (file_format < 216
543 && params.language->lang() == "hebrew")
544 font.setLanguage(default_language);
549 } else if (token == "\\begin_float") {
550 // This is the compability reader. It can be removed in
551 // LyX version 1.3.0. (Lgb)
553 string const tmptok = lex.GetString();
554 //lyxerr << "old float: " << tmptok << endl;
557 stringstream old_float;
559 if (tmptok == "footnote") {
560 inset = new InsetFoot;
561 } else if (tmptok == "margin") {
562 inset = new InsetMarginal;
563 } else if (tmptok == "fig") {
564 inset = new InsetFloat("figure");
565 old_float << "placement htbp\n"
567 } else if (tmptok == "tab") {
568 inset = new InsetFloat("table");
569 old_float << "placement htbp\n"
571 } else if (tmptok == "alg") {
572 inset = new InsetFloat("algorithm");
573 old_float << "placement htbp\n"
575 } else if (tmptok == "wide-fig") {
576 inset = new InsetFloat("figure");
577 //InsetFloat * tmp = new InsetFloat("figure");
580 old_float << "placement htbp\n"
582 } else if (tmptok == "wide-tab") {
583 inset = new InsetFloat("table");
584 //InsetFloat * tmp = new InsetFloat("table");
587 old_float << "placement htbp\n"
593 return false; // no end read yet
596 old_float << "collapsed true\n";
598 // Here we need to check for \end_deeper and handle that
599 // before we do the footnote parsing.
600 // This _is_ a hack! (Lgb)
603 string const tmp = lex.GetString();
604 if (tmp == "\\end_deeper") {
605 //lyxerr << "\\end_deeper caught!" << endl;
607 lex.printError("\\end_deeper: "
608 "depth is already null");
613 old_float << tmp << ' ';
618 old_float << lex.getLongString("\\end_float")
619 << "\n\\end_inset\n";
620 //lyxerr << "Float Body:\n" << old_float.str() << endl;
621 // That this does not work seems like a bug
622 // in stringstream. (Lgb)
623 istringstream istr(old_float.str());
625 nylex.setStream(istr);
626 inset->read(this, nylex);
627 par->insertInset(pos, inset, font);
629 } else if (token == "\\begin_deeper") {
631 } else if (token == "\\end_deeper") {
633 lex.printError("\\end_deeper: "
634 "depth is already null");
638 } else if (token == "\\begin_preamble") {
639 params.readPreamble(lex);
640 } else if (token == "\\textclass") {
642 pair<bool, LyXTextClassList::size_type> pp =
643 textclasslist.NumberOfClass(lex.GetString());
645 params.textclass = pp.second;
647 WriteAlert(string(_("Textclass error")),
648 string(_("The document uses an unknown textclass \"")) +
649 lex.GetString() + string("\"."),
650 string(_("LyX will not be able to produce output correctly.")));
651 params.textclass = 0;
653 if (!textclasslist.Load(params.textclass)) {
654 // if the textclass wasn't loaded properly
655 // we need to either substitute another
656 // or stop loading the file.
657 // I can substitute but I don't see how I can
658 // stop loading... ideas?? ARRae980418
659 WriteAlert(_("Textclass Loading Error!"),
660 string(_("Can't load textclass ")) +
661 textclasslist.NameOfClass(params.textclass),
662 _("-- substituting default"));
663 params.textclass = 0;
665 } else if (token == "\\options") {
667 params.options = lex.GetString();
668 } else if (token == "\\language") {
669 params.readLanguage(lex);
670 } else if (token == "\\fontencoding") {
672 } else if (token == "\\inputencoding") {
674 params.inputenc = lex.GetString();
675 } else if (token == "\\graphics") {
676 params.readGraphicsDriver(lex);
677 } else if (token == "\\fontscheme") {
679 params.fonts = lex.GetString();
680 } else if (token == "\\noindent") {
681 par->params().noindent(true);
682 } else if (token == "\\fill_top") {
683 par->params().spaceTop(VSpace(VSpace::VFILL));
684 } else if (token == "\\fill_bottom") {
685 par->params().spaceBottom(VSpace(VSpace::VFILL));
686 } else if (token == "\\line_top") {
687 par->params().lineTop(true);
688 } else if (token == "\\line_bottom") {
689 par->params().lineBottom(true);
690 } else if (token == "\\pagebreak_top") {
691 par->params().pagebreakTop(true);
692 } else if (token == "\\pagebreak_bottom") {
693 par->params().pagebreakBottom(true);
694 } else if (token == "\\start_of_appendix") {
695 par->params().startOfAppendix(true);
696 } else if (token == "\\paragraph_separation") {
697 int tmpret = lex.FindToken(string_paragraph_separation);
698 if (tmpret == -1) ++tmpret;
699 if (tmpret != LYX_LAYOUT_DEFAULT)
700 params.paragraph_separation =
701 static_cast<BufferParams::PARSEP>(tmpret);
702 } else if (token == "\\defskip") {
704 params.defskip = VSpace(lex.GetString());
705 } else if (token == "\\epsfig") { // obsolete
706 // Indeed it is obsolete, but we HAVE to be backwards
707 // compatible until 0.14, because otherwise all figures
708 // in existing documents are irretrivably lost. (Asger)
709 params.readGraphicsDriver(lex);
710 } else if (token == "\\quotes_language") {
711 int tmpret = lex.FindToken(string_quotes_language);
712 if (tmpret == -1) ++tmpret;
713 if (tmpret != LYX_LAYOUT_DEFAULT) {
714 InsetQuotes::quote_language tmpl =
715 InsetQuotes::EnglishQ;
718 tmpl = InsetQuotes::EnglishQ;
721 tmpl = InsetQuotes::SwedishQ;
724 tmpl = InsetQuotes::GermanQ;
727 tmpl = InsetQuotes::PolishQ;
730 tmpl = InsetQuotes::FrenchQ;
733 tmpl = InsetQuotes::DanishQ;
736 params.quotes_language = tmpl;
738 } else if (token == "\\quotes_times") {
740 switch (lex.GetInteger()) {
742 params.quotes_times = InsetQuotes::SingleQ;
745 params.quotes_times = InsetQuotes::DoubleQ;
748 } else if (token == "\\papersize") {
749 int tmpret = lex.FindToken(string_papersize);
753 params.papersize2 = tmpret;
754 } else if (token == "\\paperpackage") {
755 int tmpret = lex.FindToken(string_paperpackages);
758 params.paperpackage = BufferParams::PACKAGE_NONE;
760 params.paperpackage = tmpret;
761 } else if (token == "\\use_geometry") {
763 params.use_geometry = lex.GetInteger();
764 } else if (token == "\\use_amsmath") {
766 params.use_amsmath = lex.GetInteger();
767 } else if (token == "\\use_natbib") {
769 params.use_natbib = lex.GetInteger();
770 } else if (token == "\\use_numerical_citations") {
772 params.use_numerical_citations = lex.GetInteger();
773 } else if (token == "\\paperorientation") {
774 int tmpret = lex.FindToken(string_orientation);
775 if (tmpret == -1) ++tmpret;
776 if (tmpret != LYX_LAYOUT_DEFAULT)
777 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
778 } else if (token == "\\paperwidth") {
780 params.paperwidth = lex.GetString();
781 } else if (token == "\\paperheight") {
783 params.paperheight = lex.GetString();
784 } else if (token == "\\leftmargin") {
786 params.leftmargin = lex.GetString();
787 } else if (token == "\\topmargin") {
789 params.topmargin = lex.GetString();
790 } else if (token == "\\rightmargin") {
792 params.rightmargin = lex.GetString();
793 } else if (token == "\\bottommargin") {
795 params.bottommargin = lex.GetString();
796 } else if (token == "\\headheight") {
798 params.headheight = lex.GetString();
799 } else if (token == "\\headsep") {
801 params.headsep = lex.GetString();
802 } else if (token == "\\footskip") {
804 params.footskip = lex.GetString();
805 } else if (token == "\\paperfontsize") {
807 params.fontsize = strip(lex.GetString());
808 } else if (token == "\\papercolumns") {
810 params.columns = lex.GetInteger();
811 } else if (token == "\\papersides") {
813 switch (lex.GetInteger()) {
815 case 1: params.sides = LyXTextClass::OneSide; break;
816 case 2: params.sides = LyXTextClass::TwoSides; break;
818 } else if (token == "\\paperpagestyle") {
820 params.pagestyle = strip(lex.GetString());
821 } else if (token == "\\bullet") {
823 int const index = lex.GetInteger();
825 int temp_int = lex.GetInteger();
826 params.user_defined_bullets[index].setFont(temp_int);
827 params.temp_bullets[index].setFont(temp_int);
829 temp_int = lex.GetInteger();
830 params.user_defined_bullets[index].setCharacter(temp_int);
831 params.temp_bullets[index].setCharacter(temp_int);
833 temp_int = lex.GetInteger();
834 params.user_defined_bullets[index].setSize(temp_int);
835 params.temp_bullets[index].setSize(temp_int);
837 string const temp_str = lex.GetString();
838 if (temp_str != "\\end_bullet") {
839 // this element isn't really necessary for
840 // parsing but is easier for humans
841 // to understand bullets. Put it back and
842 // set a debug message?
843 lex.printError("\\end_bullet expected, got" + temp_str);
844 //how can I put it back?
846 } else if (token == "\\bulletLaTeX") {
848 int const index = lex.GetInteger();
850 string temp_str = lex.GetString();
852 while (temp_str != "\\end_bullet") {
853 // this loop structure is needed when user
854 // enters an empty string since the first
855 // thing returned will be the \\end_bullet
857 // if the LaTeX entry has spaces. Each element
858 // therefore needs to be read in turn
861 temp_str = lex.GetString();
863 params.user_defined_bullets[index].setText(sum_str);
864 params.temp_bullets[index].setText(sum_str);
865 } else if (token == "\\secnumdepth") {
867 params.secnumdepth = lex.GetInteger();
868 } else if (token == "\\tocdepth") {
870 params.tocdepth = lex.GetInteger();
871 } else if (token == "\\spacing") {
873 string const tmp = strip(lex.GetString());
874 Spacing::Space tmp_space = Spacing::Default;
876 if (tmp == "single") {
877 tmp_space = Spacing::Single;
878 } else if (tmp == "onehalf") {
879 tmp_space = Spacing::Onehalf;
880 } else if (tmp == "double") {
881 tmp_space = Spacing::Double;
882 } else if (tmp == "other") {
884 tmp_space = Spacing::Other;
885 tmp_val = lex.GetFloat();
887 lex.printError("Unknown spacing token: '$$Token'");
889 // Small hack so that files written with klyx will be
892 par->params().spacing(Spacing(tmp_space, tmp_val));
894 params.spacing.set(tmp_space, tmp_val);
896 } else if (token == "\\paragraph_spacing") {
898 string const tmp = strip(lex.GetString());
899 if (tmp == "single") {
900 par->params().spacing(Spacing(Spacing::Single));
901 } else if (tmp == "onehalf") {
902 par->params().spacing(Spacing(Spacing::Onehalf));
903 } else if (tmp == "double") {
904 par->params().spacing(Spacing(Spacing::Double));
905 } else if (tmp == "other") {
907 par->params().spacing(Spacing(Spacing::Other,
910 lex.printError("Unknown spacing token: '$$Token'");
912 } else if (token == "\\float_placement") {
914 params.float_placement = lex.GetString();
915 } else if (token == "\\family") {
917 font.setLyXFamily(lex.GetString());
918 } else if (token == "\\series") {
920 font.setLyXSeries(lex.GetString());
921 } else if (token == "\\shape") {
923 font.setLyXShape(lex.GetString());
924 } else if (token == "\\size") {
926 font.setLyXSize(lex.GetString());
929 #warning compatability hack needed
931 } else if (token == "\\latex") {
933 string const tok = lex.GetString();
934 // This is dirty, but gone with LyX3. (Asger)
935 if (tok == "no_latex")
936 font.setLatex(LyXFont::OFF);
937 else if (tok == "latex")
938 font.setLatex(LyXFont::ON);
939 else if (tok == "default")
940 font.setLatex(LyXFont::INHERIT);
942 lex.printError("Unknown LaTeX font flag "
945 } else if (token == "\\latex") {
947 string const tok = lex.GetString();
948 if (tok == "no_latex") {
950 insertErtContents(par, pos, font);
951 } else if (tok == "latex") {
952 ert_comp.active = true;
953 } else if (tok == "default") {
955 insertErtContents(par, pos, font);
957 lex.printError("Unknown LaTeX font flag "
961 } else if (token == "\\lang") {
963 string const tok = lex.GetString();
964 Language const * lang = languages.getLanguage(tok);
966 font.setLanguage(lang);
968 font.setLanguage(params.language);
969 lex.printError("Unknown language `$$Token'");
971 } else if (token == "\\numeric") {
973 font.setNumber(font.setLyXMisc(lex.GetString()));
974 } else if (token == "\\emph") {
976 font.setEmph(font.setLyXMisc(lex.GetString()));
977 } else if (token == "\\bar") {
979 string const tok = lex.GetString();
980 // This is dirty, but gone with LyX3. (Asger)
982 font.setUnderbar(LyXFont::ON);
983 else if (tok == "no")
984 font.setUnderbar(LyXFont::OFF);
985 else if (tok == "default")
986 font.setUnderbar(LyXFont::INHERIT);
988 lex.printError("Unknown bar font flag "
990 } else if (token == "\\noun") {
992 font.setNoun(font.setLyXMisc(lex.GetString()));
993 } else if (token == "\\color") {
995 font.setLyXColor(lex.GetString());
996 } else if (token == "\\align") {
997 int tmpret = lex.FindToken(string_align);
998 if (tmpret == -1) ++tmpret;
999 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1000 int const tmpret2 = int(pow(2.0, tmpret));
1001 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1002 par->params().align(LyXAlignment(tmpret2));
1004 } else if (token == "\\added_space_top") {
1006 par->params().spaceTop(VSpace(lex.GetString()));
1007 } else if (token == "\\added_space_bottom") {
1009 par->params().spaceBottom(VSpace(lex.GetString()));
1010 #ifndef NO_PEXTRA_REALLY
1011 } else if (token == "\\pextra_type") {
1013 par->params().pextraType(lex.GetInteger());
1014 } else if (token == "\\pextra_width") {
1016 par->params().pextraWidth(lex.GetString());
1017 } else if (token == "\\pextra_widthp") {
1019 par->params().pextraWidthp(lex.GetString());
1020 } else if (token == "\\pextra_alignment") {
1022 par->params().pextraAlignment(lex.GetInteger());
1023 } else if (token == "\\pextra_hfill") {
1025 par->params().pextraHfill(lex.GetInteger());
1026 } else if (token == "\\pextra_start_minipage") {
1028 par->params().pextraStartMinipage(lex.GetInteger());
1030 } else if (token == "\\labelwidthstring") {
1032 par->params().labelWidthString(lex.GetString());
1033 // do not delete this token, it is still needed!
1034 } else if (token == "\\end_inset") {
1035 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1036 << "Last inset read was: " << last_inset_read
1038 // Simply ignore this. The insets do not have
1040 // But insets should read it, it is a part of
1041 // the inset isn't it? Lgb.
1042 } else if (token == "\\begin_inset") {
1044 insertErtContents(par, pos, font, false);
1045 ert_stack.push(ert_comp);
1046 ert_comp = ErtComp();
1048 readInset(lex, par, pos, font);
1050 ert_comp = ert_stack.top();
1053 } else if (token == "\\SpecialChar") {
1054 LyXLayout const & layout =
1055 textclasslist.Style(params.textclass,
1058 // Insets don't make sense in a free-spacing context! ---Kayvan
1059 if (layout.free_spacing) {
1062 string next_token = lex.GetString();
1063 if (next_token == "\\-") {
1064 par->insertChar(pos, '-', font);
1065 } else if (next_token == "\\protected_separator"
1066 || next_token == "~") {
1067 par->insertChar(pos, ' ', font);
1069 lex.printError("Token `$$Token' "
1071 "paragraph layout!");
1076 Inset * inset = new InsetSpecialChar;
1077 inset->read(this, lex);
1078 par->insertInset(pos, inset, font);
1081 } else if (token == "\\newline") {
1084 if (!ert_comp.in_tabular && ert_comp.active) {
1085 ert_comp.contents += char(Paragraph::META_NEWLINE);
1087 // Since we cannot know it this is only a regular
1088 // newline or a tabular cell delimter we have to
1089 // handle the ERT here.
1090 insertErtContents(par, pos, font, false);
1092 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1096 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1099 } else if (token == "\\LyXTable") {
1101 ert_comp.in_tabular = true;
1103 Inset * inset = new InsetTabular(*this);
1104 inset->read(this, lex);
1105 par->insertInset(pos, inset, font);
1107 } else if (token == "\\hfill") {
1108 par->insertChar(pos, Paragraph::META_HFILL, font);
1110 } else if (token == "\\protected_separator") { // obsolete
1111 // This is a backward compability thingie. (Lgb)
1112 // Remove it later some time...introduced with fileformat
1114 LyXLayout const & layout =
1115 textclasslist.Style(params.textclass,
1118 if (layout.free_spacing) {
1119 par->insertChar(pos, ' ', font);
1121 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1122 par->insertInset(pos, inset, font);
1125 } else if (token == "\\bibitem") { // ale970302
1127 InsetCommandParams p("bibitem", "dummy");
1128 par->bibkey = new InsetBibKey(p);
1130 par->bibkey->read(this, lex);
1131 } else if (token == "\\backslash") {
1133 if (ert_comp.active) {
1134 ert_comp.contents += "\\";
1137 par->insertChar(pos, '\\', font);
1142 } else if (token == "\\the_end") {
1144 // If we still have some ert active here we have to insert
1145 // it so we don't loose it. (Lgb)
1146 insertErtContents(par, pos, font);
1148 the_end_read = true;
1149 minipar = parBeforeMinipage = 0;
1152 if (ert_comp.active) {
1153 ert_comp.contents += token;
1156 // This should be insurance for the future: (Asger)
1157 lex.printError("Unknown token `$$Token'. "
1158 "Inserting as text.");
1159 string::const_iterator cit = token.begin();
1160 string::const_iterator end = token.end();
1161 for (; cit != end; ++cit) {
1162 par->insertChar(pos, (*cit), font);
1170 #ifndef NO_PEXTRA_REALLY
1171 // I wonder if we could use this blanket fix for all the
1172 // checkminipage cases...
1173 if (par && par->size()) {
1174 // It is possible that this will check to often,
1175 // but that should not be an correctness issue.
1176 // Only a speed issue.
1177 checkminipage = true;
1180 // now check if we have a minipage paragraph as at this
1181 // point we already read all the necessary data!
1182 // this cannot be done in layout because there we did
1183 // not read yet the paragraph PEXTRA-params (Jug)
1185 // BEGIN pextra_minipage compability
1186 // This should be removed in 1.3.x (Lgb)
1188 // This compability code is not perfect. In a couple
1189 // of rand cases it fails. When the minipage par is
1190 // the first par in the document, and when there are
1191 // none or only one regular paragraphs after the
1192 // minipage. Currently I am not investing any effort
1193 // in fixing those cases.
1195 //lyxerr << "Call depth: " << call_depth << endl;
1196 if (checkminipage && (call_depth == 1)) {
1197 checkminipage = false;
1198 if (minipar && (minipar != par) &&
1199 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1201 lyxerr << "minipages in a row" << endl;
1202 if (par->params().pextraStartMinipage()) {
1203 lyxerr << "start new minipage" << endl;
1204 // minipages in a row
1205 par->previous()->next(0);
1208 Paragraph * tmp = minipar;
1210 tmp->params().pextraType(0);
1211 tmp->params().pextraWidth(string());
1212 tmp->params().pextraWidthp(string());
1213 tmp->params().pextraAlignment(0);
1214 tmp->params().pextraHfill(false);
1215 tmp->params().pextraStartMinipage(false);
1218 // create a new paragraph to insert the
1219 // minipages in the following case
1220 if (par->params().pextraStartMinipage() &&
1221 !par->params().pextraHfill())
1223 Paragraph * p = new Paragraph;
1225 p->previous(parBeforeMinipage);
1226 parBeforeMinipage->next(p);
1228 p->params().depth(parBeforeMinipage->params().depth());
1229 parBeforeMinipage = p;
1231 InsetMinipage * mini = new InsetMinipage;
1232 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1233 mini->width(par->params().pextraWidth());
1234 if (!par->params().pextraWidthp().empty()) {
1235 lyxerr << "WP:" << mini->width() << endl;
1236 mini->width(tostr(par->params().pextraWidthp())+"%");
1238 mini->inset.paragraph(par);
1239 // Insert the minipage last in the
1240 // previous paragraph.
1241 if (par->params().pextraHfill()) {
1242 parBeforeMinipage->insertChar
1243 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1245 parBeforeMinipage->insertInset
1246 (parBeforeMinipage->size(), mini);
1250 lyxerr << "new minipage par" << endl;
1251 //nothing to do just continue reading
1254 } else if (minipar && (minipar != par)) {
1255 lyxerr << "last minipage par read" << endl;
1256 // The last paragraph read was not part of a
1257 // minipage but the par linked list is...
1258 // So we need to remove the last par from the
1260 if (par->previous())
1261 par->previous()->next(0);
1262 par->previous(parBeforeMinipage);
1263 parBeforeMinipage->next(par);
1264 Paragraph * tmp = minipar;
1266 tmp->params().pextraType(0);
1267 tmp->params().pextraWidth(string());
1268 tmp->params().pextraWidthp(string());
1269 tmp->params().pextraAlignment(0);
1270 tmp->params().pextraHfill(false);
1271 tmp->params().pextraStartMinipage(false);
1274 depth = parBeforeMinipage->params().depth();
1275 minipar = parBeforeMinipage = 0;
1276 } else if (!minipar &&
1277 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1279 // par is the first paragraph in a minipage
1280 lyxerr << "begin minipage" << endl;
1281 // To minimize problems for
1282 // the users we will insert
1283 // the first minipage in
1284 // a sequence of minipages
1285 // in its own paragraph.
1286 Paragraph * p = new Paragraph;
1288 p->previous(par->previous());
1290 p->params().depth(depth);
1291 par->params().depth(0);
1293 if (par->previous())
1294 par->previous()->next(p);
1296 parBeforeMinipage = p;
1298 if (!first_par || (first_par == par))
1301 InsetMinipage * mini = new InsetMinipage;
1302 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1303 mini->width(minipar->params().pextraWidth());
1304 if (!par->params().pextraWidthp().empty()) {
1305 lyxerr << "WP:" << mini->width() << endl;
1306 mini->width(tostr(par->params().pextraWidthp())+"%");
1308 mini->inset.paragraph(minipar);
1310 // Insert the minipage last in the
1311 // previous paragraph.
1312 if (minipar->params().pextraHfill()) {
1313 parBeforeMinipage->insertChar
1314 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1316 parBeforeMinipage->insertInset
1317 (parBeforeMinipage->size(), mini);
1320 // End of pextra_minipage compability
1323 return the_end_read;
1326 // needed to insert the selection
1327 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1328 LyXFont const & font,
1329 string const & str) const
1331 LyXLayout const & layout = textclasslist.Style(params.textclass,
1333 // insert the string, don't insert doublespace
1334 bool space_inserted = true;
1335 for(string::const_iterator cit = str.begin();
1336 cit != str.end(); ++cit) {
1338 if (par->size() || layout.keepempty) {
1339 par->breakParagraph(params, pos,
1340 layout.isEnvironment());
1343 space_inserted = true;
1347 // do not insert consecutive spaces if !free_spacing
1348 } else if ((*cit == ' ' || *cit == '\t')
1349 && space_inserted && !layout.free_spacing) {
1351 } else if (*cit == '\t') {
1352 if (!layout.free_spacing) {
1353 // tabs are like spaces here
1354 par->insertChar(pos, ' ', font);
1356 space_inserted = true;
1358 const Paragraph::value_type nb = 8 - pos % 8;
1359 for (Paragraph::size_type a = 0;
1361 par->insertChar(pos, ' ', font);
1364 space_inserted = true;
1366 } else if (!IsPrintable(*cit)) {
1367 // Ignore unprintables
1370 // just insert the character
1371 par->insertChar(pos, *cit, font);
1373 space_inserted = (*cit == ' ');
1380 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1381 int & pos, LyXFont & font)
1383 // consistency check
1384 if (lex.GetString() != "\\begin_inset") {
1385 lyxerr << "Buffer::readInset: Consistency check failed."
1392 string const tmptok = lex.GetString();
1393 last_inset_read = tmptok;
1395 // test the different insets
1396 if (tmptok == "LatexCommand") {
1397 InsetCommandParams inscmd;
1400 string const cmdName = inscmd.getCmdName();
1402 // This strange command allows LyX to recognize "natbib" style
1403 // citations: citet, citep, Citet etc.
1404 if (compare_no_case(cmdName, "cite", 4) == 0) {
1405 inset = new InsetCitation(inscmd);
1406 } else if (cmdName == "bibitem") {
1407 lex.printError("Wrong place for bibitem");
1408 inset = new InsetBibKey(inscmd);
1409 } else if (cmdName == "BibTeX") {
1410 inset = new InsetBibtex(inscmd);
1411 } else if (cmdName == "index") {
1412 inset = new InsetIndex(inscmd);
1413 } else if (cmdName == "include") {
1414 inset = new InsetInclude(inscmd, *this);
1415 } else if (cmdName == "label") {
1416 inset = new InsetLabel(inscmd);
1417 } else if (cmdName == "url"
1418 || cmdName == "htmlurl") {
1419 inset = new InsetUrl(inscmd);
1420 } else if (cmdName == "ref"
1421 || cmdName == "pageref"
1422 || cmdName == "vref"
1423 || cmdName == "vpageref"
1424 || cmdName == "prettyref") {
1425 if (!inscmd.getOptions().empty()
1426 || !inscmd.getContents().empty()) {
1427 inset = new InsetRef(inscmd, *this);
1429 } else if (cmdName == "tableofcontents") {
1430 inset = new InsetTOC(inscmd);
1431 } else if (cmdName == "listofalgorithms") {
1432 inset = new InsetFloatList("algorithm");
1433 } else if (cmdName == "listoffigures") {
1434 inset = new InsetFloatList("figure");
1435 } else if (cmdName == "listoftables") {
1436 inset = new InsetFloatList("table");
1437 } else if (cmdName == "printindex") {
1438 inset = new InsetPrintIndex(inscmd);
1439 } else if (cmdName == "lyxparent") {
1440 inset = new InsetParent(inscmd, *this);
1443 bool alreadyread = false;
1444 if (tmptok == "Quotes") {
1445 inset = new InsetQuotes;
1446 } else if (tmptok == "External") {
1447 inset = new InsetExternal;
1448 } else if (tmptok == "FormulaMacro") {
1449 inset = new InsetFormulaMacro;
1450 } else if (tmptok == "Formula") {
1451 inset = new InsetFormula;
1452 } else if (tmptok == "Figure") {
1453 inset = new InsetFig(100, 100, *this);
1454 } else if (tmptok == "Info") {// backwards compatibility
1455 inset = new InsetNote(this,
1456 lex.getLongString("\\end_inset"),
1459 } else if (tmptok == "Note") {
1460 inset = new InsetNote;
1461 } else if (tmptok == "Include") {
1462 InsetCommandParams p( "Include" );
1463 inset = new InsetInclude(p, *this);
1464 } else if (tmptok == "ERT") {
1465 inset = new InsetERT;
1466 } else if (tmptok == "Tabular") {
1467 inset = new InsetTabular(*this);
1468 } else if (tmptok == "Text") {
1469 inset = new InsetText;
1470 } else if (tmptok == "Foot") {
1471 inset = new InsetFoot;
1472 } else if (tmptok == "Marginal") {
1473 inset = new InsetMarginal;
1474 } else if (tmptok == "Minipage") {
1475 inset = new InsetMinipage;
1476 } else if (tmptok == "Float") {
1478 string tmptok = lex.GetString();
1479 inset = new InsetFloat(tmptok);
1481 } else if (tmptok == "List") {
1482 inset = new InsetList;
1483 } else if (tmptok == "Theorem") {
1484 inset = new InsetList;
1486 } else if (tmptok == "Caption") {
1487 inset = new InsetCaption;
1488 } else if (tmptok == "GRAPHICS") {
1489 inset = new InsetGraphics;
1490 } else if (tmptok == "FloatList") {
1491 inset = new InsetFloatList;
1494 if (inset && !alreadyread) inset->read(this, lex);
1498 par->insertInset(pos, inset, font);
1504 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1508 string const token(lex.GetString());
1509 if (token == "\\lyxformat") { // the first token _must_ be...
1511 string tmp_format = lex.GetString();
1512 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1513 // if present remove ".," from string.
1514 string::size_type dot = tmp_format.find_first_of(".,");
1515 //lyxerr << " dot found at " << dot << endl;
1516 if (dot != string::npos)
1517 tmp_format.erase(dot, 1);
1518 file_format = strToInt(tmp_format);
1519 if (file_format == LYX_FORMAT) {
1521 } else if (file_format > LYX_FORMAT) {
1523 WriteAlert(_("Warning!"),
1524 _("LyX file format is newer that what"),
1525 _("is supported in this LyX version. Expect some problems."));
1527 } else if (file_format < LYX_FORMAT) {
1529 if (file_format < 200) {
1530 WriteAlert(_("ERROR!"),
1531 _("Old LyX file format found. "
1532 "Use LyX 0.10.x to read this!"));
1536 bool the_end = readLyXformat2(lex, par);
1538 // the_end was added in 213
1539 if (file_format < 213)
1543 WriteAlert(_("Warning!"),
1544 _("Reading of document is not complete"),
1545 _("Maybe the document is truncated"));
1547 } else { // "\\lyxformat" not found
1548 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1551 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1556 // Should probably be moved to somewhere else: BufferView? LyXView?
1557 bool Buffer::save() const
1559 // We don't need autosaves in the immediate future. (Asger)
1560 resetAutosaveTimers();
1564 if (lyxrc.make_backup) {
1565 s = fileName() + '~';
1566 if (!lyxrc.backupdir_path.empty())
1567 s = AddName(lyxrc.backupdir_path,
1568 subst(os::slashify_path(s),'/','!'));
1570 // Rename is the wrong way of making a backup,
1571 // this is the correct way.
1572 /* truss cp fil fil2:
1573 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1574 stat("LyXVC.lyx", 0xEFFFF688) = 0
1575 open("LyXVC.lyx", O_RDONLY) = 3
1576 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1577 fstat(4, 0xEFFFF508) = 0
1578 fstat(3, 0xEFFFF508) = 0
1579 read(3, " # T h i s f i l e w".., 8192) = 5579
1580 write(4, " # T h i s f i l e w".., 5579) = 5579
1581 read(3, 0xEFFFD4A0, 8192) = 0
1584 chmod("LyXVC3.lyx", 0100644) = 0
1585 lseek(0, 0, SEEK_CUR) = 46440
1589 // Should probably have some more error checking here.
1590 // Should be cleaned up in 0.13, at least a bit.
1591 // Doing it this way, also makes the inodes stay the same.
1592 // This is still not a very good solution, in particular we
1593 // might loose the owner of the backup.
1594 FileInfo finfo(fileName());
1595 if (finfo.exist()) {
1596 mode_t fmode = finfo.getMode();
1597 struct utimbuf times = {
1598 finfo.getAccessTime(),
1599 finfo.getModificationTime() };
1601 ifstream ifs(fileName().c_str());
1602 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1607 ::chmod(s.c_str(), fmode);
1609 if (::utime(s.c_str(), ×)) {
1610 lyxerr << "utime error." << endl;
1613 lyxerr << "LyX was not able to make "
1614 "backup copy. Beware." << endl;
1619 if (writeFile(fileName(), false)) {
1621 removeAutosaveFile(fileName());
1623 // Saving failed, so backup is not backup
1624 if (lyxrc.make_backup) {
1625 lyx::rename(s, fileName());
1633 // Returns false if unsuccesful
1634 bool Buffer::writeFile(string const & fname, bool flag) const
1636 // if flag is false writeFile will not create any GUI
1637 // warnings, only cerr.
1638 // Needed for autosave in background or panic save (Matthias 120496)
1640 if (read_only && (fname == filename)) {
1641 // Here we should come with a question if we should
1642 // perform the write anyway.
1644 lyxerr << _("Error! Document is read-only: ")
1647 WriteAlert(_("Error! Document is read-only: "),
1652 FileInfo finfo(fname);
1653 if (finfo.exist() && !finfo.writable()) {
1654 // Here we should come with a question if we should
1655 // try to do the save anyway. (i.e. do a chmod first)
1657 lyxerr << _("Error! Cannot write file: ")
1660 WriteFSAlert(_("Error! Cannot write file: "),
1665 ofstream ofs(fname.c_str());
1668 lyxerr << _("Error! Cannot open file: ")
1671 WriteFSAlert(_("Error! Cannot open file: "),
1677 // Use the standard "C" locale for file output.
1678 ofs.imbue(std::locale::classic());
1681 // The top of the file should not be written by params.
1683 // write out a comment in the top of the file
1684 ofs << '#' << LYX_DOCVERSION
1685 << " created this file. For more info see http://www.lyx.org/\n"
1686 << "\\lyxformat " << LYX_FORMAT << "\n";
1688 // now write out the buffer paramters.
1689 params.writeFile(ofs);
1691 Paragraph::depth_type depth = 0;
1693 // this will write out all the paragraphs
1694 // using recursive descent.
1695 paragraph->writeFile(this, ofs, params, depth);
1697 // Write marker that shows file is complete
1698 ofs << "\n\\the_end" << endl;
1702 // how to check if close went ok?
1703 // Following is an attempt... (BE 20001011)
1705 // good() returns false if any error occured, including some
1706 // formatting error.
1707 // bad() returns true if something bad happened in the buffer,
1708 // which should include file system full errors.
1715 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1717 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1727 string const Buffer::asciiParagraph(Paragraph const * par,
1728 unsigned int linelen) const
1730 ostringstream buffer;
1731 Paragraph::depth_type depth = 0;
1733 Paragraph::depth_type ltype_depth = 0;
1734 unsigned int currlinelen = 0;
1735 bool ref_printed = false;
1739 if (!par->previous()) {
1740 // begins or ends a deeper area ?
1741 if (depth != par->params().depth()) {
1742 if (par->params().depth() > depth) {
1743 while (par->params().depth() > depth) {
1747 while (par->params().depth() < depth) {
1753 // First write the layout
1754 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1755 if (tmp == "Itemize") {
1757 ltype_depth = depth + 1;
1758 } else if (tmp == "Enumerate") {
1760 ltype_depth = depth + 1;
1761 } else if (contains(tmp, "ection")) {
1763 ltype_depth = depth + 1;
1764 } else if (contains(tmp, "aragraph")) {
1766 ltype_depth = depth + 1;
1767 } else if (tmp == "Description") {
1769 ltype_depth = depth + 1;
1770 } else if (tmp == "Abstract") {
1773 } else if (tmp == "Bibliography") {
1781 /* maybe some vertical spaces */
1783 /* the labelwidthstring used in lists */
1787 /* some pagebreaks? */
1791 /* what about the alignment */
1793 lyxerr << "Should this ever happen?" << endl;
1797 LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1799 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1800 if (!i && !noparbreak) {
1803 for (Paragraph::depth_type j = 0; j < depth; ++j)
1805 currlinelen = depth * 2;
1808 case 4: // (Sub)Paragraph
1809 case 5: // Description
1813 buffer << "Abstract\n\n";
1815 buffer << "Abstract: ";
1817 case 7: // Bibliography
1820 buffer << "References\n\n";
1822 buffer << "References: ";
1827 buffer << par->params().labelString() << " ";
1830 if (ltype_depth > depth) {
1831 for (Paragraph::depth_type j = ltype_depth - 1;
1834 currlinelen += (ltype_depth-depth)*2;
1838 LyXFont const font2 = par->getFontSettings(params, i);
1839 if (font1.latex() != font2.latex()) {
1840 if (font2.latex() == LyXFont::OFF)
1849 char c = par->getUChar(params, i);
1853 case Paragraph::META_INSET:
1855 Inset const * inset = par->getInset(i);
1857 if (!inset->ascii(this, buffer)) {
1860 rsplit(buffer.str().c_str(),
1862 currlinelen += s.length();
1864 // to be sure it breaks paragraph
1865 currlinelen += linelen;
1871 case Paragraph::META_NEWLINE:
1874 for (Paragraph::depth_type j = 0;
1878 currlinelen = depth * 2;
1879 if (ltype_depth > depth) {
1880 for (Paragraph::depth_type j = ltype_depth;
1883 currlinelen += (ltype_depth - depth) * 2;
1887 case Paragraph::META_HFILL:
1896 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1897 (c == ' ') && ((i + 2) < par->size()))
1900 for (Paragraph::depth_type j = 0;
1903 currlinelen = depth * 2;
1904 if (ltype_depth > depth) {
1905 for (Paragraph::depth_type j = ltype_depth;
1908 currlinelen += (ltype_depth-depth)*2;
1910 } else if (c != '\0')
1913 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1918 return buffer.str().c_str();
1922 void Buffer::writeFileAscii(string const & fname, int linelen)
1924 ofstream ofs(fname.c_str());
1926 WriteFSAlert(_("Error: Cannot write file:"), fname);
1929 writeFileAscii(ofs, linelen);
1933 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1935 Paragraph * par = paragraph;
1937 ofs << asciiParagraph(par, linelen);
1945 void Buffer::makeLaTeXFile(string const & fname,
1946 string const & original_path,
1947 bool nice, bool only_body)
1949 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1951 niceFile = nice; // this will be used by Insetincludes.
1953 tex_code_break_column = lyxrc.ascii_linelen;
1955 LyXTextClass const & tclass =
1956 textclasslist.TextClass(params.textclass);
1958 ofstream ofs(fname.c_str());
1960 WriteFSAlert(_("Error: Cannot open file: "), fname);
1964 // validate the buffer.
1965 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1966 LaTeXFeatures features(params, tclass.numLayouts());
1968 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1971 // The starting paragraph of the coming rows is the
1972 // first paragraph of the document. (Asger)
1973 texrow.start(paragraph, 0);
1975 if (!only_body && nice) {
1976 ofs << "%% " LYX_DOCVERSION " created this file. "
1977 "For more info, see http://www.lyx.org/.\n"
1978 "%% Do not edit unless you really know what "
1983 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1984 // There are a few differences between nice LaTeX and usual files:
1985 // usual is \batchmode and has a
1986 // special input@path to allow the including of figures
1987 // with either \input or \includegraphics (what figinsets do).
1988 // batchmode is not set if there is a tex_code_break_column.
1989 // In this case somebody is interested in the generated LaTeX,
1990 // so this is OK. input@path is set when the actual parameter
1991 // original_path is set. This is done for usual tex-file, but not
1992 // for nice-latex-file. (Matthias 250696)
1995 // code for usual, NOT nice-latex-file
1996 ofs << "\\batchmode\n"; // changed
1997 // from \nonstopmode
2000 if (!original_path.empty()) {
2001 ofs << "\\makeatletter\n"
2002 << "\\def\\input@path{{"
2003 << os::external_path(original_path) << "/}}\n"
2004 << "\\makeatother\n";
2010 ofs << "\\documentclass";
2012 ostringstream options; // the document class options.
2014 if (tokenPos(tclass.opt_fontsize(),
2015 '|', params.fontsize) >= 0) {
2016 // only write if existing in list (and not default)
2017 options << params.fontsize << "pt,";
2021 if (!params.use_geometry &&
2022 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2023 switch (params.papersize) {
2024 case BufferParams::PAPER_A4PAPER:
2025 options << "a4paper,";
2027 case BufferParams::PAPER_USLETTER:
2028 options << "letterpaper,";
2030 case BufferParams::PAPER_A5PAPER:
2031 options << "a5paper,";
2033 case BufferParams::PAPER_B5PAPER:
2034 options << "b5paper,";
2036 case BufferParams::PAPER_EXECUTIVEPAPER:
2037 options << "executivepaper,";
2039 case BufferParams::PAPER_LEGALPAPER:
2040 options << "legalpaper,";
2046 if (params.sides != tclass.sides()) {
2047 switch (params.sides) {
2048 case LyXTextClass::OneSide:
2049 options << "oneside,";
2051 case LyXTextClass::TwoSides:
2052 options << "twoside,";
2058 if (params.columns != tclass.columns()) {
2059 if (params.columns == 2)
2060 options << "twocolumn,";
2062 options << "onecolumn,";
2065 if (!params.use_geometry
2066 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2067 options << "landscape,";
2069 // language should be a parameter to \documentclass
2071 ostringstream language_options;
2072 if (params.language->babel() == "hebrew"
2073 && default_language->babel() != "hebrew")
2074 // This seems necessary
2075 features.UsedLanguages.insert(default_language);
2077 if (lyxrc.language_use_babel ||
2078 params.language->lang() != lyxrc.default_language ||
2079 !features.UsedLanguages.empty()) {
2081 for (LaTeXFeatures::LanguageList::const_iterator cit =
2082 features.UsedLanguages.begin();
2083 cit != features.UsedLanguages.end(); ++cit)
2084 language_options << (*cit)->babel() << ',';
2085 language_options << params.language->babel();
2086 if (lyxrc.language_global_options)
2087 options << language_options.str() << ',';
2090 // the user-defined options
2091 if (!params.options.empty()) {
2092 options << params.options << ',';
2095 string strOptions(options.str().c_str());
2096 if (!strOptions.empty()){
2097 strOptions = strip(strOptions, ',');
2098 ofs << '[' << strOptions << ']';
2102 << textclasslist.LatexnameOfClass(params.textclass)
2105 // end of \documentclass defs
2107 // font selection must be done before loading fontenc.sty
2108 // The ae package is not needed when using OT1 font encoding.
2109 if (params.fonts != "default" &&
2110 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2111 ofs << "\\usepackage{" << params.fonts << "}\n";
2113 if (params.fonts == "ae") {
2114 ofs << "\\usepackage{aecompl}\n";
2118 // this one is not per buffer
2119 if (lyxrc.fontenc != "default") {
2120 ofs << "\\usepackage[" << lyxrc.fontenc
2125 if (params.inputenc == "auto") {
2126 string const doc_encoding =
2127 params.language->encoding()->LatexName();
2129 // Create a list with all the input encodings used
2131 set<string> encodings;
2132 for (LaTeXFeatures::LanguageList::const_iterator it =
2133 features.UsedLanguages.begin();
2134 it != features.UsedLanguages.end(); ++it)
2135 if ((*it)->encoding()->LatexName() != doc_encoding)
2136 encodings.insert((*it)->encoding()->LatexName());
2138 ofs << "\\usepackage[";
2139 std::copy(encodings.begin(), encodings.end(),
2140 std::ostream_iterator<string>(ofs, ","));
2141 ofs << doc_encoding << "]{inputenc}\n";
2143 } else if (params.inputenc != "default") {
2144 ofs << "\\usepackage[" << params.inputenc
2149 // At the very beginning the text parameters.
2150 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2151 switch (params.paperpackage) {
2152 case BufferParams::PACKAGE_A4:
2153 ofs << "\\usepackage{a4}\n";
2156 case BufferParams::PACKAGE_A4WIDE:
2157 ofs << "\\usepackage{a4wide}\n";
2160 case BufferParams::PACKAGE_WIDEMARGINSA4:
2161 ofs << "\\usepackage[widemargins]{a4}\n";
2166 if (params.use_geometry) {
2167 ofs << "\\usepackage{geometry}\n";
2169 ofs << "\\geometry{verbose";
2170 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2171 ofs << ",landscape";
2172 switch (params.papersize2) {
2173 case BufferParams::VM_PAPER_CUSTOM:
2174 if (!params.paperwidth.empty())
2175 ofs << ",paperwidth="
2176 << params.paperwidth;
2177 if (!params.paperheight.empty())
2178 ofs << ",paperheight="
2179 << params.paperheight;
2181 case BufferParams::VM_PAPER_USLETTER:
2182 ofs << ",letterpaper";
2184 case BufferParams::VM_PAPER_USLEGAL:
2185 ofs << ",legalpaper";
2187 case BufferParams::VM_PAPER_USEXECUTIVE:
2188 ofs << ",executivepaper";
2190 case BufferParams::VM_PAPER_A3:
2193 case BufferParams::VM_PAPER_A4:
2196 case BufferParams::VM_PAPER_A5:
2199 case BufferParams::VM_PAPER_B3:
2202 case BufferParams::VM_PAPER_B4:
2205 case BufferParams::VM_PAPER_B5:
2209 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2210 switch (lyxrc.default_papersize) {
2211 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2212 case BufferParams::PAPER_USLETTER:
2213 ofs << ",letterpaper";
2215 case BufferParams::PAPER_LEGALPAPER:
2216 ofs << ",legalpaper";
2218 case BufferParams::PAPER_EXECUTIVEPAPER:
2219 ofs << ",executivepaper";
2221 case BufferParams::PAPER_A3PAPER:
2224 case BufferParams::PAPER_A4PAPER:
2227 case BufferParams::PAPER_A5PAPER:
2230 case BufferParams::PAPER_B5PAPER:
2235 if (!params.topmargin.empty())
2236 ofs << ",tmargin=" << params.topmargin;
2237 if (!params.bottommargin.empty())
2238 ofs << ",bmargin=" << params.bottommargin;
2239 if (!params.leftmargin.empty())
2240 ofs << ",lmargin=" << params.leftmargin;
2241 if (!params.rightmargin.empty())
2242 ofs << ",rmargin=" << params.rightmargin;
2243 if (!params.headheight.empty())
2244 ofs << ",headheight=" << params.headheight;
2245 if (!params.headsep.empty())
2246 ofs << ",headsep=" << params.headsep;
2247 if (!params.footskip.empty())
2248 ofs << ",footskip=" << params.footskip;
2252 if (features.amsstyle
2253 && !tclass.provides(LyXTextClass::amsmath)) {
2254 ofs << "\\usepackage{amsmath}\n";
2258 if (tokenPos(tclass.opt_pagestyle(),
2259 '|', params.pagestyle) >= 0) {
2260 if (params.pagestyle == "fancy") {
2261 ofs << "\\usepackage{fancyhdr}\n";
2264 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2268 // We try to load babel late, in case it interferes
2269 // with other packages.
2271 string tmp = lyxrc.language_package;
2272 if (!lyxrc.language_global_options
2273 && tmp == "\\usepackage{babel}")
2274 tmp = string("\\usepackage[") +
2275 language_options.str().c_str() +
2281 if (params.secnumdepth != tclass.secnumdepth()) {
2282 ofs << "\\setcounter{secnumdepth}{"
2283 << params.secnumdepth
2287 if (params.tocdepth != tclass.tocdepth()) {
2288 ofs << "\\setcounter{tocdepth}{"
2294 if (params.paragraph_separation) {
2295 switch (params.defskip.kind()) {
2296 case VSpace::SMALLSKIP:
2297 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2299 case VSpace::MEDSKIP:
2300 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2302 case VSpace::BIGSKIP:
2303 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2305 case VSpace::LENGTH:
2306 ofs << "\\setlength\\parskip{"
2307 << params.defskip.length().asLatexString()
2310 default: // should never happen // Then delete it.
2311 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2316 ofs << "\\setlength\\parindent{0pt}\n";
2320 // Now insert the LyX specific LaTeX commands...
2322 // The optional packages;
2323 string preamble(features.getPackages());
2325 // this might be useful...
2326 preamble += "\n\\makeatletter\n";
2328 // Some macros LyX will need
2329 string tmppreamble(features.getMacros());
2331 if (!tmppreamble.empty()) {
2332 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2333 "LyX specific LaTeX commands.\n"
2334 + tmppreamble + '\n';
2337 // the text class specific preamble
2338 tmppreamble = features.getTClassPreamble();
2339 if (!tmppreamble.empty()) {
2340 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2341 "Textclass specific LaTeX commands.\n"
2342 + tmppreamble + '\n';
2345 /* the user-defined preamble */
2346 if (!params.preamble.empty()) {
2347 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2348 "User specified LaTeX commands.\n"
2349 + params.preamble + '\n';
2352 preamble += "\\makeatother\n";
2354 // Itemize bullet settings need to be last in case the user
2355 // defines their own bullets that use a package included
2356 // in the user-defined preamble -- ARRae
2357 // Actually it has to be done much later than that
2358 // since some packages like frenchb make modifications
2359 // at \begin{document} time -- JMarc
2361 for (int i = 0; i < 4; ++i) {
2362 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2363 if (bullets_def.empty())
2364 bullets_def="\\AtBeginDocument{\n";
2365 bullets_def += " \\renewcommand{\\labelitemi";
2367 // `i' is one less than the item to modify
2374 bullets_def += "ii";
2380 bullets_def += "}{" +
2381 params.user_defined_bullets[i].getText()
2386 if (!bullets_def.empty())
2387 preamble += bullets_def + "}\n\n";
2389 for (int j = countChar(preamble, '\n'); j-- ;) {
2396 ofs << "\\begin{document}\n";
2399 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2401 if (!lyxrc.language_auto_begin) {
2402 ofs << subst(lyxrc.language_command_begin, "$$lang",
2403 params.language->babel())
2408 latexParagraphs(ofs, paragraph, 0, texrow);
2410 // add this just in case after all the paragraphs
2414 if (!lyxrc.language_auto_end) {
2415 ofs << subst(lyxrc.language_command_end, "$$lang",
2416 params.language->babel())
2422 ofs << "\\end{document}\n";
2425 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2427 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2431 // Just to be sure. (Asger)
2434 // tex_code_break_column's value is used to decide
2435 // if we are in batchmode or not (within mathed_write()
2436 // in math_write.C) so we must set it to a non-zero
2437 // value when we leave otherwise we save incorrect .lyx files.
2438 tex_code_break_column = lyxrc.ascii_linelen;
2442 lyxerr << "File was not closed properly." << endl;
2445 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2450 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2452 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2453 Paragraph * endpar, TexRow & texrow) const
2455 bool was_title = false;
2456 bool already_title = false;
2459 while (par != endpar) {
2460 LyXLayout const & layout =
2461 textclasslist.Style(params.textclass,
2464 if (layout.intitle) {
2465 if (already_title) {
2466 lyxerr <<"Error in latexParagraphs: You"
2467 " should not mix title layouts"
2468 " with normal ones." << endl;
2471 } else if (was_title && !already_title) {
2472 ofs << "\\maketitle\n";
2474 already_title = true;
2478 if (layout.isEnvironment()) {
2479 par = par->TeXEnvironment(this, params, ofs, texrow);
2481 par = par->TeXOnePar(this, params, ofs, texrow, false);
2484 // It might be that we only have a title in this document
2485 if (was_title && !already_title) {
2486 ofs << "\\maketitle\n";
2492 bool Buffer::isLatex() const
2494 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2498 bool Buffer::isLinuxDoc() const
2500 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2504 bool Buffer::isLiterate() const
2506 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2510 bool Buffer::isDocBook() const
2512 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2516 bool Buffer::isSGML() const
2518 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2519 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2523 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2524 string const & latexname) const
2526 if (!latexname.empty() && latexname != "!-- --")
2527 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2528 //os << string(depth, ' ') << "<" << latexname << ">\n";
2532 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2533 string const & latexname) const
2535 if (!latexname.empty() && latexname != "!-- --")
2536 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2537 //os << string(depth, ' ') << "</" << latexname << ">\n";
2541 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2543 ofstream ofs(fname.c_str());
2546 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2550 niceFile = nice; // this will be used by included files.
2552 LyXTextClass const & tclass =
2553 textclasslist.TextClass(params.textclass);
2555 LaTeXFeatures features(params, tclass.numLayouts());
2560 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2563 string sgml_includedfiles=features.getIncludedFiles(fname);
2565 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2566 ofs << "<!doctype linuxdoc system>\n\n";
2568 ofs << "<!doctype linuxdoc system [ "
2569 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2572 if (params.options.empty())
2573 sgmlOpenTag(ofs, 0, top_element);
2575 string top = top_element;
2577 top += params.options;
2578 sgmlOpenTag(ofs, 0, top);
2582 ofs << "<!-- " << LYX_DOCVERSION
2583 << " created this file. For more info see http://www.lyx.org/"
2586 Paragraph::depth_type depth = 0; // paragraph depth
2587 Paragraph * par = paragraph;
2589 vector<string> environment_stack(5);
2592 LyXLayout const & style =
2593 textclasslist.Style(params.textclass,
2596 // treat <toc> as a special case for compatibility with old code
2597 if (par->getChar(0) == Paragraph::META_INSET) {
2598 Inset * inset = par->getInset(0);
2599 Inset::Code lyx_code = inset->lyxCode();
2600 if (lyx_code == Inset::TOC_CODE){
2601 string const temp = "toc";
2602 sgmlOpenTag(ofs, depth, temp);
2609 // environment tag closing
2610 for (; depth > par->params().depth(); --depth) {
2611 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2612 environment_stack[depth].erase();
2615 // write opening SGML tags
2616 switch (style.latextype) {
2617 case LATEX_PARAGRAPH:
2618 if (depth == par->params().depth()
2619 && !environment_stack[depth].empty()) {
2620 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2621 environment_stack[depth].erase();
2627 sgmlOpenTag(ofs, depth, style.latexname());
2632 linuxDocError(par, 0,
2633 _("Error : Wrong depth for"
2634 " LatexType Command.\n"));
2636 if (!environment_stack[depth].empty()){
2637 sgmlCloseTag(ofs, depth,
2638 environment_stack[depth]);
2642 environment_stack[depth].erase();
2643 sgmlOpenTag(ofs, depth, style.latexname());
2646 case LATEX_ENVIRONMENT:
2647 case LATEX_ITEM_ENVIRONMENT:
2648 if (depth == par->params().depth()
2649 && environment_stack[depth] != style.latexname()) {
2650 sgmlCloseTag(ofs, depth,
2651 environment_stack[depth]);
2652 environment_stack[depth].erase();
2654 if (depth < par->params().depth()) {
2655 depth = par->params().depth();
2656 environment_stack[depth].erase();
2658 if (environment_stack[depth] != style.latexname()) {
2660 sgmlOpenTag(ofs, depth, "p");
2662 sgmlOpenTag(ofs, depth, style.latexname());
2664 if (environment_stack.size() == depth + 1)
2665 environment_stack.push_back("!-- --");
2666 environment_stack[depth] = style.latexname();
2669 if (style.latexparam() == "CDATA")
2672 if (style.latextype == LATEX_ENVIRONMENT) break;
2674 if (style.labeltype == LABEL_MANUAL)
2679 sgmlOpenTag(ofs, depth + 1, item_name);
2682 sgmlOpenTag(ofs, depth, style.latexname());
2686 simpleLinuxDocOnePar(ofs, par, depth);
2691 // write closing SGML tags
2692 switch (style.latextype) {
2695 case LATEX_ENVIRONMENT:
2696 case LATEX_ITEM_ENVIRONMENT:
2697 if (style.latexparam() == "CDATA")
2701 sgmlCloseTag(ofs, depth, style.latexname());
2707 for (int i=depth; i >= 0; --i)
2708 sgmlCloseTag(ofs, depth, environment_stack[i]);
2712 sgmlCloseTag(ofs, 0, top_element);
2716 // How to check for successful close
2720 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2721 Paragraph::depth_type depth, int desc_on,
2724 Paragraph * tpar = par;
2726 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2728 tpar = tpar->next();
2731 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2732 "Caption").second) {
2733 sgmlOpenTag(os, depth + 1, inner_tag);
2735 simpleDocBookOnePar(os, extra_par, tpar,
2736 desc_on, depth + 2);
2737 sgmlCloseTag(os, depth+1, inner_tag);
2738 if (!extra_par.empty())
2744 // checks, if newcol chars should be put into this line
2745 // writes newline, if necessary.
2748 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2749 string::size_type newcol)
2752 if (colcount > lyxrc.ascii_linelen) {
2754 colcount = newcol; // assume write after this call
2769 string tag_name(PAR_TAG const & pt) {
2771 case NONE: return "!-- --";
2772 case TT: return "tt";
2773 case SF: return "sf";
2774 case BF: return "bf";
2775 case IT: return "it";
2776 case SL: return "sl";
2777 case EM: return "em";
2784 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2786 p1 = static_cast<PAR_TAG>(p1 | p2);
2791 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2793 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2801 // Handle internal paragraph parsing -- layout already processed.
2802 void Buffer::simpleLinuxDocOnePar(ostream & os,
2804 Paragraph::depth_type /*depth*/)
2806 LyXLayout const & style = textclasslist.Style(params.textclass,
2808 string::size_type char_line_count = 5; // Heuristic choice ;-)
2810 // gets paragraph main font
2813 if (style.labeltype == LABEL_MANUAL) {
2814 font_old = style.labelfont;
2817 font_old = style.font;
2821 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2822 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2823 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2826 stack < PAR_TAG > tag_state;
2827 // parsing main loop
2828 for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2830 PAR_TAG tag_close = NONE;
2831 list < PAR_TAG > tag_open;
2833 LyXFont const font = par->getFont(params, i);
2835 if (font_old.family() != font.family()) {
2836 switch (family_type) {
2837 case LyXFont::SANS_FAMILY:
2840 case LyXFont::TYPEWRITER_FAMILY:
2847 family_type = font.family();
2849 switch (family_type) {
2850 case LyXFont::SANS_FAMILY:
2851 tag_open.push_back(SF);
2853 case LyXFont::TYPEWRITER_FAMILY:
2854 tag_open.push_back(TT);
2861 if (font_old.series() != font.series()) {
2862 switch (series_type) {
2863 case LyXFont::BOLD_SERIES:
2870 series_type = font.series();
2872 switch (series_type) {
2873 case LyXFont::BOLD_SERIES:
2874 tag_open.push_back(BF);
2882 if (font_old.shape() != font.shape()) {
2883 switch (shape_type) {
2884 case LyXFont::ITALIC_SHAPE:
2887 case LyXFont::SLANTED_SHAPE:
2894 shape_type = font.shape();
2896 switch (shape_type) {
2897 case LyXFont::ITALIC_SHAPE:
2898 tag_open.push_back(IT);
2900 case LyXFont::SLANTED_SHAPE:
2901 tag_open.push_back(SL);
2908 if (font_old.emph() != font.emph()) {
2909 if (font.emph() == LyXFont::ON) {
2910 tag_open.push_back(EM);
2919 list < PAR_TAG > temp;
2920 while(!tag_state.empty() && tag_close ) {
2921 PAR_TAG k = tag_state.top();
2923 os << "</" << tag_name(k) << ">";
2930 for(list< PAR_TAG >::const_iterator j = temp.begin();
2931 j != temp.end(); ++j) {
2933 os << "<" << tag_name(*j) << ">";
2936 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2937 j != tag_open.end(); ++j) {
2939 os << "<" << tag_name(*j) << ">";
2942 char c = par->getChar(i);
2944 if (c == Paragraph::META_INSET) {
2945 Inset * inset = par->getInset(i);
2946 inset->linuxdoc(this, os);
2953 font.latex() == LyXFont::ON ||
2955 style.latexparam() == "CDATA") {
2956 // "TeX"-Mode on == > SGML-Mode on.
2962 if (par->linuxDocConvertChar(c, sgml_string)
2963 && !style.free_spacing) {
2964 // in freespacing mode, spaces are
2965 // non-breaking characters
2966 if (desc_on) {// if char is ' ' then...
2969 linux_doc_line_break(os, char_line_count, 6);
2973 linux_doc_line_break(os, char_line_count, 1);
2978 char_line_count += sgml_string.length();
2984 while (!tag_state.empty()) {
2985 os << "</" << tag_name(tag_state.top()) << ">";
2989 // resets description flag correctly
2991 // <tag> not closed...
2992 linux_doc_line_break(os, char_line_count, 6);
2998 // Print an error message.
2999 void Buffer::linuxDocError(Paragraph * par, int pos,
3000 string const & message)
3002 // insert an error marker in text
3003 InsetError * new_inset = new InsetError(message);
3004 par->insertInset(pos, new_inset);
3008 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3010 ofstream ofs(fname.c_str());
3012 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3016 Paragraph * par = paragraph;
3018 niceFile = nice; // this will be used by Insetincludes.
3020 LyXTextClass const & tclass =
3021 textclasslist.TextClass(params.textclass);
3023 LaTeXFeatures features(params, tclass.numLayouts());
3028 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3031 string sgml_includedfiles = features.getIncludedFiles(fname);
3033 ofs << "<!doctype " << top_element
3034 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3036 if (params.preamble.empty() && sgml_includedfiles.empty())
3039 ofs << "\n [ " << params.preamble
3040 << sgml_includedfiles << " \n]>\n\n";
3043 string top = top_element;
3045 top += params.language->code();
3048 if (!params.options.empty()) {
3050 top += params.options;
3052 sgmlOpenTag(ofs, 0, top);
3054 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
3055 << "\n See http://www.lyx.org/ for more information -->\n";
3057 vector<string> environment_stack(10);
3058 vector<string> environment_inner(10);
3059 vector<string> command_stack(10);
3061 bool command_flag = false;
3062 Paragraph::depth_type command_depth = 0;
3063 Paragraph::depth_type command_base = 0;
3064 Paragraph::depth_type cmd_depth = 0;
3065 Paragraph::depth_type depth = 0; // paragraph depth
3068 string command_name;
3074 int desc_on = 0; // description mode
3076 LyXLayout const & style =
3077 textclasslist.Style(params.textclass,
3080 // environment tag closing
3081 for (; depth > par->params().depth(); --depth) {
3082 if (environment_inner[depth] != "!-- --") {
3083 item_name = "listitem";
3084 sgmlCloseTag(ofs, command_depth + depth,
3086 if (environment_inner[depth] == "varlistentry")
3087 sgmlCloseTag(ofs, depth+command_depth,
3088 environment_inner[depth]);
3090 sgmlCloseTag(ofs, depth + command_depth,
3091 environment_stack[depth]);
3092 environment_stack[depth].erase();
3093 environment_inner[depth].erase();
3096 if (depth == par->params().depth()
3097 && environment_stack[depth] != style.latexname()
3098 && !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")
3105 depth + command_depth,
3106 environment_inner[depth]);
3109 sgmlCloseTag(ofs, depth + command_depth,
3110 environment_stack[depth]);
3112 environment_stack[depth].erase();
3113 environment_inner[depth].erase();
3116 // Write opening SGML tags.
3117 switch (style.latextype) {
3118 case LATEX_PARAGRAPH:
3119 sgmlOpenTag(ofs, depth + command_depth,
3125 linuxDocError(par, 0,
3126 _("Error : Wrong depth for "
3127 "LatexType Command.\n"));
3129 command_name = style.latexname();
3131 sgmlparam = style.latexparam();
3132 c_params = split(sgmlparam, c_depth,'|');
3134 cmd_depth = lyx::atoi(c_depth);
3137 if (cmd_depth < command_base) {
3138 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3139 sgmlCloseTag(ofs, j, command_stack[j]);
3140 command_depth = command_base = cmd_depth;
3141 } else if (cmd_depth <= command_depth) {
3142 for (int j = command_depth; j >= int(cmd_depth); --j)
3143 sgmlCloseTag(ofs, j, command_stack[j]);
3144 command_depth = cmd_depth;
3146 command_depth = cmd_depth;
3148 command_depth = command_base = cmd_depth;
3149 command_flag = true;
3151 if (command_stack.size() == command_depth + 1)
3152 command_stack.push_back(string());
3153 command_stack[command_depth] = command_name;
3155 // treat label as a special case for
3156 // more WYSIWYM handling.
3157 if (par->getChar(0) == Paragraph::META_INSET) {
3158 Inset * inset = par->getInset(0);
3159 Inset::Code lyx_code = inset->lyxCode();
3160 if (lyx_code == Inset::LABEL_CODE){
3161 command_name += " id=\"";
3162 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3163 command_name += "\"";
3168 sgmlOpenTag(ofs, depth + command_depth, command_name);
3169 if (c_params.empty())
3170 item_name = "title";
3172 item_name = c_params;
3173 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3176 case LATEX_ENVIRONMENT:
3177 case LATEX_ITEM_ENVIRONMENT:
3178 if (depth < par->params().depth()) {
3179 depth = par->params().depth();
3180 environment_stack[depth].erase();
3183 if (environment_stack[depth] != style.latexname()) {
3184 if(environment_stack.size() == depth + 1) {
3185 environment_stack.push_back("!-- --");
3186 environment_inner.push_back("!-- --");
3188 environment_stack[depth] = style.latexname();
3189 environment_inner[depth] = "!-- --";
3190 sgmlOpenTag(ofs, depth + command_depth,
3191 environment_stack[depth]);
3193 if (environment_inner[depth] != "!-- --") {
3194 item_name= "listitem";
3196 command_depth + depth,
3198 if (environment_inner[depth] == "varlistentry")
3200 depth + command_depth,
3201 environment_inner[depth]);
3205 if (style.latextype == LATEX_ENVIRONMENT) {
3206 if (!style.latexparam().empty()) {
3207 if(style.latexparam() == "CDATA")
3210 sgmlOpenTag(ofs, depth + command_depth,
3211 style.latexparam());
3216 desc_on = (style.labeltype == LABEL_MANUAL);
3219 environment_inner[depth]= "varlistentry";
3221 environment_inner[depth]= "listitem";
3223 sgmlOpenTag(ofs, depth + 1 + command_depth,
3224 environment_inner[depth]);
3228 sgmlOpenTag(ofs, depth + 1 + command_depth,
3232 sgmlOpenTag(ofs, depth + 1 + command_depth,
3237 sgmlOpenTag(ofs, depth + command_depth,
3243 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3244 depth + 1 + command_depth);
3248 // write closing SGML tags
3249 switch (style.latextype) {
3251 if (c_params.empty())
3255 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3257 case LATEX_ENVIRONMENT:
3258 if (!style.latexparam().empty()) {
3259 if(style.latexparam() == "CDATA")
3262 sgmlCloseTag(ofs, depth + command_depth,
3263 style.latexparam());
3266 case LATEX_ITEM_ENVIRONMENT:
3267 if (desc_on == 1) break;
3269 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3271 case LATEX_PARAGRAPH:
3272 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3275 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3281 for (int d = depth; d >= 0; --d) {
3282 if (!environment_stack[depth].empty()) {
3283 if (environment_inner[depth] != "!-- --") {
3284 item_name = "listitem";
3285 sgmlCloseTag(ofs, command_depth + depth,
3287 if (environment_inner[depth] == "varlistentry")
3288 sgmlCloseTag(ofs, depth + command_depth,
3289 environment_inner[depth]);
3292 sgmlCloseTag(ofs, depth + command_depth,
3293 environment_stack[depth]);
3297 for (int j = command_depth; j >= 0 ; --j)
3298 if (!command_stack[j].empty())
3299 sgmlCloseTag(ofs, j, command_stack[j]);
3302 sgmlCloseTag(ofs, 0, top_element);
3305 // How to check for successful close
3309 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3310 Paragraph * par, int & desc_on,
3311 Paragraph::depth_type depth) const
3313 bool emph_flag = false;
3315 LyXLayout const & style = textclasslist.Style(params.textclass,
3318 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3320 int char_line_count = depth;
3321 //if (!style.free_spacing)
3322 // os << string(depth,' ');
3324 // parsing main loop
3325 for (Paragraph::size_type i = 0;
3326 i < par->size(); ++i) {
3327 LyXFont font = par->getFont(params, i);
3329 // handle <emphasis> tag
3330 if (font_old.emph() != font.emph()) {
3331 if (font.emph() == LyXFont::ON) {
3335 os << "</emphasis>";
3340 char c = par->getChar(i);
3342 if (c == Paragraph::META_INSET) {
3343 Inset * inset = par->getInset(i);
3345 inset->docBook(this, ost);
3346 string tmp_out = ost.str().c_str();
3349 // This code needs some explanation:
3350 // Two insets are treated specially
3351 // label if it is the first element in a command paragraph
3353 // graphics inside tables or figure floats can't go on
3354 // title (the equivalente in latex for this case is caption
3355 // and title should come first
3358 if (desc_on!= 3 || i!= 0) {
3359 if (!tmp_out.empty() && tmp_out[0] == '@') {
3361 extra += frontStrip(tmp_out, '@');
3363 os << frontStrip(tmp_out, '@');
3369 } else if (font.latex() == LyXFont::ON) {
3370 // "TeX"-Mode on ==> SGML-Mode on.
3377 if (par->linuxDocConvertChar(c, sgml_string)
3378 && !style.free_spacing) { // in freespacing
3380 // non-breaking characters
3384 os << "\n</term><listitem><para>";
3397 os << "</emphasis>";
3400 // resets description flag correctly
3402 // <term> not closed...
3405 if(style.free_spacing) os << '\n';
3409 // This should be enabled when the Chktex class is implemented. (Asger)
3410 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3411 // Other flags: -wall -v0 -x
3412 int Buffer::runChktex()
3414 if (!users->text) return 0;
3416 users->owner()->prohibitInput();
3418 // get LaTeX-Filename
3419 string const name = getLatexName();
3420 string path = OnlyPath(filename);
3422 string const org_path = path;
3423 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3427 Path p(path); // path to LaTeX file
3428 users->owner()->message(_("Running chktex..."));
3430 // Remove all error insets
3431 bool const removedErrorInsets = users->removeAutoInsets();
3433 // Generate the LaTeX file if neccessary
3434 makeLaTeXFile(name, org_path, false);
3437 Chktex chktex(lyxrc.chktex_command, name, filepath);
3438 int res = chktex.run(terr); // run chktex
3441 WriteAlert(_("chktex did not work!"),
3442 _("Could not run with file:"), name);
3443 } else if (res > 0) {
3444 // Insert all errors as errors boxes
3445 users->insertErrors(terr);
3448 // if we removed error insets before we ran chktex or if we inserted
3449 // error insets after we ran chktex, this must be run:
3450 if (removedErrorInsets || res){
3452 users->fitCursor(users->text);
3454 users->owner()->allowInput();
3460 void Buffer::validate(LaTeXFeatures & features) const
3462 Paragraph * par = paragraph;
3463 LyXTextClass const & tclass =
3464 textclasslist.TextClass(params.textclass);
3466 // AMS Style is at document level
3467 features.amsstyle = (params.use_amsmath ||
3468 tclass.provides(LyXTextClass::amsmath));
3471 // We don't use "lyxerr.debug" because of speed. (Asger)
3472 if (lyxerr.debugging(Debug::LATEX))
3473 lyxerr << "Paragraph: " << par << endl;
3475 // Now just follow the list of paragraphs and run
3476 // validate on each of them.
3477 par->validate(features);
3479 // and then the next paragraph
3483 // the bullet shapes are buffer level not paragraph level
3484 // so they are tested here
3485 for (int i = 0; i < 4; ++i) {
3486 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3487 int const font = params.user_defined_bullets[i].getFont();
3489 int const c = params
3490 .user_defined_bullets[i]
3497 features.latexsym = true;
3499 } else if (font == 1) {
3500 features.amssymb = true;
3501 } else if ((font >= 2 && font <= 5)) {
3502 features.pifont = true;
3507 if (lyxerr.debugging(Debug::LATEX)) {
3508 features.showStruct();
3513 void Buffer::setPaperStuff()
3515 params.papersize = BufferParams::PAPER_DEFAULT;
3516 char const c1 = params.paperpackage;
3517 if (c1 == BufferParams::PACKAGE_NONE) {
3518 char const c2 = params.papersize2;
3519 if (c2 == BufferParams::VM_PAPER_USLETTER)
3520 params.papersize = BufferParams::PAPER_USLETTER;
3521 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3522 params.papersize = BufferParams::PAPER_LEGALPAPER;
3523 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3524 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3525 else if (c2 == BufferParams::VM_PAPER_A3)
3526 params.papersize = BufferParams::PAPER_A3PAPER;
3527 else if (c2 == BufferParams::VM_PAPER_A4)
3528 params.papersize = BufferParams::PAPER_A4PAPER;
3529 else if (c2 == BufferParams::VM_PAPER_A5)
3530 params.papersize = BufferParams::PAPER_A5PAPER;
3531 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3532 (c2 == BufferParams::VM_PAPER_B5))
3533 params.papersize = BufferParams::PAPER_B5PAPER;
3534 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3535 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3536 params.papersize = BufferParams::PAPER_A4PAPER;
3540 // This function should be in Buffer because it's a buffer's property (ale)
3541 string const Buffer::getIncludeonlyList(char delim)
3544 for (inset_iterator it = inset_iterator_begin();
3545 it != inset_iterator_end(); ++it) {
3546 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3547 InsetInclude * insetinc =
3548 static_cast<InsetInclude *>(*it);
3549 if (insetinc->isIncludeOnly()) {
3552 lst += insetinc->getRelFileBaseName();
3556 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3561 vector<string> const Buffer::getLabelList()
3563 /// if this is a child document and the parent is already loaded
3564 /// Use the parent's list instead [ale990407]
3565 if (!params.parentname.empty()
3566 && bufferlist.exists(params.parentname)) {
3567 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3569 return tmp->getLabelList();
3572 vector<string> label_list;
3573 for (inset_iterator it = inset_iterator_begin();
3574 it != inset_iterator_end(); ++it) {
3575 vector<string> const l = (*it)->getLabelList();
3576 label_list.insert(label_list.end(), l.begin(), l.end());
3582 Buffer::Lists const Buffer::getLists() const
3585 Paragraph * par = paragraph;
3587 LyXTextClassList::size_type cap;
3588 boost::tie(found, cap) = textclasslist
3589 .NumberOfLayout(params.textclass, "Caption");
3592 char const labeltype =
3593 textclasslist.Style(params.textclass,
3594 par->getLayout()).labeltype;
3596 if (labeltype >= LABEL_COUNTER_CHAPTER
3597 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3598 // insert this into the table of contents
3599 SingleList & item = l["TOC"];
3602 textclasslist.TextClass(params.textclass).maxcounter());
3603 item.push_back(TocItem(par, depth, par->asString(this, true)));
3605 // For each paragrph, traverse its insets and look for
3609 Paragraph::inset_iterator it =
3610 par->inset_iterator_begin();
3611 Paragraph::inset_iterator end =
3612 par->inset_iterator_end();
3614 for (; it != end; ++it) {
3615 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3617 static_cast<InsetFloat*>(*it);
3619 string const type = il->type();
3621 // Now find the caption in the float...
3622 // We now tranverse the paragraphs of
3624 Paragraph * tmp = il->inset.paragraph();
3626 if (tmp->layout == cap) {
3627 SingleList & item = l[type];
3629 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3630 item.push_back(TocItem(tmp, 0 , str));
3637 lyxerr << "caption not found" << endl;
3646 // This is also a buffer property (ale)
3647 vector<pair<string, string> > const Buffer::getBibkeyList()
3649 /// if this is a child document and the parent is already loaded
3650 /// Use the parent's list instead [ale990412]
3651 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3652 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3654 return tmp->getBibkeyList();
3657 vector<pair<string, string> > keys;
3658 Paragraph * par = paragraph;
3661 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3662 par->asString(this, false)));
3666 // Might be either using bibtex or a child has bibliography
3668 for (inset_iterator it = inset_iterator_begin();
3669 it != inset_iterator_end(); ++it) {
3670 // Search for Bibtex or Include inset
3671 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3672 vector<pair<string,string> > tmp =
3673 static_cast<InsetBibtex*>(*it)->getKeys(this);
3674 keys.insert(keys.end(), tmp.begin(), tmp.end());
3675 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3676 vector<pair<string,string> > const tmp =
3677 static_cast<InsetInclude*>(*it)->getKeys();
3678 keys.insert(keys.end(), tmp.begin(), tmp.end());
3687 bool Buffer::isDepClean(string const & name) const
3689 DEPCLEAN * item = dep_clean;
3690 while (item && item->master != name)
3692 if (!item) return true;
3697 void Buffer::markDepClean(string const & name)
3700 dep_clean = new DEPCLEAN;
3701 dep_clean->clean = true;
3702 dep_clean->master = name;
3703 dep_clean->next = 0;
3705 DEPCLEAN * item = dep_clean;
3706 while (item && item->master != name)
3711 item = new DEPCLEAN;
3713 item->master = name;
3720 bool Buffer::dispatch(string const & command)
3722 // Split command string into command and argument
3724 string line = frontStrip(command);
3725 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3727 return dispatch(lyxaction.LookupFunc(cmd), arg);
3731 bool Buffer::dispatch(int action, string const & argument)
3733 bool dispatched = true;
3736 Exporter::Export(this, argument, false);
3746 void Buffer::resizeInsets(BufferView * bv)
3748 /// then remove all LyXText in text-insets
3749 Paragraph * par = paragraph;
3750 for (; par; par = par->next()) {
3751 par->resizeInsetsLyXText(bv);
3756 void Buffer::redraw()
3759 users->fitCursor(users->text);
3763 void Buffer::changeLanguage(Language const * from, Language const * to)
3766 Paragraph * par = paragraph;
3768 par->changeLanguage(params, from, to);
3774 bool Buffer::isMultiLingual()
3776 Paragraph * par = paragraph;
3778 if (par->isMultiLingual(params))
3786 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3787 Paragraph::size_type pos)
3790 it = par->InsetIterator(pos);
3791 if (it == par->inset_iterator_end()) {
3798 void Buffer::inset_iterator::setParagraph()
3801 it = par->inset_iterator_begin();
3802 if (it != par->inset_iterator_end())
3807 // We maintain an invariant that whenever par = 0 then it = 0
3811 Inset * Buffer::getInsetFromID(int id_arg) const
3813 for (inset_iterator it = inset_const_iterator_begin();
3814 it != inset_const_iterator_end(); ++it)
3816 if ((*it)->id() == id_arg)
3818 Inset * in = (*it)->getInsetFromID(id_arg);
3826 Paragraph * Buffer::getParFromID(int id) const
3828 if (id < 0) return 0;
3829 Paragraph * par = paragraph;
3831 if (par->id() == id) {
3834 Paragraph * tmp = par->getParFromID(id);