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 "frontends/Dialogs.h"
101 #include "frontends/Alert.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"
108 #include "iterators.h"
118 using std::make_pair;
128 // all these externs should eventually be removed.
129 extern BufferList bufferlist;
131 extern LyXAction lyxaction;
135 const int LYX_FORMAT = 220;
139 extern int tex_code_break_column;
142 Buffer::Buffer(string const & file, bool ronly)
144 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
146 filepath = OnlyPath(file);
155 if (read_only || (lyxrc.use_tempdir)) {
156 tmppath = CreateBufferTmpDir();
157 } else tmppath.erase();
163 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
164 // here the buffer should take care that it is
165 // saved properly, before it goes into the void.
167 // make sure that views using this buffer
172 if (!tmppath.empty()) {
173 DestroyBufferTmpDir(tmppath);
176 Paragraph * par = paragraph;
179 tmppar = par->next();
187 string const Buffer::getLatexName(bool no_path) const
189 string name = ChangeExtension(MakeLatexName(filename), ".tex");
191 return OnlyFilename(name);
197 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
199 string const filename = getLatexName(false);
201 if (filename.empty())
202 return make_pair(Buffer::latexlog, string());
204 string path = OnlyPath(filename);
206 if (lyxrc.use_tempdir || !IsDirWriteable(path))
209 string const fname = AddName(path,
210 OnlyFilename(ChangeExtension(filename,
213 AddName(path, OnlyFilename(
214 ChangeExtension(filename,
215 formats.extension("literate") + ".out")));
217 // If no Latex log or Build log is newer, show Build log
219 FileInfo const f_fi(fname);
220 FileInfo const b_fi(bname);
223 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
224 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
225 return make_pair(Buffer::buildlog, bname);
227 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
228 return make_pair(Buffer::latexlog, fname);
232 void Buffer::setReadonly(bool flag)
234 if (read_only != flag) {
237 users->owner()->getDialogs()->updateBufferDependent(false);
242 /// Update window titles of all users
243 // Should work on a list
244 void Buffer::updateTitles() const
246 if (users) users->owner()->updateWindowTitle();
250 /// Reset autosave timer of all users
251 // Should work on a list
252 void Buffer::resetAutosaveTimers() const
254 if (users) users->owner()->resetAutosaveTimer();
258 void Buffer::setFileName(string const & newfile)
260 filename = MakeAbsPath(newfile);
261 filepath = OnlyPath(filename);
262 setReadonly(IsFileWriteable(filename) == 0);
267 // We'll remove this later. (Lgb)
270 string last_inset_read;
272 #ifndef NO_COMPABILITY
275 ErtComp() : active(false), in_tabular(false) {
282 std::stack<ErtComp> ert_stack;
286 #warning And _why_ is this here? (Lgb)
293 // candidate for move to BufferView
294 // (at least some parts in the beginning of the func)
297 // changed to be public and have one parameter
298 // if par = 0 normal behavior
299 // else insert behavior
300 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
301 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
305 #ifndef NO_COMPABILITY
306 ert_comp.contents.erase();
307 ert_comp.active = false;
308 ert_comp.in_tabular = false;
311 Paragraph::depth_type depth = 0;
312 bool the_end_read = false;
314 Paragraph * first_par = 0;
315 LyXFont font(LyXFont::ALL_INHERIT, params.language);
316 if (file_format < 216 && params.language->lang() == "hebrew")
317 font.setLanguage(default_language);
322 // We are inserting into an existing document
323 users->text->breakParagraph(users);
324 first_par = users->text->firstParagraph();
327 // We don't want to adopt the parameters from the
328 // document we insert, so we skip until the text begins:
331 string const pretoken = lex.getString();
332 if (pretoken == "\\layout") {
333 lex.pushToken(pretoken);
341 string const token = lex.getString();
343 if (token.empty()) continue;
345 lyxerr[Debug::PARSER] << "Handling token: `"
346 << token << "'" << endl;
349 parseSingleLyXformat2Token(lex, par, first_par,
357 paragraph = first_par;
359 if (unknown_layouts > 0) {
360 string s = _("Couldn't set the layout for ");
361 if (unknown_layouts == 1) {
362 s += _("one paragraph");
364 s += tostr(unknown_layouts);
365 s += _(" paragraphs");
367 Alert::alert(_("Textclass Loading Error!"), s,
368 _("When reading " + fileName()));
371 if (unknown_tokens > 0) {
372 string s = _("Encountered ");
373 if (unknown_tokens == 1) {
374 s += _("one unknown token");
376 s += tostr(unknown_tokens);
377 s += _(" unknown tokens");
379 Alert::alert(_("Textclass Loading Error!"), s,
380 _("When reading " + fileName()));
387 #ifndef NO_COMPABILITY
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;
406 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
407 Paragraph *& first_par,
408 string const & token, int & pos,
409 Paragraph::depth_type & depth,
413 bool the_end_read = false;
414 #ifndef NO_COMPABILITY
415 #ifndef NO_PEXTRA_REALLY
416 // This is super temporary but is needed to get the compability
417 // mode for minipages work correctly together with new tabulars.
418 static int call_depth;
420 bool checkminipage = false;
421 static Paragraph * minipar;
422 static Paragraph * parBeforeMinipage;
425 if (token[0] != '\\') {
426 #ifndef NO_COMPABILITY
427 if (ert_comp.active) {
428 ert_comp.contents += token;
431 for (string::const_iterator cit = token.begin();
432 cit != token.end(); ++cit) {
433 par->insertChar(pos, (*cit), font);
436 #ifndef NO_COMPABILITY
439 } else if (token == "\\i") {
440 Inset * inset = new InsetLatexAccent;
441 inset->read(this, lex);
442 par->insertInset(pos, inset, font);
444 } else if (token == "\\layout") {
445 #ifndef NO_COMPABILITY
446 ert_comp.in_tabular = false;
448 insertErtContents(par, pos, font);
451 string const layoutname = lex.getString();
452 pair<bool, LyXTextClass::LayoutList::size_type> pp
453 = textclasslist.NumberOfLayout(params.textclass,
456 #ifndef NO_COMPABILITY
457 if (compare_no_case(layoutname, "latex") == 0) {
458 ert_comp.active = true;
462 // The is the compability reading of layout caption.
463 // It can be removed in LyX version 1.3.0. (Lgb)
464 if (compare_no_case(layoutname, "caption") == 0) {
465 // We expect that the par we are now working on is
466 // really inside a InsetText inside a InsetFloat.
467 // We also know that captions can only be
468 // one paragraph. (Lgb)
470 // We should now read until the next "\layout"
472 // This is probably not good enough, what if the
473 // caption is the last par in the document (Lgb)
474 istream & ist = lex.getStream();
480 if (prefixIs(line, "\\layout")) {
484 if (prefixIs(line, "\\begin_inset"))
486 if (prefixIs(line, "\\end_inset")) {
497 // Now we should have the whole layout in ss
498 // we should now be able to give this to the
500 ss << "\\end_inset\n";
502 // This seems like a bug in stringstream.
503 // We really should be able to use ss
505 istringstream is(ss.str());
507 tmplex.setStream(is);
508 Inset * inset = new InsetCaption;
509 inset->Read(this, tmplex);
510 par->InsertInset(pos, inset, font);
517 par = new Paragraph(par);
521 par->layout = pp.second;
522 #ifndef NO_COMPABILITY
523 } else if (ert_comp.active) {
528 // use default layout "Standard" (0)
531 string const s = _("Layout had to be changed from\n")
532 + layoutname + _(" to ")
533 + textclasslist.NameOfLayout(params.textclass, par->layout);
534 InsetError * new_inset = new InsetError(s);
535 par->insertInset(0, new_inset);
536 par->setFont(0, LyXFont(LyXFont::ALL_INHERIT,
539 // Test whether the layout is obsolete.
540 LyXLayout const & layout =
541 textclasslist.Style(params.textclass,
543 if (!layout.obsoleted_by().empty())
544 par->layout = textclasslist
545 .NumberOfLayout(params.textclass,
546 layout.obsoleted_by())
548 par->params().depth(depth);
549 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
550 if (file_format < 216
551 && params.language->lang() == "hebrew")
552 font.setLanguage(default_language);
557 #ifndef NO_COMPABILITY
558 } else if (token == "\\begin_float") {
559 insertErtContents(par, pos, font);
560 //insertErtContents(par, pos, font, false);
561 //ert_stack.push(ert_comp);
562 //ert_comp = ErtComp();
564 // This is the compability reader. It can be removed in
565 // LyX version 1.3.0. (Lgb)
567 string const tmptok = lex.getString();
568 //lyxerr << "old float: " << tmptok << endl;
571 stringstream old_float;
573 if (tmptok == "footnote") {
574 inset = new InsetFoot;
575 old_float << "collapsed true\n";
576 } else if (tmptok == "margin") {
577 inset = new InsetMarginal;
578 old_float << "collapsed true\n";
579 } else if (tmptok == "fig") {
580 inset = new InsetFloat("figure");
581 old_float << "placement htbp\n"
583 << "collapsed false\n";
584 } else if (tmptok == "tab") {
585 inset = new InsetFloat("table");
586 old_float << "placement htbp\n"
588 << "collapsed false\n";
589 } else if (tmptok == "alg") {
590 inset = new InsetFloat("algorithm");
591 old_float << "placement htbp\n"
593 << "collapsed false\n";
594 } else if (tmptok == "wide-fig") {
595 inset = new InsetFloat("figure");
596 //InsetFloat * tmp = new InsetFloat("figure");
599 old_float << "placement htbp\n"
601 << "collapsed false\n";
602 } else if (tmptok == "wide-tab") {
603 inset = new InsetFloat("table");
604 //InsetFloat * tmp = new InsetFloat("table");
607 old_float << "placement htbp\n"
609 << "collapsed false\n";
613 #ifndef NO_PEXTRA_REALLY
616 return false; // no end read yet
619 // Here we need to check for \end_deeper and handle that
620 // before we do the footnote parsing.
621 // This _is_ a hack! (Lgb)
624 string const tmp = lex.getString();
625 if (tmp == "\\end_deeper") {
626 //lyxerr << "\\end_deeper caught!" << endl;
628 lex.printError("\\end_deeper: "
629 "depth is already null");
634 old_float << tmp << ' ';
639 old_float << lex.getLongString("\\end_float")
640 << "\n\\end_inset\n";
641 //lyxerr << "Float Body:\n" << old_float.str() << endl;
642 // That this does not work seems like a bug
643 // in stringstream. (Lgb)
644 istringstream istr(old_float.str());
646 nylex.setStream(istr);
647 inset->read(this, nylex);
648 par->insertInset(pos, inset, font);
650 insertErtContents(par, pos, font);
652 } else if (token == "\\begin_deeper") {
654 } else if (token == "\\end_deeper") {
656 lex.printError("\\end_deeper: "
657 "depth is already null");
661 } else if (token == "\\begin_preamble") {
662 params.readPreamble(lex);
663 } else if (token == "\\textclass") {
665 pair<bool, LyXTextClassList::size_type> pp =
666 textclasslist.NumberOfClass(lex.getString());
668 params.textclass = pp.second;
670 Alert::alert(string(_("Textclass error")),
671 string(_("The document uses an unknown textclass \"")) +
672 lex.getString() + string("\"."),
673 string(_("LyX will not be able to produce output correctly.")));
674 params.textclass = 0;
676 if (!textclasslist.Load(params.textclass)) {
677 // if the textclass wasn't loaded properly
678 // we need to either substitute another
679 // or stop loading the file.
680 // I can substitute but I don't see how I can
681 // stop loading... ideas?? ARRae980418
682 Alert::alert(_("Textclass Loading Error!"),
683 string(_("Can't load textclass ")) +
684 textclasslist.NameOfClass(params.textclass),
685 _("-- substituting default"));
686 params.textclass = 0;
688 } else if (token == "\\options") {
690 params.options = lex.getString();
691 } else if (token == "\\language") {
692 params.readLanguage(lex);
693 } else if (token == "\\fontencoding") {
695 } else if (token == "\\inputencoding") {
697 params.inputenc = lex.getString();
698 } else if (token == "\\graphics") {
699 params.readGraphicsDriver(lex);
700 } else if (token == "\\fontscheme") {
702 params.fonts = lex.getString();
703 } else if (token == "\\noindent") {
704 par->params().noindent(true);
705 } else if (token == "\\fill_top") {
706 par->params().spaceTop(VSpace(VSpace::VFILL));
707 } else if (token == "\\fill_bottom") {
708 par->params().spaceBottom(VSpace(VSpace::VFILL));
709 } else if (token == "\\line_top") {
710 par->params().lineTop(true);
711 } else if (token == "\\line_bottom") {
712 par->params().lineBottom(true);
713 } else if (token == "\\pagebreak_top") {
714 par->params().pagebreakTop(true);
715 } else if (token == "\\pagebreak_bottom") {
716 par->params().pagebreakBottom(true);
717 } else if (token == "\\start_of_appendix") {
718 par->params().startOfAppendix(true);
719 } else if (token == "\\paragraph_separation") {
720 int tmpret = lex.findToken(string_paragraph_separation);
721 if (tmpret == -1) ++tmpret;
722 if (tmpret != LYX_LAYOUT_DEFAULT)
723 params.paragraph_separation =
724 static_cast<BufferParams::PARSEP>(tmpret);
725 } else if (token == "\\defskip") {
727 params.defskip = VSpace(lex.getString());
728 } else if (token == "\\epsfig") { // obsolete
729 // Indeed it is obsolete, but we HAVE to be backwards
730 // compatible until 0.14, because otherwise all figures
731 // in existing documents are irretrivably lost. (Asger)
732 params.readGraphicsDriver(lex);
733 } else if (token == "\\quotes_language") {
734 int tmpret = lex.findToken(string_quotes_language);
735 if (tmpret == -1) ++tmpret;
736 if (tmpret != LYX_LAYOUT_DEFAULT) {
737 InsetQuotes::quote_language tmpl =
738 InsetQuotes::EnglishQ;
741 tmpl = InsetQuotes::EnglishQ;
744 tmpl = InsetQuotes::SwedishQ;
747 tmpl = InsetQuotes::GermanQ;
750 tmpl = InsetQuotes::PolishQ;
753 tmpl = InsetQuotes::FrenchQ;
756 tmpl = InsetQuotes::DanishQ;
759 params.quotes_language = tmpl;
761 } else if (token == "\\quotes_times") {
763 switch (lex.getInteger()) {
765 params.quotes_times = InsetQuotes::SingleQ;
768 params.quotes_times = InsetQuotes::DoubleQ;
771 } else if (token == "\\papersize") {
772 int tmpret = lex.findToken(string_papersize);
776 params.papersize2 = tmpret;
777 } else if (token == "\\paperpackage") {
778 int tmpret = lex.findToken(string_paperpackages);
781 params.paperpackage = BufferParams::PACKAGE_NONE;
783 params.paperpackage = tmpret;
784 } else if (token == "\\use_geometry") {
786 params.use_geometry = lex.getInteger();
787 } else if (token == "\\use_amsmath") {
789 params.use_amsmath = lex.getInteger();
790 } else if (token == "\\use_natbib") {
792 params.use_natbib = lex.getInteger();
793 } else if (token == "\\use_numerical_citations") {
795 params.use_numerical_citations = lex.getInteger();
796 } else if (token == "\\paperorientation") {
797 int tmpret = lex.findToken(string_orientation);
798 if (tmpret == -1) ++tmpret;
799 if (tmpret != LYX_LAYOUT_DEFAULT)
800 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
801 } else if (token == "\\paperwidth") {
803 params.paperwidth = lex.getString();
804 } else if (token == "\\paperheight") {
806 params.paperheight = lex.getString();
807 } else if (token == "\\leftmargin") {
809 params.leftmargin = lex.getString();
810 } else if (token == "\\topmargin") {
812 params.topmargin = lex.getString();
813 } else if (token == "\\rightmargin") {
815 params.rightmargin = lex.getString();
816 } else if (token == "\\bottommargin") {
818 params.bottommargin = lex.getString();
819 } else if (token == "\\headheight") {
821 params.headheight = lex.getString();
822 } else if (token == "\\headsep") {
824 params.headsep = lex.getString();
825 } else if (token == "\\footskip") {
827 params.footskip = lex.getString();
828 } else if (token == "\\paperfontsize") {
830 params.fontsize = strip(lex.getString());
831 } else if (token == "\\papercolumns") {
833 params.columns = lex.getInteger();
834 } else if (token == "\\papersides") {
836 switch (lex.getInteger()) {
838 case 1: params.sides = LyXTextClass::OneSide; break;
839 case 2: params.sides = LyXTextClass::TwoSides; break;
841 } else if (token == "\\paperpagestyle") {
843 params.pagestyle = strip(lex.getString());
844 } else if (token == "\\bullet") {
846 int const index = lex.getInteger();
848 int temp_int = lex.getInteger();
849 params.user_defined_bullets[index].setFont(temp_int);
850 params.temp_bullets[index].setFont(temp_int);
852 temp_int = lex.getInteger();
853 params.user_defined_bullets[index].setCharacter(temp_int);
854 params.temp_bullets[index].setCharacter(temp_int);
856 temp_int = lex.getInteger();
857 params.user_defined_bullets[index].setSize(temp_int);
858 params.temp_bullets[index].setSize(temp_int);
860 string const temp_str = lex.getString();
861 if (temp_str != "\\end_bullet") {
862 // this element isn't really necessary for
863 // parsing but is easier for humans
864 // to understand bullets. Put it back and
865 // set a debug message?
866 lex.printError("\\end_bullet expected, got" + temp_str);
867 //how can I put it back?
869 } else if (token == "\\bulletLaTeX") {
871 int const index = lex.getInteger();
873 string temp_str = lex.getString();
875 while (temp_str != "\\end_bullet") {
876 // this loop structure is needed when user
877 // enters an empty string since the first
878 // thing returned will be the \\end_bullet
880 // if the LaTeX entry has spaces. Each element
881 // therefore needs to be read in turn
884 temp_str = lex.getString();
886 params.user_defined_bullets[index].setText(sum_str);
887 params.temp_bullets[index].setText(sum_str);
888 } else if (token == "\\secnumdepth") {
890 params.secnumdepth = lex.getInteger();
891 } else if (token == "\\tocdepth") {
893 params.tocdepth = lex.getInteger();
894 } else if (token == "\\spacing") {
896 string const tmp = strip(lex.getString());
897 Spacing::Space tmp_space = Spacing::Default;
899 if (tmp == "single") {
900 tmp_space = Spacing::Single;
901 } else if (tmp == "onehalf") {
902 tmp_space = Spacing::Onehalf;
903 } else if (tmp == "double") {
904 tmp_space = Spacing::Double;
905 } else if (tmp == "other") {
907 tmp_space = Spacing::Other;
908 tmp_val = lex.getFloat();
910 lex.printError("Unknown spacing token: '$$Token'");
912 // Small hack so that files written with klyx will be
915 par->params().spacing(Spacing(tmp_space, tmp_val));
917 params.spacing.set(tmp_space, tmp_val);
919 } else if (token == "\\paragraph_spacing") {
921 string const tmp = strip(lex.getString());
922 if (tmp == "single") {
923 par->params().spacing(Spacing(Spacing::Single));
924 } else if (tmp == "onehalf") {
925 par->params().spacing(Spacing(Spacing::Onehalf));
926 } else if (tmp == "double") {
927 par->params().spacing(Spacing(Spacing::Double));
928 } else if (tmp == "other") {
930 par->params().spacing(Spacing(Spacing::Other,
933 lex.printError("Unknown spacing token: '$$Token'");
935 } else if (token == "\\float_placement") {
937 params.float_placement = lex.getString();
938 } else if (token == "\\family") {
940 font.setLyXFamily(lex.getString());
941 } else if (token == "\\series") {
943 font.setLyXSeries(lex.getString());
944 } else if (token == "\\shape") {
946 font.setLyXShape(lex.getString());
947 } else if (token == "\\size") {
949 font.setLyXSize(lex.getString());
950 #ifndef NO_COMPABILITY
951 } else if (token == "\\latex") {
953 string const tok = lex.getString();
954 if (tok == "no_latex") {
956 insertErtContents(par, pos, font);
957 } else if (tok == "latex") {
958 ert_comp.active = true;
959 } else if (tok == "default") {
961 insertErtContents(par, pos, font);
963 lex.printError("Unknown LaTeX font flag "
967 } else if (token == "\\lang") {
969 string const tok = lex.getString();
970 Language const * lang = languages.getLanguage(tok);
972 font.setLanguage(lang);
974 font.setLanguage(params.language);
975 lex.printError("Unknown language `$$Token'");
977 } else if (token == "\\numeric") {
979 font.setNumber(font.setLyXMisc(lex.getString()));
980 } else if (token == "\\emph") {
982 font.setEmph(font.setLyXMisc(lex.getString()));
983 } else if (token == "\\bar") {
985 string const tok = lex.getString();
986 // This is dirty, but gone with LyX3. (Asger)
988 font.setUnderbar(LyXFont::ON);
989 else if (tok == "no")
990 font.setUnderbar(LyXFont::OFF);
991 else if (tok == "default")
992 font.setUnderbar(LyXFont::INHERIT);
994 lex.printError("Unknown bar font flag "
996 } else if (token == "\\noun") {
998 font.setNoun(font.setLyXMisc(lex.getString()));
999 } else if (token == "\\color") {
1001 font.setLyXColor(lex.getString());
1002 } else if (token == "\\align") {
1003 int tmpret = lex.findToken(string_align);
1004 if (tmpret == -1) ++tmpret;
1005 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1006 int const tmpret2 = int(pow(2.0, tmpret));
1007 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1008 par->params().align(LyXAlignment(tmpret2));
1010 } else if (token == "\\added_space_top") {
1012 par->params().spaceTop(VSpace(lex.getString()));
1013 } else if (token == "\\added_space_bottom") {
1015 par->params().spaceBottom(VSpace(lex.getString()));
1016 #ifndef NO_COMPABILITY
1017 #ifndef NO_PEXTRA_REALLY
1018 } else if (token == "\\pextra_type") {
1020 par->params().pextraType(lex.getInteger());
1021 } else if (token == "\\pextra_width") {
1023 par->params().pextraWidth(lex.getString());
1024 } else if (token == "\\pextra_widthp") {
1026 par->params().pextraWidthp(lex.getString());
1027 } else if (token == "\\pextra_alignment") {
1029 par->params().pextraAlignment(lex.getInteger());
1030 } else if (token == "\\pextra_hfill") {
1032 par->params().pextraHfill(lex.getInteger());
1033 } else if (token == "\\pextra_start_minipage") {
1035 par->params().pextraStartMinipage(lex.getInteger());
1038 } else if (token == "\\labelwidthstring") {
1040 par->params().labelWidthString(lex.getString());
1041 // do not delete this token, it is still needed!
1042 } else if (token == "\\end_inset") {
1043 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1044 << "Last inset read was: " << last_inset_read
1046 // Simply ignore this. The insets do not have
1048 // But insets should read it, it is a part of
1049 // the inset isn't it? Lgb.
1050 } else if (token == "\\begin_inset") {
1051 #ifndef NO_COMPABILITY
1052 insertErtContents(par, pos, font, false);
1053 ert_stack.push(ert_comp);
1054 ert_comp = ErtComp();
1056 readInset(lex, par, pos, font);
1057 #ifndef NO_COMPABILITY
1058 ert_comp = ert_stack.top();
1060 insertErtContents(par, pos, font);
1062 } else if (token == "\\SpecialChar") {
1063 LyXLayout const & layout =
1064 textclasslist.Style(params.textclass,
1067 // Insets don't make sense in a free-spacing context! ---Kayvan
1068 if (layout.free_spacing || par->isFreeSpacing()) {
1071 string next_token = lex.getString();
1072 if (next_token == "\\-") {
1073 par->insertChar(pos, '-', font);
1074 } else if (next_token == "\\protected_separator"
1075 || next_token == "~") {
1076 par->insertChar(pos, ' ', font);
1078 lex.printError("Token `$$Token' "
1080 "paragraph layout!");
1085 Inset * inset = new InsetSpecialChar;
1086 inset->read(this, lex);
1087 par->insertInset(pos, inset, font);
1090 } else if (token == "\\newline") {
1091 #ifndef NO_COMPABILITY
1092 if (!ert_comp.in_tabular && ert_comp.active) {
1093 ert_comp.contents += char(Paragraph::META_NEWLINE);
1095 // Since we cannot know it this is only a regular
1096 // newline or a tabular cell delimter we have to
1097 // handle the ERT here.
1098 insertErtContents(par, pos, font, false);
1100 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1104 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1107 } else if (token == "\\LyXTable") {
1108 #ifndef NO_COMPABILITY
1109 ert_comp.in_tabular = true;
1111 Inset * inset = new InsetTabular(*this);
1112 inset->read(this, lex);
1113 par->insertInset(pos, inset, font);
1115 } else if (token == "\\hfill") {
1116 par->insertChar(pos, Paragraph::META_HFILL, font);
1118 } else if (token == "\\protected_separator") { // obsolete
1119 // This is a backward compability thingie. (Lgb)
1120 // Remove it later some time...introduced with fileformat
1122 LyXLayout const & layout =
1123 textclasslist.Style(params.textclass,
1126 if (layout.free_spacing || par->isFreeSpacing()) {
1127 par->insertChar(pos, ' ', font);
1129 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1130 par->insertInset(pos, inset, font);
1133 } else if (token == "\\bibitem") { // ale970302
1135 InsetCommandParams p("bibitem", "dummy");
1136 par->bibkey = new InsetBibKey(p);
1138 par->bibkey->read(this, lex);
1139 } else if (token == "\\backslash") {
1140 #ifndef NO_COMPABILITY
1141 if (ert_comp.active) {
1142 ert_comp.contents += "\\";
1145 par->insertChar(pos, '\\', font);
1147 #ifndef NO_COMPABILITY
1150 } else if (token == "\\the_end") {
1151 #ifndef NO_COMPABILITY
1152 // If we still have some ert active here we have to insert
1153 // it so we don't loose it. (Lgb)
1154 insertErtContents(par, pos, font);
1156 the_end_read = true;
1157 #ifndef NO_COMPABILITY
1158 #ifndef NO_PEXTRA_REALLY
1159 minipar = parBeforeMinipage = 0;
1163 #ifndef NO_COMPABILITY
1164 if (ert_comp.active) {
1165 ert_comp.contents += token;
1168 // This should be insurance for the future: (Asger)
1171 string const s = _("Unknown token: ") + token
1172 + " " + lex.text() + "\n";
1174 InsetError * new_inset = new InsetError(s);
1175 par->insertInset(pos, new_inset);
1176 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT,
1179 #ifndef NO_COMPABILITY
1184 #ifndef NO_COMPABILITY
1185 #ifndef NO_PEXTRA_REALLY
1186 // I wonder if we could use this blanket fix for all the
1187 // checkminipage cases...
1188 if (par && par->size()) {
1189 // It is possible that this will check to often,
1190 // but that should not be an correctness issue.
1191 // Only a speed issue.
1192 checkminipage = true;
1195 // now check if we have a minipage paragraph as at this
1196 // point we already read all the necessary data!
1197 // this cannot be done in layout because there we did
1198 // not read yet the paragraph PEXTRA-params (Jug)
1200 // BEGIN pextra_minipage compability
1201 // This should be removed in 1.3.x (Lgb)
1203 // This compability code is not perfect. In a couple
1204 // of rand cases it fails. When the minipage par is
1205 // the first par in the document, and when there are
1206 // none or only one regular paragraphs after the
1207 // minipage. Currently I am not investing any effort
1208 // in fixing those cases.
1210 //lyxerr << "Call depth: " << call_depth << endl;
1211 if (checkminipage && (call_depth == 1)) {
1212 checkminipage = false;
1213 if (minipar && (minipar != par) &&
1214 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1216 lyxerr << "minipages in a row" << endl;
1217 if (par->params().pextraStartMinipage()) {
1218 lyxerr << "start new minipage" << endl;
1219 // minipages in a row
1220 par->previous()->next(0);
1223 Paragraph * tmp = minipar;
1225 tmp->params().pextraType(0);
1226 tmp->params().pextraWidth(string());
1227 tmp->params().pextraWidthp(string());
1228 tmp->params().pextraAlignment(0);
1229 tmp->params().pextraHfill(false);
1230 tmp->params().pextraStartMinipage(false);
1233 // create a new paragraph to insert the
1234 // minipages in the following case
1235 if (par->params().pextraStartMinipage() &&
1236 !par->params().pextraHfill())
1238 Paragraph * p = new Paragraph;
1240 p->previous(parBeforeMinipage);
1241 parBeforeMinipage->next(p);
1243 p->params().depth(parBeforeMinipage->params().depth());
1244 parBeforeMinipage = p;
1246 InsetMinipage * mini = new InsetMinipage;
1247 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1248 mini->width(par->params().pextraWidth());
1249 if (!par->params().pextraWidthp().empty()) {
1250 lyxerr << "WP:" << mini->width() << endl;
1251 mini->width(tostr(par->params().pextraWidthp())+"%");
1253 mini->inset.paragraph(par);
1254 // Insert the minipage last in the
1255 // previous paragraph.
1256 if (par->params().pextraHfill()) {
1257 parBeforeMinipage->insertChar
1258 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1260 parBeforeMinipage->insertInset
1261 (parBeforeMinipage->size(), mini);
1265 lyxerr << "new minipage par" << endl;
1266 //nothing to do just continue reading
1269 } else if (minipar && (minipar != par)) {
1270 lyxerr << "last minipage par read" << endl;
1271 // The last paragraph read was not part of a
1272 // minipage but the par linked list is...
1273 // So we need to remove the last par from the
1275 if (par->previous())
1276 par->previous()->next(0);
1277 par->previous(parBeforeMinipage);
1278 parBeforeMinipage->next(par);
1279 Paragraph * tmp = minipar;
1281 tmp->params().pextraType(0);
1282 tmp->params().pextraWidth(string());
1283 tmp->params().pextraWidthp(string());
1284 tmp->params().pextraAlignment(0);
1285 tmp->params().pextraHfill(false);
1286 tmp->params().pextraStartMinipage(false);
1289 depth = parBeforeMinipage->params().depth();
1290 minipar = parBeforeMinipage = 0;
1291 } else if (!minipar &&
1292 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1294 // par is the first paragraph in a minipage
1295 lyxerr << "begin minipage" << endl;
1296 // To minimize problems for
1297 // the users we will insert
1298 // the first minipage in
1299 // a sequence of minipages
1300 // in its own paragraph.
1301 Paragraph * p = new Paragraph;
1303 p->previous(par->previous());
1305 p->params().depth(depth);
1306 par->params().depth(0);
1308 if (par->previous())
1309 par->previous()->next(p);
1311 parBeforeMinipage = p;
1313 if (!first_par || (first_par == par))
1316 InsetMinipage * mini = new InsetMinipage;
1317 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1318 mini->width(minipar->params().pextraWidth());
1319 if (!par->params().pextraWidthp().empty()) {
1320 lyxerr << "WP:" << mini->width() << endl;
1321 mini->width(tostr(par->params().pextraWidthp())+"%");
1323 mini->inset.paragraph(minipar);
1325 // Insert the minipage last in the
1326 // previous paragraph.
1327 if (minipar->params().pextraHfill()) {
1328 parBeforeMinipage->insertChar
1329 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1331 parBeforeMinipage->insertInset
1332 (parBeforeMinipage->size(), mini);
1335 // End of pextra_minipage compability
1339 return the_end_read;
1342 // needed to insert the selection
1343 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1344 LyXFont const & fn,string const & str) const
1346 LyXLayout const & layout = textclasslist.Style(params.textclass,
1350 (void)par->checkInsertChar(font);
1351 // insert the string, don't insert doublespace
1352 bool space_inserted = true;
1353 for(string::const_iterator cit = str.begin();
1354 cit != str.end(); ++cit) {
1356 if (par->size() || layout.keepempty) {
1357 par->breakParagraph(params, pos,
1358 layout.isEnvironment());
1361 space_inserted = true;
1365 // do not insert consecutive spaces if !free_spacing
1366 } else if ((*cit == ' ' || *cit == '\t') &&
1367 space_inserted && !layout.free_spacing &&
1368 !par->isFreeSpacing())
1371 } else if (*cit == '\t') {
1372 if (!layout.free_spacing && !par->isFreeSpacing()) {
1373 // tabs are like spaces here
1374 par->insertChar(pos, ' ', font);
1376 space_inserted = true;
1378 const pos_type nb = 8 - pos % 8;
1379 for (pos_type a = 0; a < nb ; ++a) {
1380 par->insertChar(pos, ' ', font);
1383 space_inserted = true;
1385 } else if (!IsPrintable(*cit)) {
1386 // Ignore unprintables
1389 // just insert the character
1390 par->insertChar(pos, *cit, font);
1392 space_inserted = (*cit == ' ');
1399 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1400 int & pos, LyXFont & font)
1402 // consistency check
1403 if (lex.getString() != "\\begin_inset") {
1404 lyxerr << "Buffer::readInset: Consistency check failed."
1411 string const tmptok = lex.getString();
1412 last_inset_read = tmptok;
1414 // test the different insets
1415 if (tmptok == "LatexCommand") {
1416 InsetCommandParams inscmd;
1419 string const cmdName = inscmd.getCmdName();
1421 // This strange command allows LyX to recognize "natbib" style
1422 // citations: citet, citep, Citet etc.
1423 if (compare_no_case(cmdName, "cite", 4) == 0) {
1424 inset = new InsetCitation(inscmd);
1425 } else if (cmdName == "bibitem") {
1426 lex.printError("Wrong place for bibitem");
1427 inset = new InsetBibKey(inscmd);
1428 } else if (cmdName == "BibTeX") {
1429 inset = new InsetBibtex(inscmd);
1430 } else if (cmdName == "index") {
1431 inset = new InsetIndex(inscmd);
1432 } else if (cmdName == "include") {
1433 inset = new InsetInclude(inscmd, *this);
1434 } else if (cmdName == "label") {
1435 inset = new InsetLabel(inscmd);
1436 } else if (cmdName == "url"
1437 || cmdName == "htmlurl") {
1438 inset = new InsetUrl(inscmd);
1439 } else if (cmdName == "ref"
1440 || cmdName == "pageref"
1441 || cmdName == "vref"
1442 || cmdName == "vpageref"
1443 || cmdName == "prettyref") {
1444 if (!inscmd.getOptions().empty()
1445 || !inscmd.getContents().empty()) {
1446 inset = new InsetRef(inscmd, *this);
1448 } else if (cmdName == "tableofcontents") {
1449 inset = new InsetTOC(inscmd);
1450 } else if (cmdName == "listofalgorithms") {
1451 inset = new InsetFloatList("algorithm");
1452 } else if (cmdName == "listoffigures") {
1453 inset = new InsetFloatList("figure");
1454 } else if (cmdName == "listoftables") {
1455 inset = new InsetFloatList("table");
1456 } else if (cmdName == "printindex") {
1457 inset = new InsetPrintIndex(inscmd);
1458 } else if (cmdName == "lyxparent") {
1459 inset = new InsetParent(inscmd, *this);
1462 bool alreadyread = false;
1463 if (tmptok == "Quotes") {
1464 inset = new InsetQuotes;
1465 } else if (tmptok == "External") {
1466 inset = new InsetExternal;
1467 } else if (tmptok == "FormulaMacro") {
1468 inset = new InsetFormulaMacro;
1469 } else if (tmptok == "Formula") {
1470 inset = new InsetFormula;
1471 } else if (tmptok == "Figure") { // Backward compatibility
1472 inset = new InsetFig(100, 100, *this);
1473 //inset = new InsetGraphics;
1474 } else if (tmptok == "Graphics") {
1475 inset = new InsetGraphics;
1476 } else if (tmptok == "Info") {// backwards compatibility
1477 inset = new InsetNote(this,
1478 lex.getLongString("\\end_inset"),
1481 } else if (tmptok == "Note") {
1482 inset = new InsetNote;
1483 } else if (tmptok == "Include") {
1484 InsetCommandParams p( "Include" );
1485 inset = new InsetInclude(p, *this);
1486 } else if (tmptok == "ERT") {
1487 inset = new InsetERT;
1488 } else if (tmptok == "Tabular") {
1489 inset = new InsetTabular(*this);
1490 } else if (tmptok == "Text") {
1491 inset = new InsetText;
1492 } else if (tmptok == "Foot") {
1493 inset = new InsetFoot;
1494 } else if (tmptok == "Marginal") {
1495 inset = new InsetMarginal;
1496 } else if (tmptok == "Minipage") {
1497 inset = new InsetMinipage;
1498 } else if (tmptok == "Float") {
1500 string tmptok = lex.getString();
1501 inset = new InsetFloat(tmptok);
1503 } else if (tmptok == "List") {
1504 inset = new InsetList;
1505 } else if (tmptok == "Theorem") {
1506 inset = new InsetList;
1508 } else if (tmptok == "Caption") {
1509 inset = new InsetCaption;
1510 } else if (tmptok == "FloatList") {
1511 inset = new InsetFloatList;
1514 if (inset && !alreadyread) inset->read(this, lex);
1518 par->insertInset(pos, inset, font);
1524 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1528 string const token(lex.getString());
1529 if (token == "\\lyxformat") { // the first token _must_ be...
1531 string tmp_format = lex.getString();
1532 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1533 // if present remove ".," from string.
1534 string::size_type dot = tmp_format.find_first_of(".,");
1535 //lyxerr << " dot found at " << dot << endl;
1536 if (dot != string::npos)
1537 tmp_format.erase(dot, 1);
1538 file_format = strToInt(tmp_format);
1539 if (file_format == LYX_FORMAT) {
1541 } else if (file_format > LYX_FORMAT) {
1543 Alert::alert(_("Warning!"),
1544 _("LyX file format is newer that what"),
1545 _("is supported in this LyX version. Expect some problems."));
1547 } else if (file_format < LYX_FORMAT) {
1549 if (file_format < 200) {
1550 Alert::alert(_("ERROR!"),
1551 _("Old LyX file format found. "
1552 "Use LyX 0.10.x to read this!"));
1556 bool the_end = readLyXformat2(lex, par);
1557 params.setPaperStuff();
1558 // the_end was added in 213
1559 if (file_format < 213)
1563 Alert::alert(_("Warning!"),
1564 _("Reading of document is not complete"),
1565 _("Maybe the document is truncated"));
1568 } else { // "\\lyxformat" not found
1569 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1572 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1577 // Should probably be moved to somewhere else: BufferView? LyXView?
1578 bool Buffer::save() const
1580 // We don't need autosaves in the immediate future. (Asger)
1581 resetAutosaveTimers();
1585 if (lyxrc.make_backup) {
1586 s = fileName() + '~';
1587 if (!lyxrc.backupdir_path.empty())
1588 s = AddName(lyxrc.backupdir_path,
1589 subst(os::slashify_path(s),'/','!'));
1591 // Rename is the wrong way of making a backup,
1592 // this is the correct way.
1593 /* truss cp fil fil2:
1594 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1595 stat("LyXVC.lyx", 0xEFFFF688) = 0
1596 open("LyXVC.lyx", O_RDONLY) = 3
1597 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1598 fstat(4, 0xEFFFF508) = 0
1599 fstat(3, 0xEFFFF508) = 0
1600 read(3, " # T h i s f i l e w".., 8192) = 5579
1601 write(4, " # T h i s f i l e w".., 5579) = 5579
1602 read(3, 0xEFFFD4A0, 8192) = 0
1605 chmod("LyXVC3.lyx", 0100644) = 0
1606 lseek(0, 0, SEEK_CUR) = 46440
1610 // Should probably have some more error checking here.
1611 // Should be cleaned up in 0.13, at least a bit.
1612 // Doing it this way, also makes the inodes stay the same.
1613 // This is still not a very good solution, in particular we
1614 // might loose the owner of the backup.
1615 FileInfo finfo(fileName());
1616 if (finfo.exist()) {
1617 mode_t fmode = finfo.getMode();
1618 struct utimbuf times = {
1619 finfo.getAccessTime(),
1620 finfo.getModificationTime() };
1622 ifstream ifs(fileName().c_str());
1623 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1628 ::chmod(s.c_str(), fmode);
1630 if (::utime(s.c_str(), ×)) {
1631 lyxerr << "utime error." << endl;
1634 lyxerr << "LyX was not able to make "
1635 "backup copy. Beware." << endl;
1640 if (writeFile(fileName(), false)) {
1642 removeAutosaveFile(fileName());
1644 // Saving failed, so backup is not backup
1645 if (lyxrc.make_backup) {
1646 lyx::rename(s, fileName());
1654 // Returns false if unsuccesful
1655 bool Buffer::writeFile(string const & fname, bool flag) const
1657 // if flag is false writeFile will not create any GUI
1658 // warnings, only cerr.
1659 // Needed for autosave in background or panic save (Matthias 120496)
1661 if (read_only && (fname == filename)) {
1662 // Here we should come with a question if we should
1663 // perform the write anyway.
1665 lyxerr << _("Error! Document is read-only: ")
1668 Alert::alert(_("Error! Document is read-only: "),
1673 FileInfo finfo(fname);
1674 if (finfo.exist() && !finfo.writable()) {
1675 // Here we should come with a question if we should
1676 // try to do the save anyway. (i.e. do a chmod first)
1678 lyxerr << _("Error! Cannot write file: ")
1681 Alert::err_alert(_("Error! Cannot write file: "),
1686 ofstream ofs(fname.c_str());
1689 lyxerr << _("Error! Cannot open file: ")
1692 Alert::err_alert(_("Error! Cannot open file: "),
1698 // Use the standard "C" locale for file output.
1699 ofs.imbue(std::locale::classic());
1702 // The top of the file should not be written by params.
1704 // write out a comment in the top of the file
1705 ofs << '#' << lyx_docversion
1706 << " created this file. For more info see http://www.lyx.org/\n"
1707 << "\\lyxformat " << LYX_FORMAT << "\n";
1709 // now write out the buffer paramters.
1710 params.writeFile(ofs);
1712 Paragraph::depth_type depth = 0;
1714 // this will write out all the paragraphs
1715 // using recursive descent.
1716 paragraph->writeFile(this, ofs, params, depth);
1718 // Write marker that shows file is complete
1719 ofs << "\n\\the_end" << endl;
1723 // how to check if close went ok?
1724 // Following is an attempt... (BE 20001011)
1726 // good() returns false if any error occured, including some
1727 // formatting error.
1728 // bad() returns true if something bad happened in the buffer,
1729 // which should include file system full errors.
1736 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1738 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1748 string const Buffer::asciiParagraph(Paragraph const * par,
1749 unsigned int linelen) const
1751 ostringstream buffer;
1752 Paragraph::depth_type depth = 0;
1754 Paragraph::depth_type ltype_depth = 0;
1755 string::size_type currlinelen = 0;
1756 bool ref_printed = false;
1760 if (!par->previous()) {
1761 // begins or ends a deeper area ?
1762 if (depth != par->params().depth()) {
1763 if (par->params().depth() > depth) {
1764 while (par->params().depth() > depth) {
1768 while (par->params().depth() < depth) {
1774 // First write the layout
1775 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1776 if (tmp == "Itemize") {
1778 ltype_depth = depth + 1;
1779 } else if (tmp == "Enumerate") {
1781 ltype_depth = depth + 1;
1782 } else if (contains(tmp, "ection")) {
1784 ltype_depth = depth + 1;
1785 } else if (contains(tmp, "aragraph")) {
1787 ltype_depth = depth + 1;
1788 } else if (tmp == "Description") {
1790 ltype_depth = depth + 1;
1791 } else if (tmp == "Abstract") {
1794 } else if (tmp == "Bibliography") {
1802 /* maybe some vertical spaces */
1804 /* the labelwidthstring used in lists */
1808 /* some pagebreaks? */
1812 /* what about the alignment */
1814 lyxerr << "Should this ever happen?" << endl;
1817 for (pos_type i = 0; i < par->size(); ++i) {
1818 if (!i && !noparbreak) {
1821 for (Paragraph::depth_type j = 0; j < depth; ++j)
1823 currlinelen = depth * 2;
1826 case 4: // (Sub)Paragraph
1827 case 5: // Description
1831 buffer << "Abstract\n\n";
1833 buffer << "Abstract: ";
1835 case 7: // Bibliography
1838 buffer << "References\n\n";
1840 buffer << "References: ";
1845 buffer << par->params().labelString() << " ";
1848 if (ltype_depth > depth) {
1849 for (Paragraph::depth_type j = ltype_depth - 1;
1852 currlinelen += (ltype_depth-depth)*2;
1856 char c = par->getUChar(params, i);
1860 case Paragraph::META_INSET:
1862 Inset const * inset = par->getInset(i);
1864 if (!inset->ascii(this, buffer)) {
1867 rsplit(buffer.str().c_str(),
1869 currlinelen += s.length();
1871 // to be sure it breaks paragraph
1872 currlinelen += linelen;
1878 case Paragraph::META_NEWLINE:
1881 for (Paragraph::depth_type j = 0;
1885 currlinelen = depth * 2;
1886 if (ltype_depth > depth) {
1887 for (Paragraph::depth_type j = ltype_depth;
1890 currlinelen += (ltype_depth - depth) * 2;
1894 case Paragraph::META_HFILL:
1899 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1900 (c == ' ') && ((i + 2) < par->size()))
1903 for (Paragraph::depth_type j = 0;
1906 currlinelen = depth * 2;
1907 if (ltype_depth > depth) {
1908 for (Paragraph::depth_type j = ltype_depth;
1911 currlinelen += (ltype_depth-depth)*2;
1913 } else if (c != '\0') {
1917 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1921 return buffer.str().c_str();
1925 void Buffer::writeFileAscii(string const & fname, int linelen)
1927 ofstream ofs(fname.c_str());
1929 Alert::err_alert(_("Error: Cannot write file:"), fname);
1932 writeFileAscii(ofs, linelen);
1936 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1938 Paragraph * par = paragraph;
1940 ofs << asciiParagraph(par, linelen);
1948 void Buffer::makeLaTeXFile(string const & fname,
1949 string const & original_path,
1950 bool nice, bool only_body)
1952 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1954 niceFile = nice; // this will be used by Insetincludes.
1956 tex_code_break_column = lyxrc.ascii_linelen;
1958 LyXTextClass const & tclass =
1959 textclasslist.TextClass(params.textclass);
1961 ofstream ofs(fname.c_str());
1963 Alert::err_alert(_("Error: Cannot open file: "), fname);
1967 // validate the buffer.
1968 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1969 LaTeXFeatures features(params, tclass.numLayouts());
1971 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1974 // The starting paragraph of the coming rows is the
1975 // first paragraph of the document. (Asger)
1976 texrow.start(paragraph, 0);
1978 if (!only_body && nice) {
1979 ofs << "%% " << lyx_docversion << " created this file. "
1980 "For more info, see http://www.lyx.org/.\n"
1981 "%% Do not edit unless you really know what "
1986 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1987 // There are a few differences between nice LaTeX and usual files:
1988 // usual is \batchmode and has a
1989 // special input@path to allow the including of figures
1990 // with either \input or \includegraphics (what figinsets do).
1991 // batchmode is not set if there is a tex_code_break_column.
1992 // In this case somebody is interested in the generated LaTeX,
1993 // so this is OK. input@path is set when the actual parameter
1994 // original_path is set. This is done for usual tex-file, but not
1995 // for nice-latex-file. (Matthias 250696)
1998 // code for usual, NOT nice-latex-file
1999 ofs << "\\batchmode\n"; // changed
2000 // from \nonstopmode
2003 if (!original_path.empty()) {
2004 ofs << "\\makeatletter\n"
2005 << "\\def\\input@path{{"
2006 << os::external_path(original_path) << "/}}\n"
2007 << "\\makeatother\n";
2013 ofs << "\\documentclass";
2015 ostringstream options; // the document class options.
2017 if (tokenPos(tclass.opt_fontsize(),
2018 '|', params.fontsize) >= 0) {
2019 // only write if existing in list (and not default)
2020 options << params.fontsize << "pt,";
2024 if (!params.use_geometry &&
2025 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2026 switch (params.papersize) {
2027 case BufferParams::PAPER_A4PAPER:
2028 options << "a4paper,";
2030 case BufferParams::PAPER_USLETTER:
2031 options << "letterpaper,";
2033 case BufferParams::PAPER_A5PAPER:
2034 options << "a5paper,";
2036 case BufferParams::PAPER_B5PAPER:
2037 options << "b5paper,";
2039 case BufferParams::PAPER_EXECUTIVEPAPER:
2040 options << "executivepaper,";
2042 case BufferParams::PAPER_LEGALPAPER:
2043 options << "legalpaper,";
2049 if (params.sides != tclass.sides()) {
2050 switch (params.sides) {
2051 case LyXTextClass::OneSide:
2052 options << "oneside,";
2054 case LyXTextClass::TwoSides:
2055 options << "twoside,";
2061 if (params.columns != tclass.columns()) {
2062 if (params.columns == 2)
2063 options << "twocolumn,";
2065 options << "onecolumn,";
2068 if (!params.use_geometry
2069 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2070 options << "landscape,";
2072 // language should be a parameter to \documentclass
2074 ostringstream language_options;
2075 if (params.language->babel() == "hebrew"
2076 && default_language->babel() != "hebrew")
2077 // This seems necessary
2078 features.useLanguage(default_language);
2080 if (lyxrc.language_use_babel ||
2081 params.language->lang() != lyxrc.default_language ||
2082 !features.hasLanguages()) {
2084 language_options << features.getLanguages();
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 = features.getEncodingSet(doc_encoding);
2133 ofs << "\\usepackage[";
2134 std::copy(encodings.begin(), encodings.end(),
2135 std::ostream_iterator<string>(ofs, ","));
2136 ofs << doc_encoding << "]{inputenc}\n";
2138 } else if (params.inputenc != "default") {
2139 ofs << "\\usepackage[" << params.inputenc
2144 // At the very beginning the text parameters.
2145 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2146 switch (params.paperpackage) {
2147 case BufferParams::PACKAGE_A4:
2148 ofs << "\\usepackage{a4}\n";
2151 case BufferParams::PACKAGE_A4WIDE:
2152 ofs << "\\usepackage{a4wide}\n";
2155 case BufferParams::PACKAGE_WIDEMARGINSA4:
2156 ofs << "\\usepackage[widemargins]{a4}\n";
2161 if (params.use_geometry) {
2162 ofs << "\\usepackage{geometry}\n";
2164 ofs << "\\geometry{verbose";
2165 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2166 ofs << ",landscape";
2167 switch (params.papersize2) {
2168 case BufferParams::VM_PAPER_CUSTOM:
2169 if (!params.paperwidth.empty())
2170 ofs << ",paperwidth="
2171 << params.paperwidth;
2172 if (!params.paperheight.empty())
2173 ofs << ",paperheight="
2174 << params.paperheight;
2176 case BufferParams::VM_PAPER_USLETTER:
2177 ofs << ",letterpaper";
2179 case BufferParams::VM_PAPER_USLEGAL:
2180 ofs << ",legalpaper";
2182 case BufferParams::VM_PAPER_USEXECUTIVE:
2183 ofs << ",executivepaper";
2185 case BufferParams::VM_PAPER_A3:
2188 case BufferParams::VM_PAPER_A4:
2191 case BufferParams::VM_PAPER_A5:
2194 case BufferParams::VM_PAPER_B3:
2197 case BufferParams::VM_PAPER_B4:
2200 case BufferParams::VM_PAPER_B5:
2204 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2205 switch (lyxrc.default_papersize) {
2206 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2207 case BufferParams::PAPER_USLETTER:
2208 ofs << ",letterpaper";
2210 case BufferParams::PAPER_LEGALPAPER:
2211 ofs << ",legalpaper";
2213 case BufferParams::PAPER_EXECUTIVEPAPER:
2214 ofs << ",executivepaper";
2216 case BufferParams::PAPER_A3PAPER:
2219 case BufferParams::PAPER_A4PAPER:
2222 case BufferParams::PAPER_A5PAPER:
2225 case BufferParams::PAPER_B5PAPER:
2230 if (!params.topmargin.empty())
2231 ofs << ",tmargin=" << params.topmargin;
2232 if (!params.bottommargin.empty())
2233 ofs << ",bmargin=" << params.bottommargin;
2234 if (!params.leftmargin.empty())
2235 ofs << ",lmargin=" << params.leftmargin;
2236 if (!params.rightmargin.empty())
2237 ofs << ",rmargin=" << params.rightmargin;
2238 if (!params.headheight.empty())
2239 ofs << ",headheight=" << params.headheight;
2240 if (!params.headsep.empty())
2241 ofs << ",headsep=" << params.headsep;
2242 if (!params.footskip.empty())
2243 ofs << ",footskip=" << params.footskip;
2248 if (features.isRequired("amsstyle")
2249 && !tclass.provides(LyXTextClass::amsmath)) {
2250 ofs << "\\usepackage{amsmath}\n";
2254 if (tokenPos(tclass.opt_pagestyle(),
2255 '|', params.pagestyle) >= 0) {
2256 if (params.pagestyle == "fancy") {
2257 ofs << "\\usepackage{fancyhdr}\n";
2260 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2264 if (params.secnumdepth != tclass.secnumdepth()) {
2265 ofs << "\\setcounter{secnumdepth}{"
2266 << params.secnumdepth
2270 if (params.tocdepth != tclass.tocdepth()) {
2271 ofs << "\\setcounter{tocdepth}{"
2277 if (params.paragraph_separation) {
2278 switch (params.defskip.kind()) {
2279 case VSpace::SMALLSKIP:
2280 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2282 case VSpace::MEDSKIP:
2283 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2285 case VSpace::BIGSKIP:
2286 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2288 case VSpace::LENGTH:
2289 ofs << "\\setlength\\parskip{"
2290 << params.defskip.length().asLatexString()
2293 default: // should never happen // Then delete it.
2294 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2299 ofs << "\\setlength\\parindent{0pt}\n";
2303 // Now insert the LyX specific LaTeX commands...
2305 // The optional packages;
2306 string preamble(features.getPackages());
2308 // this might be useful...
2309 preamble += "\n\\makeatletter\n";
2311 // Some macros LyX will need
2312 string tmppreamble(features.getMacros());
2314 if (!tmppreamble.empty()) {
2315 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2316 "LyX specific LaTeX commands.\n"
2317 + tmppreamble + '\n';
2320 // the text class specific preamble
2321 tmppreamble = features.getTClassPreamble();
2322 if (!tmppreamble.empty()) {
2323 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2324 "Textclass specific LaTeX commands.\n"
2325 + tmppreamble + '\n';
2328 /* the user-defined preamble */
2329 if (!params.preamble.empty()) {
2330 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2331 "User specified LaTeX commands.\n"
2332 + params.preamble + '\n';
2335 preamble += "\\makeatother\n";
2337 // Itemize bullet settings need to be last in case the user
2338 // defines their own bullets that use a package included
2339 // in the user-defined preamble -- ARRae
2340 // Actually it has to be done much later than that
2341 // since some packages like frenchb make modifications
2342 // at \begin{document} time -- JMarc
2344 for (int i = 0; i < 4; ++i) {
2345 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2346 if (bullets_def.empty())
2347 bullets_def="\\AtBeginDocument{\n";
2348 bullets_def += " \\renewcommand{\\labelitemi";
2350 // `i' is one less than the item to modify
2357 bullets_def += "ii";
2363 bullets_def += "}{" +
2364 params.user_defined_bullets[i].getText()
2369 if (!bullets_def.empty())
2370 preamble += bullets_def + "}\n\n";
2372 for (int j = countChar(preamble, '\n'); j-- ;) {
2378 // We try to load babel late, in case it interferes
2379 // with other packages.
2381 string tmp = lyxrc.language_package;
2382 if (!lyxrc.language_global_options
2383 && tmp == "\\usepackage{babel}")
2384 tmp = string("\\usepackage[") +
2385 language_options.str().c_str() +
2392 ofs << "\\begin{document}\n";
2395 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2397 if (!lyxrc.language_auto_begin) {
2398 ofs << subst(lyxrc.language_command_begin, "$$lang",
2399 params.language->babel())
2404 latexParagraphs(ofs, paragraph, 0, texrow);
2406 // add this just in case after all the paragraphs
2410 if (!lyxrc.language_auto_end) {
2411 ofs << subst(lyxrc.language_command_end, "$$lang",
2412 params.language->babel())
2418 ofs << "\\end{document}\n";
2421 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2423 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2427 // Just to be sure. (Asger)
2430 // tex_code_break_column's value is used to decide
2431 // if we are in batchmode or not (within mathed_write()
2432 // in math_write.C) so we must set it to a non-zero
2433 // value when we leave otherwise we save incorrect .lyx files.
2434 tex_code_break_column = lyxrc.ascii_linelen;
2438 lyxerr << "File was not closed properly." << endl;
2441 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2446 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2448 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2449 Paragraph * endpar, TexRow & texrow) const
2451 bool was_title = false;
2452 bool already_title = false;
2455 while (par != endpar) {
2456 LyXLayout const & layout =
2457 textclasslist.Style(params.textclass,
2460 if (layout.intitle) {
2461 if (already_title) {
2462 lyxerr <<"Error in latexParagraphs: You"
2463 " should not mix title layouts"
2464 " with normal ones." << endl;
2467 } else if (was_title && !already_title) {
2468 ofs << "\\maketitle\n";
2470 already_title = true;
2474 if (layout.isEnvironment()) {
2475 par = par->TeXEnvironment(this, params, ofs, texrow);
2477 par = par->TeXOnePar(this, params, ofs, texrow, false);
2480 // It might be that we only have a title in this document
2481 if (was_title && !already_title) {
2482 ofs << "\\maketitle\n";
2488 bool Buffer::isLatex() const
2490 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2494 bool Buffer::isLinuxDoc() const
2496 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2500 bool Buffer::isLiterate() const
2502 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2506 bool Buffer::isDocBook() const
2508 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2512 bool Buffer::isSGML() const
2514 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2515 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2519 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2520 string const & latexname) const
2522 if (!latexname.empty() && latexname != "!-- --")
2523 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2524 os << string(depth, ' ') << "<" << latexname << ">\n";
2528 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2529 string const & latexname) const
2531 if (!latexname.empty() && latexname != "!-- --")
2532 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2533 os << string(depth, ' ') << "</" << latexname << ">\n";
2537 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2539 ofstream ofs(fname.c_str());
2542 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2546 niceFile = nice; // this will be used by included files.
2548 LyXTextClass const & tclass =
2549 textclasslist.TextClass(params.textclass);
2551 LaTeXFeatures features(params, tclass.numLayouts());
2556 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2559 ofs << "<!doctype linuxdoc system";
2561 string preamble = params.preamble;
2562 preamble += features.getIncludedFiles(fname);
2563 preamble += features.getLyXSGMLEntities();
2565 if (!preamble.empty()) {
2566 ofs << " [ " << preamble << " ]";
2570 if (params.options.empty())
2571 sgmlOpenTag(ofs, 0, top_element);
2573 string top = top_element;
2575 top += params.options;
2576 sgmlOpenTag(ofs, 0, top);
2580 ofs << "<!-- " << lyx_docversion
2581 << " created this file. For more info see http://www.lyx.org/"
2584 Paragraph::depth_type depth = 0; // paragraph depth
2585 Paragraph * par = paragraph;
2587 vector<string> environment_stack(5);
2590 LyXLayout const & style =
2591 textclasslist.Style(params.textclass,
2594 // treat <toc> as a special case for compatibility with old code
2595 if (par->isInset(0)) {
2596 Inset * inset = par->getInset(0);
2597 Inset::Code lyx_code = inset->lyxCode();
2598 if (lyx_code == Inset::TOC_CODE){
2599 string const temp = "toc";
2600 sgmlOpenTag(ofs, depth, temp);
2607 // environment tag closing
2608 for (; depth > par->params().depth(); --depth) {
2609 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2610 environment_stack[depth].erase();
2613 // write opening SGML tags
2614 switch (style.latextype) {
2615 case LATEX_PARAGRAPH:
2616 if (depth == par->params().depth()
2617 && !environment_stack[depth].empty()) {
2618 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2619 environment_stack[depth].erase();
2625 sgmlOpenTag(ofs, depth, style.latexname());
2631 _("Error : Wrong depth for"
2632 " LatexType Command.\n"));
2634 if (!environment_stack[depth].empty()){
2635 sgmlCloseTag(ofs, depth,
2636 environment_stack[depth]);
2640 environment_stack[depth].erase();
2641 sgmlOpenTag(ofs, depth, style.latexname());
2644 case LATEX_ENVIRONMENT:
2645 case LATEX_ITEM_ENVIRONMENT:
2646 if (depth == par->params().depth()
2647 && environment_stack[depth] != style.latexname()) {
2648 sgmlCloseTag(ofs, depth,
2649 environment_stack[depth]);
2650 environment_stack[depth].erase();
2652 if (depth < par->params().depth()) {
2653 depth = par->params().depth();
2654 environment_stack[depth].erase();
2656 if (environment_stack[depth] != style.latexname()) {
2658 sgmlOpenTag(ofs, depth, "p");
2660 sgmlOpenTag(ofs, depth, style.latexname());
2662 if (environment_stack.size() == depth + 1)
2663 environment_stack.push_back("!-- --");
2664 environment_stack[depth] = style.latexname();
2667 if (style.latexparam() == "CDATA")
2670 if (style.latextype == LATEX_ENVIRONMENT) break;
2672 if (style.labeltype == LABEL_MANUAL)
2677 sgmlOpenTag(ofs, depth + 1, item_name);
2680 sgmlOpenTag(ofs, depth, style.latexname());
2684 simpleLinuxDocOnePar(ofs, par, depth);
2689 // write closing SGML tags
2690 switch (style.latextype) {
2693 case LATEX_ENVIRONMENT:
2694 case LATEX_ITEM_ENVIRONMENT:
2695 if (style.latexparam() == "CDATA")
2699 sgmlCloseTag(ofs, depth, style.latexname());
2705 for (int i=depth; i >= 0; --i)
2706 sgmlCloseTag(ofs, depth, environment_stack[i]);
2710 sgmlCloseTag(ofs, 0, top_element);
2714 // How to check for successful close
2718 // checks, if newcol chars should be put into this line
2719 // writes newline, if necessary.
2722 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2723 string::size_type newcol)
2726 if (colcount > lyxrc.ascii_linelen) {
2728 colcount = newcol; // assume write after this call
2743 string tag_name(PAR_TAG const & pt) {
2745 case NONE: return "!-- --";
2746 case TT: return "tt";
2747 case SF: return "sf";
2748 case BF: return "bf";
2749 case IT: return "it";
2750 case SL: return "sl";
2751 case EM: return "em";
2758 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2760 p1 = static_cast<PAR_TAG>(p1 | p2);
2765 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2767 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2773 // Handle internal paragraph parsing -- layout already processed.
2774 void Buffer::simpleLinuxDocOnePar(ostream & os,
2776 Paragraph::depth_type /*depth*/)
2778 LyXLayout const & style = textclasslist.Style(params.textclass,
2780 string::size_type char_line_count = 5; // Heuristic choice ;-)
2782 // gets paragraph main font
2785 if (style.labeltype == LABEL_MANUAL) {
2786 font_old = style.labelfont;
2789 font_old = style.font;
2793 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2794 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2795 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2798 stack<PAR_TAG> tag_state;
2799 // parsing main loop
2800 for (pos_type i = 0; i < par->size(); ++i) {
2802 PAR_TAG tag_close = NONE;
2803 list < PAR_TAG > tag_open;
2805 LyXFont const font = par->getFont(params, i);
2807 if (font_old.family() != font.family()) {
2808 switch (family_type) {
2809 case LyXFont::SANS_FAMILY:
2812 case LyXFont::TYPEWRITER_FAMILY:
2819 family_type = font.family();
2821 switch (family_type) {
2822 case LyXFont::SANS_FAMILY:
2823 tag_open.push_back(SF);
2825 case LyXFont::TYPEWRITER_FAMILY:
2826 tag_open.push_back(TT);
2833 if (font_old.series() != font.series()) {
2834 switch (series_type) {
2835 case LyXFont::BOLD_SERIES:
2842 series_type = font.series();
2844 switch (series_type) {
2845 case LyXFont::BOLD_SERIES:
2846 tag_open.push_back(BF);
2854 if (font_old.shape() != font.shape()) {
2855 switch (shape_type) {
2856 case LyXFont::ITALIC_SHAPE:
2859 case LyXFont::SLANTED_SHAPE:
2866 shape_type = font.shape();
2868 switch (shape_type) {
2869 case LyXFont::ITALIC_SHAPE:
2870 tag_open.push_back(IT);
2872 case LyXFont::SLANTED_SHAPE:
2873 tag_open.push_back(SL);
2880 if (font_old.emph() != font.emph()) {
2881 if (font.emph() == LyXFont::ON) {
2882 tag_open.push_back(EM);
2891 list < PAR_TAG > temp;
2892 while(!tag_state.empty() && tag_close ) {
2893 PAR_TAG k = tag_state.top();
2895 os << "</" << tag_name(k) << ">";
2902 for(list< PAR_TAG >::const_iterator j = temp.begin();
2903 j != temp.end(); ++j) {
2905 os << "<" << tag_name(*j) << ">";
2908 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2909 j != tag_open.end(); ++j) {
2911 os << "<" << tag_name(*j) << ">";
2914 char c = par->getChar(i);
2916 if (c == Paragraph::META_INSET) {
2917 Inset * inset = par->getInset(i);
2918 inset->linuxdoc(this, os);
2923 if (style.latexparam() == "CDATA") {
2924 // "TeX"-Mode on == > SGML-Mode on.
2930 if (par->sgmlConvertChar(c, sgml_string)
2931 && !style.free_spacing && !par->isFreeSpacing())
2933 // in freespacing mode, spaces are
2934 // non-breaking characters
2935 if (desc_on) {// if char is ' ' then...
2938 sgmlLineBreak(os, char_line_count, 6);
2942 sgmlLineBreak(os, char_line_count, 1);
2947 char_line_count += sgml_string.length();
2953 while (!tag_state.empty()) {
2954 os << "</" << tag_name(tag_state.top()) << ">";
2958 // resets description flag correctly
2960 // <tag> not closed...
2961 sgmlLineBreak(os, char_line_count, 6);
2967 // Print an error message.
2968 void Buffer::sgmlError(Paragraph * par, int pos,
2969 string const & message) const
2971 // insert an error marker in text
2972 InsetError * new_inset = new InsetError(message);
2973 par->insertInset(pos, new_inset);
2974 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT, params.language));
2978 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2980 ofstream ofs(fname.c_str());
2982 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2986 Paragraph * par = paragraph;
2988 niceFile = nice; // this will be used by Insetincludes.
2990 LyXTextClass const & tclass =
2991 textclasslist.TextClass(params.textclass);
2993 LaTeXFeatures features(params, tclass.numLayouts());
2998 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3001 ofs << "<!DOCTYPE " << top_element
3002 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3004 string preamble = params.preamble;
3005 preamble += features.getIncludedFiles(fname);
3006 preamble += features.getLyXSGMLEntities();
3008 if (!preamble.empty()) {
3009 ofs << "\n [ " << preamble << " ]";
3014 string top = top_element;
3016 top += params.language->code();
3019 if (!params.options.empty()) {
3021 top += params.options;
3023 sgmlOpenTag(ofs, 0, top);
3025 ofs << "<!-- DocBook file was created by " << lyx_docversion
3026 << "\n See http://www.lyx.org/ for more information -->\n";
3028 vector<string> environment_stack(10);
3029 vector<string> environment_inner(10);
3030 vector<string> command_stack(10);
3032 bool command_flag = false;
3033 Paragraph::depth_type command_depth = 0;
3034 Paragraph::depth_type command_base = 0;
3035 Paragraph::depth_type cmd_depth = 0;
3036 Paragraph::depth_type depth = 0; // paragraph depth
3039 string command_name;
3045 int desc_on = 0; // description mode
3047 LyXLayout const & style =
3048 textclasslist.Style(params.textclass,
3051 // environment tag closing
3052 for (; depth > par->params().depth(); --depth) {
3053 if (environment_inner[depth] != "!-- --") {
3054 item_name = "listitem";
3055 sgmlCloseTag(ofs, command_depth + depth,
3057 if (environment_inner[depth] == "varlistentry")
3058 sgmlCloseTag(ofs, depth+command_depth,
3059 environment_inner[depth]);
3061 sgmlCloseTag(ofs, depth + command_depth,
3062 environment_stack[depth]);
3063 environment_stack[depth].erase();
3064 environment_inner[depth].erase();
3067 if (depth == par->params().depth()
3068 && environment_stack[depth] != style.latexname()
3069 && !environment_stack[depth].empty()) {
3070 if (environment_inner[depth] != "!-- --") {
3071 item_name= "listitem";
3072 sgmlCloseTag(ofs, command_depth+depth,
3074 if (environment_inner[depth] == "varlistentry")
3076 depth + command_depth,
3077 environment_inner[depth]);
3080 sgmlCloseTag(ofs, depth + command_depth,
3081 environment_stack[depth]);
3083 environment_stack[depth].erase();
3084 environment_inner[depth].erase();
3087 // Write opening SGML tags.
3088 switch (style.latextype) {
3089 case LATEX_PARAGRAPH:
3090 sgmlOpenTag(ofs, depth + command_depth,
3097 _("Error : Wrong depth for "
3098 "LatexType Command.\n"));
3100 command_name = style.latexname();
3102 sgmlparam = style.latexparam();
3103 c_params = split(sgmlparam, c_depth,'|');
3105 cmd_depth = lyx::atoi(c_depth);
3108 if (cmd_depth < command_base) {
3109 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3110 sgmlCloseTag(ofs, j, command_stack[j]);
3111 command_depth = command_base = cmd_depth;
3112 } else if (cmd_depth <= command_depth) {
3113 for (int j = command_depth; j >= int(cmd_depth); --j)
3114 sgmlCloseTag(ofs, j, command_stack[j]);
3115 command_depth = cmd_depth;
3117 command_depth = cmd_depth;
3119 command_depth = command_base = cmd_depth;
3120 command_flag = true;
3122 if (command_stack.size() == command_depth + 1)
3123 command_stack.push_back(string());
3124 command_stack[command_depth] = command_name;
3126 // treat label as a special case for
3127 // more WYSIWYM handling.
3128 if (par->isInset(0)) {
3129 Inset * inset = par->getInset(0);
3130 Inset::Code lyx_code = inset->lyxCode();
3131 if (lyx_code == Inset::LABEL_CODE){
3132 command_name += " id=\"";
3133 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3134 command_name += "\"";
3139 sgmlOpenTag(ofs, depth + command_depth, command_name);
3140 if (c_params.empty())
3141 item_name = "title";
3143 item_name = c_params;
3144 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3147 case LATEX_ENVIRONMENT:
3148 case LATEX_ITEM_ENVIRONMENT:
3149 if (depth < par->params().depth()) {
3150 depth = par->params().depth();
3151 environment_stack[depth].erase();
3154 if (environment_stack[depth] != style.latexname()) {
3155 if(environment_stack.size() == depth + 1) {
3156 environment_stack.push_back("!-- --");
3157 environment_inner.push_back("!-- --");
3159 environment_stack[depth] = style.latexname();
3160 environment_inner[depth] = "!-- --";
3161 sgmlOpenTag(ofs, depth + command_depth,
3162 environment_stack[depth]);
3164 if (environment_inner[depth] != "!-- --") {
3165 item_name= "listitem";
3167 command_depth + depth,
3169 if (environment_inner[depth] == "varlistentry")
3171 depth + command_depth,
3172 environment_inner[depth]);
3176 if (style.latextype == LATEX_ENVIRONMENT) {
3177 if (!style.latexparam().empty()) {
3178 if(style.latexparam() == "CDATA")
3181 sgmlOpenTag(ofs, depth + command_depth,
3182 style.latexparam());
3187 desc_on = (style.labeltype == LABEL_MANUAL);
3190 environment_inner[depth]= "varlistentry";
3192 environment_inner[depth]= "listitem";
3194 sgmlOpenTag(ofs, depth + 1 + command_depth,
3195 environment_inner[depth]);
3199 sgmlOpenTag(ofs, depth + 1 + command_depth,
3203 sgmlOpenTag(ofs, depth + 1 + command_depth,
3208 sgmlOpenTag(ofs, depth + command_depth,
3213 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3217 // write closing SGML tags
3218 switch (style.latextype) {
3220 if (c_params.empty())
3224 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3226 case LATEX_ENVIRONMENT:
3227 if (!style.latexparam().empty()) {
3228 if(style.latexparam() == "CDATA")
3231 sgmlCloseTag(ofs, depth + command_depth,
3232 style.latexparam());
3235 case LATEX_ITEM_ENVIRONMENT:
3236 if (desc_on == 1) break;
3238 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3240 case LATEX_PARAGRAPH:
3241 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3244 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3250 for (int d = depth; d >= 0; --d) {
3251 if (!environment_stack[depth].empty()) {
3252 if (environment_inner[depth] != "!-- --") {
3253 item_name = "listitem";
3254 sgmlCloseTag(ofs, command_depth + depth,
3256 if (environment_inner[depth] == "varlistentry")
3257 sgmlCloseTag(ofs, depth + command_depth,
3258 environment_inner[depth]);
3261 sgmlCloseTag(ofs, depth + command_depth,
3262 environment_stack[depth]);
3266 for (int j = command_depth; j >= 0 ; --j)
3267 if (!command_stack[j].empty())
3268 sgmlCloseTag(ofs, j, command_stack[j]);
3271 sgmlCloseTag(ofs, 0, top_element);
3274 // How to check for successful close
3278 void Buffer::simpleDocBookOnePar(ostream & os,
3279 Paragraph * par, int & desc_on,
3280 Paragraph::depth_type depth) const
3282 bool emph_flag = false;
3284 LyXLayout const & style = textclasslist.Style(params.textclass,
3287 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3289 int char_line_count = depth;
3290 //if (!style.free_spacing)
3291 // os << string(depth,' ');
3293 // parsing main loop
3294 for (pos_type i = 0; i < par->size(); ++i) {
3295 LyXFont font = par->getFont(params, i);
3297 // handle <emphasis> tag
3298 if (font_old.emph() != font.emph()) {
3299 if (font.emph() == LyXFont::ON) {
3303 os << "</emphasis>";
3308 char c = par->getChar(i);
3310 if (c == Paragraph::META_INSET) {
3311 Inset * inset = par->getInset(i);
3312 inset->docbook(this, os);
3315 par->sgmlConvertChar(c, sgml_string);
3317 if (style.pass_thru) {
3319 } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
3321 } else if (desc_on ==1) {
3323 os << "\n</term><listitem><para>";
3333 os << "</emphasis>";
3336 // resets description flag correctly
3338 // <term> not closed...
3341 if(style.free_spacing) os << '\n';
3345 // This should be enabled when the Chktex class is implemented. (Asger)
3346 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3347 // Other flags: -wall -v0 -x
3348 int Buffer::runChktex()
3350 if (!users->text) return 0;
3352 users->owner()->prohibitInput();
3354 // get LaTeX-Filename
3355 string const name = getLatexName();
3356 string path = OnlyPath(filename);
3358 string const org_path = path;
3359 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3363 Path p(path); // path to LaTeX file
3364 users->owner()->message(_("Running chktex..."));
3366 // Remove all error insets
3367 bool const removedErrorInsets = users->removeAutoInsets();
3369 // Generate the LaTeX file if neccessary
3370 makeLaTeXFile(name, org_path, false);
3373 Chktex chktex(lyxrc.chktex_command, name, filepath);
3374 int res = chktex.run(terr); // run chktex
3377 Alert::alert(_("chktex did not work!"),
3378 _("Could not run with file:"), name);
3379 } else if (res > 0) {
3380 // Insert all errors as errors boxes
3381 users->insertErrors(terr);
3384 // if we removed error insets before we ran chktex or if we inserted
3385 // error insets after we ran chktex, this must be run:
3386 if (removedErrorInsets || res){
3390 users->owner()->allowInput();
3396 void Buffer::validate(LaTeXFeatures & features) const
3398 Paragraph * par = paragraph;
3399 LyXTextClass const & tclass =
3400 textclasslist.TextClass(params.textclass);
3402 // AMS Style is at document level
3403 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3404 features.require("amsstyle");
3407 // We don't use "lyxerr.debug" because of speed. (Asger)
3408 if (lyxerr.debugging(Debug::LATEX))
3409 lyxerr << "Paragraph: " << par << endl;
3411 // Now just follow the list of paragraphs and run
3412 // validate on each of them.
3413 par->validate(features);
3415 // and then the next paragraph
3419 // the bullet shapes are buffer level not paragraph level
3420 // so they are tested here
3421 for (int i = 0; i < 4; ++i) {
3422 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3423 int const font = params.user_defined_bullets[i].getFont();
3425 int const c = params
3426 .user_defined_bullets[i]
3433 features.require("latexsym");
3435 } else if (font == 1) {
3436 features.require("amssymb");
3437 } else if ((font >= 2 && font <= 5)) {
3438 features.require("pifont");
3443 if (lyxerr.debugging(Debug::LATEX)) {
3444 features.showStruct();
3449 // This function should be in Buffer because it's a buffer's property (ale)
3450 string const Buffer::getIncludeonlyList(char delim)
3453 for (inset_iterator it = inset_iterator_begin();
3454 it != inset_iterator_end(); ++it) {
3455 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3456 InsetInclude * insetinc =
3457 static_cast<InsetInclude *>(*it);
3458 if (insetinc->isIncludeOnly()) {
3461 lst += insetinc->getRelFileBaseName();
3465 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3470 vector<string> const Buffer::getLabelList()
3472 /// if this is a child document and the parent is already loaded
3473 /// Use the parent's list instead [ale990407]
3474 if (!params.parentname.empty()
3475 && bufferlist.exists(params.parentname)) {
3476 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3478 return tmp->getLabelList();
3481 vector<string> label_list;
3482 for (inset_iterator it = inset_iterator_begin();
3483 it != inset_iterator_end(); ++it) {
3484 vector<string> const l = (*it)->getLabelList();
3485 label_list.insert(label_list.end(), l.begin(), l.end());
3491 Buffer::Lists const Buffer::getLists() const
3494 Paragraph * par = paragraph;
3497 std::pair<bool, LyXTextClassList::size_type> const tmp =
3498 textclasslist.NumberOfLayout(params.textclass, "Caption");
3499 bool const found = tmp.first;
3500 LyXTextClassList::size_type const cap = tmp.second;
3503 // This is the prefered way to to this, but boost::tie can break
3506 LyXTextClassList::size_type cap;
3507 boost::tie(found, cap) = textclasslist
3508 .NumberOfLayout(params.textclass, "Caption");
3512 char const labeltype =
3513 textclasslist.Style(params.textclass,
3514 par->getLayout()).labeltype;
3516 if (labeltype >= LABEL_COUNTER_CHAPTER
3517 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3518 // insert this into the table of contents
3519 SingleList & item = l["TOC"];
3522 textclasslist.TextClass(params.textclass).maxcounter());
3523 item.push_back(TocItem(par, depth, par->asString(this, true)));
3525 // For each paragrph, traverse its insets and look for
3529 Paragraph::inset_iterator it =
3530 par->inset_iterator_begin();
3531 Paragraph::inset_iterator end =
3532 par->inset_iterator_end();
3534 for (; it != end; ++it) {
3535 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3537 static_cast<InsetFloat*>(*it);
3539 string const type = il->type();
3541 // Now find the caption in the float...
3542 // We now tranverse the paragraphs of
3544 Paragraph * tmp = il->inset.paragraph();
3546 if (tmp->layout == cap) {
3547 SingleList & item = l[type];
3549 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3550 item.push_back(TocItem(tmp, 0 , str));
3557 lyxerr << "caption not found" << endl;
3566 // This is also a buffer property (ale)
3567 vector<pair<string, string> > const Buffer::getBibkeyList()
3569 /// if this is a child document and the parent is already loaded
3570 /// Use the parent's list instead [ale990412]
3571 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3572 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3574 return tmp->getBibkeyList();
3577 vector<pair<string, string> > keys;
3578 Paragraph * par = paragraph;
3581 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3582 par->asString(this, false)));
3586 // Might be either using bibtex or a child has bibliography
3588 for (inset_iterator it = inset_iterator_begin();
3589 it != inset_iterator_end(); ++it) {
3590 // Search for Bibtex or Include inset
3591 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3592 vector<pair<string,string> > tmp =
3593 static_cast<InsetBibtex*>(*it)->getKeys(this);
3594 keys.insert(keys.end(), tmp.begin(), tmp.end());
3595 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3596 vector<pair<string,string> > const tmp =
3597 static_cast<InsetInclude*>(*it)->getKeys();
3598 keys.insert(keys.end(), tmp.begin(), tmp.end());
3607 bool Buffer::isDepClean(string const & name) const
3609 DEPCLEAN * item = dep_clean;
3610 while (item && item->master != name)
3612 if (!item) return true;
3617 void Buffer::markDepClean(string const & name)
3620 dep_clean = new DEPCLEAN;
3621 dep_clean->clean = true;
3622 dep_clean->master = name;
3623 dep_clean->next = 0;
3625 DEPCLEAN * item = dep_clean;
3626 while (item && item->master != name)
3631 item = new DEPCLEAN;
3633 item->master = name;
3640 bool Buffer::dispatch(string const & command)
3642 // Split command string into command and argument
3644 string line = frontStrip(command);
3645 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3647 return dispatch(lyxaction.LookupFunc(cmd), arg);
3651 bool Buffer::dispatch(int action, string const & argument)
3653 bool dispatched = true;
3656 Exporter::Export(this, argument, false);
3666 void Buffer::resizeInsets(BufferView * bv)
3668 /// then remove all LyXText in text-insets
3669 Paragraph * par = paragraph;
3670 for (; par; par = par->next()) {
3671 par->resizeInsetsLyXText(bv);
3676 void Buffer::redraw()
3683 void Buffer::changeLanguage(Language const * from, Language const * to)
3686 ParIterator end = par_iterator_end();
3687 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3688 (*it)->changeLanguage(params, from, to);
3692 bool Buffer::isMultiLingual()
3694 ParIterator end = par_iterator_end();
3695 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3696 if ((*it)->isMultiLingual(params))
3703 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3706 it = par->InsetIterator(pos);
3707 if (it == par->inset_iterator_end()) {
3714 void Buffer::inset_iterator::setParagraph()
3717 it = par->inset_iterator_begin();
3718 if (it != par->inset_iterator_end())
3723 // We maintain an invariant that whenever par = 0 then it = 0
3727 Inset * Buffer::getInsetFromID(int id_arg) const
3729 for (inset_iterator it = inset_const_iterator_begin();
3730 it != inset_const_iterator_end(); ++it)
3732 if ((*it)->id() == id_arg)
3734 Inset * in = (*it)->getInsetFromID(id_arg);
3742 Paragraph * Buffer::getParFromID(int id) const
3744 if (id < 0) return 0;
3745 Paragraph * par = paragraph;
3747 if (par->id() == id) {
3750 Paragraph * tmp = par->getParFromID(id);
3760 ParIterator Buffer::par_iterator_begin()
3762 return ParIterator(paragraph);
3766 ParIterator Buffer::par_iterator_end()
3768 return ParIterator();