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) {
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) {
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)
1370 } else if (*cit == '\t') {
1371 if (!layout.free_spacing) {
1372 // tabs are like spaces here
1373 par->insertChar(pos, ' ', font);
1375 space_inserted = true;
1377 const pos_type nb = 8 - pos % 8;
1378 for (pos_type a = 0; a < nb ; ++a) {
1379 par->insertChar(pos, ' ', font);
1382 space_inserted = true;
1384 } else if (!IsPrintable(*cit)) {
1385 // Ignore unprintables
1388 // just insert the character
1389 par->insertChar(pos, *cit, font);
1391 space_inserted = (*cit == ' ');
1398 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1399 int & pos, LyXFont & font)
1401 // consistency check
1402 if (lex.getString() != "\\begin_inset") {
1403 lyxerr << "Buffer::readInset: Consistency check failed."
1410 string const tmptok = lex.getString();
1411 last_inset_read = tmptok;
1413 // test the different insets
1414 if (tmptok == "LatexCommand") {
1415 InsetCommandParams inscmd;
1418 string const cmdName = inscmd.getCmdName();
1420 // This strange command allows LyX to recognize "natbib" style
1421 // citations: citet, citep, Citet etc.
1422 if (compare_no_case(cmdName, "cite", 4) == 0) {
1423 inset = new InsetCitation(inscmd);
1424 } else if (cmdName == "bibitem") {
1425 lex.printError("Wrong place for bibitem");
1426 inset = new InsetBibKey(inscmd);
1427 } else if (cmdName == "BibTeX") {
1428 inset = new InsetBibtex(inscmd);
1429 } else if (cmdName == "index") {
1430 inset = new InsetIndex(inscmd);
1431 } else if (cmdName == "include") {
1432 inset = new InsetInclude(inscmd, *this);
1433 } else if (cmdName == "label") {
1434 inset = new InsetLabel(inscmd);
1435 } else if (cmdName == "url"
1436 || cmdName == "htmlurl") {
1437 inset = new InsetUrl(inscmd);
1438 } else if (cmdName == "ref"
1439 || cmdName == "pageref"
1440 || cmdName == "vref"
1441 || cmdName == "vpageref"
1442 || cmdName == "prettyref") {
1443 if (!inscmd.getOptions().empty()
1444 || !inscmd.getContents().empty()) {
1445 inset = new InsetRef(inscmd, *this);
1447 } else if (cmdName == "tableofcontents") {
1448 inset = new InsetTOC(inscmd);
1449 } else if (cmdName == "listofalgorithms") {
1450 inset = new InsetFloatList("algorithm");
1451 } else if (cmdName == "listoffigures") {
1452 inset = new InsetFloatList("figure");
1453 } else if (cmdName == "listoftables") {
1454 inset = new InsetFloatList("table");
1455 } else if (cmdName == "printindex") {
1456 inset = new InsetPrintIndex(inscmd);
1457 } else if (cmdName == "lyxparent") {
1458 inset = new InsetParent(inscmd, *this);
1461 bool alreadyread = false;
1462 if (tmptok == "Quotes") {
1463 inset = new InsetQuotes;
1464 } else if (tmptok == "External") {
1465 inset = new InsetExternal;
1466 } else if (tmptok == "FormulaMacro") {
1467 inset = new InsetFormulaMacro;
1468 } else if (tmptok == "Formula") {
1469 inset = new InsetFormula;
1470 } else if (tmptok == "Figure") { // Backward compatibility
1471 inset = new InsetFig(100, 100, *this);
1472 //inset = new InsetGraphics;
1473 } else if (tmptok == "Graphics") {
1474 inset = new InsetGraphics;
1475 } else if (tmptok == "Info") {// backwards compatibility
1476 inset = new InsetNote(this,
1477 lex.getLongString("\\end_inset"),
1480 } else if (tmptok == "Note") {
1481 inset = new InsetNote;
1482 } else if (tmptok == "Include") {
1483 InsetCommandParams p( "Include" );
1484 inset = new InsetInclude(p, *this);
1485 } else if (tmptok == "ERT") {
1486 inset = new InsetERT;
1487 } else if (tmptok == "Tabular") {
1488 inset = new InsetTabular(*this);
1489 } else if (tmptok == "Text") {
1490 inset = new InsetText;
1491 } else if (tmptok == "Foot") {
1492 inset = new InsetFoot;
1493 } else if (tmptok == "Marginal") {
1494 inset = new InsetMarginal;
1495 } else if (tmptok == "Minipage") {
1496 inset = new InsetMinipage;
1497 } else if (tmptok == "Float") {
1499 string tmptok = lex.getString();
1500 inset = new InsetFloat(tmptok);
1502 } else if (tmptok == "List") {
1503 inset = new InsetList;
1504 } else if (tmptok == "Theorem") {
1505 inset = new InsetList;
1507 } else if (tmptok == "Caption") {
1508 inset = new InsetCaption;
1509 } else if (tmptok == "FloatList") {
1510 inset = new InsetFloatList;
1513 if (inset && !alreadyread) inset->read(this, lex);
1517 par->insertInset(pos, inset, font);
1523 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1527 string const token(lex.getString());
1528 if (token == "\\lyxformat") { // the first token _must_ be...
1530 string tmp_format = lex.getString();
1531 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1532 // if present remove ".," from string.
1533 string::size_type dot = tmp_format.find_first_of(".,");
1534 //lyxerr << " dot found at " << dot << endl;
1535 if (dot != string::npos)
1536 tmp_format.erase(dot, 1);
1537 file_format = strToInt(tmp_format);
1538 if (file_format == LYX_FORMAT) {
1540 } else if (file_format > LYX_FORMAT) {
1542 Alert::alert(_("Warning!"),
1543 _("LyX file format is newer that what"),
1544 _("is supported in this LyX version. Expect some problems."));
1546 } else if (file_format < LYX_FORMAT) {
1548 if (file_format < 200) {
1549 Alert::alert(_("ERROR!"),
1550 _("Old LyX file format found. "
1551 "Use LyX 0.10.x to read this!"));
1555 bool the_end = readLyXformat2(lex, par);
1556 params.setPaperStuff();
1557 // the_end was added in 213
1558 if (file_format < 213)
1562 Alert::alert(_("Warning!"),
1563 _("Reading of document is not complete"),
1564 _("Maybe the document is truncated"));
1567 } else { // "\\lyxformat" not found
1568 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1571 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1576 // Should probably be moved to somewhere else: BufferView? LyXView?
1577 bool Buffer::save() const
1579 // We don't need autosaves in the immediate future. (Asger)
1580 resetAutosaveTimers();
1584 if (lyxrc.make_backup) {
1585 s = fileName() + '~';
1586 if (!lyxrc.backupdir_path.empty())
1587 s = AddName(lyxrc.backupdir_path,
1588 subst(os::slashify_path(s),'/','!'));
1590 // Rename is the wrong way of making a backup,
1591 // this is the correct way.
1592 /* truss cp fil fil2:
1593 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1594 stat("LyXVC.lyx", 0xEFFFF688) = 0
1595 open("LyXVC.lyx", O_RDONLY) = 3
1596 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1597 fstat(4, 0xEFFFF508) = 0
1598 fstat(3, 0xEFFFF508) = 0
1599 read(3, " # T h i s f i l e w".., 8192) = 5579
1600 write(4, " # T h i s f i l e w".., 5579) = 5579
1601 read(3, 0xEFFFD4A0, 8192) = 0
1604 chmod("LyXVC3.lyx", 0100644) = 0
1605 lseek(0, 0, SEEK_CUR) = 46440
1609 // Should probably have some more error checking here.
1610 // Should be cleaned up in 0.13, at least a bit.
1611 // Doing it this way, also makes the inodes stay the same.
1612 // This is still not a very good solution, in particular we
1613 // might loose the owner of the backup.
1614 FileInfo finfo(fileName());
1615 if (finfo.exist()) {
1616 mode_t fmode = finfo.getMode();
1617 struct utimbuf times = {
1618 finfo.getAccessTime(),
1619 finfo.getModificationTime() };
1621 ifstream ifs(fileName().c_str());
1622 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1627 ::chmod(s.c_str(), fmode);
1629 if (::utime(s.c_str(), ×)) {
1630 lyxerr << "utime error." << endl;
1633 lyxerr << "LyX was not able to make "
1634 "backup copy. Beware." << endl;
1639 if (writeFile(fileName(), false)) {
1641 removeAutosaveFile(fileName());
1643 // Saving failed, so backup is not backup
1644 if (lyxrc.make_backup) {
1645 lyx::rename(s, fileName());
1653 // Returns false if unsuccesful
1654 bool Buffer::writeFile(string const & fname, bool flag) const
1656 // if flag is false writeFile will not create any GUI
1657 // warnings, only cerr.
1658 // Needed for autosave in background or panic save (Matthias 120496)
1660 if (read_only && (fname == filename)) {
1661 // Here we should come with a question if we should
1662 // perform the write anyway.
1664 lyxerr << _("Error! Document is read-only: ")
1667 Alert::alert(_("Error! Document is read-only: "),
1672 FileInfo finfo(fname);
1673 if (finfo.exist() && !finfo.writable()) {
1674 // Here we should come with a question if we should
1675 // try to do the save anyway. (i.e. do a chmod first)
1677 lyxerr << _("Error! Cannot write file: ")
1680 Alert::err_alert(_("Error! Cannot write file: "),
1685 ofstream ofs(fname.c_str());
1688 lyxerr << _("Error! Cannot open file: ")
1691 Alert::err_alert(_("Error! Cannot open file: "),
1697 // Use the standard "C" locale for file output.
1698 ofs.imbue(std::locale::classic());
1701 // The top of the file should not be written by params.
1703 // write out a comment in the top of the file
1704 ofs << '#' << lyx_docversion
1705 << " created this file. For more info see http://www.lyx.org/\n"
1706 << "\\lyxformat " << LYX_FORMAT << "\n";
1708 // now write out the buffer paramters.
1709 params.writeFile(ofs);
1711 Paragraph::depth_type depth = 0;
1713 // this will write out all the paragraphs
1714 // using recursive descent.
1715 paragraph->writeFile(this, ofs, params, depth);
1717 // Write marker that shows file is complete
1718 ofs << "\n\\the_end" << endl;
1722 // how to check if close went ok?
1723 // Following is an attempt... (BE 20001011)
1725 // good() returns false if any error occured, including some
1726 // formatting error.
1727 // bad() returns true if something bad happened in the buffer,
1728 // which should include file system full errors.
1735 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1737 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1747 string const Buffer::asciiParagraph(Paragraph const * par,
1748 unsigned int linelen) const
1750 ostringstream buffer;
1751 Paragraph::depth_type depth = 0;
1753 Paragraph::depth_type ltype_depth = 0;
1754 string::size_type currlinelen = 0;
1755 bool ref_printed = false;
1759 if (!par->previous()) {
1760 // begins or ends a deeper area ?
1761 if (depth != par->params().depth()) {
1762 if (par->params().depth() > depth) {
1763 while (par->params().depth() > depth) {
1767 while (par->params().depth() < depth) {
1773 // First write the layout
1774 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1775 if (tmp == "Itemize") {
1777 ltype_depth = depth + 1;
1778 } else if (tmp == "Enumerate") {
1780 ltype_depth = depth + 1;
1781 } else if (contains(tmp, "ection")) {
1783 ltype_depth = depth + 1;
1784 } else if (contains(tmp, "aragraph")) {
1786 ltype_depth = depth + 1;
1787 } else if (tmp == "Description") {
1789 ltype_depth = depth + 1;
1790 } else if (tmp == "Abstract") {
1793 } else if (tmp == "Bibliography") {
1801 /* maybe some vertical spaces */
1803 /* the labelwidthstring used in lists */
1807 /* some pagebreaks? */
1811 /* what about the alignment */
1813 lyxerr << "Should this ever happen?" << endl;
1816 for (pos_type i = 0; i < par->size(); ++i) {
1817 if (!i && !noparbreak) {
1820 for (Paragraph::depth_type j = 0; j < depth; ++j)
1822 currlinelen = depth * 2;
1825 case 4: // (Sub)Paragraph
1826 case 5: // Description
1830 buffer << "Abstract\n\n";
1832 buffer << "Abstract: ";
1834 case 7: // Bibliography
1837 buffer << "References\n\n";
1839 buffer << "References: ";
1844 buffer << par->params().labelString() << " ";
1847 if (ltype_depth > depth) {
1848 for (Paragraph::depth_type j = ltype_depth - 1;
1851 currlinelen += (ltype_depth-depth)*2;
1855 char c = par->getUChar(params, i);
1859 case Paragraph::META_INSET:
1861 Inset const * inset = par->getInset(i);
1863 if (!inset->ascii(this, buffer)) {
1866 rsplit(buffer.str().c_str(),
1868 currlinelen += s.length();
1870 // to be sure it breaks paragraph
1871 currlinelen += linelen;
1877 case Paragraph::META_NEWLINE:
1880 for (Paragraph::depth_type j = 0;
1884 currlinelen = depth * 2;
1885 if (ltype_depth > depth) {
1886 for (Paragraph::depth_type j = ltype_depth;
1889 currlinelen += (ltype_depth - depth) * 2;
1893 case Paragraph::META_HFILL:
1898 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1899 (c == ' ') && ((i + 2) < par->size()))
1902 for (Paragraph::depth_type j = 0;
1905 currlinelen = depth * 2;
1906 if (ltype_depth > depth) {
1907 for (Paragraph::depth_type j = ltype_depth;
1910 currlinelen += (ltype_depth-depth)*2;
1912 } else if (c != '\0') {
1916 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1920 return buffer.str().c_str();
1924 void Buffer::writeFileAscii(string const & fname, int linelen)
1926 ofstream ofs(fname.c_str());
1928 Alert::err_alert(_("Error: Cannot write file:"), fname);
1931 writeFileAscii(ofs, linelen);
1935 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1937 Paragraph * par = paragraph;
1939 ofs << asciiParagraph(par, linelen);
1947 void Buffer::makeLaTeXFile(string const & fname,
1948 string const & original_path,
1949 bool nice, bool only_body)
1951 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1953 niceFile = nice; // this will be used by Insetincludes.
1955 tex_code_break_column = lyxrc.ascii_linelen;
1957 LyXTextClass const & tclass =
1958 textclasslist.TextClass(params.textclass);
1960 ofstream ofs(fname.c_str());
1962 Alert::err_alert(_("Error: Cannot open file: "), fname);
1966 // validate the buffer.
1967 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1968 LaTeXFeatures features(params, tclass.numLayouts());
1970 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1973 // The starting paragraph of the coming rows is the
1974 // first paragraph of the document. (Asger)
1975 texrow.start(paragraph, 0);
1977 if (!only_body && nice) {
1978 ofs << "%% " << lyx_docversion << " created this file. "
1979 "For more info, see http://www.lyx.org/.\n"
1980 "%% Do not edit unless you really know what "
1985 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1986 // There are a few differences between nice LaTeX and usual files:
1987 // usual is \batchmode and has a
1988 // special input@path to allow the including of figures
1989 // with either \input or \includegraphics (what figinsets do).
1990 // batchmode is not set if there is a tex_code_break_column.
1991 // In this case somebody is interested in the generated LaTeX,
1992 // so this is OK. input@path is set when the actual parameter
1993 // original_path is set. This is done for usual tex-file, but not
1994 // for nice-latex-file. (Matthias 250696)
1997 // code for usual, NOT nice-latex-file
1998 ofs << "\\batchmode\n"; // changed
1999 // from \nonstopmode
2002 if (!original_path.empty()) {
2003 ofs << "\\makeatletter\n"
2004 << "\\def\\input@path{{"
2005 << os::external_path(original_path) << "/}}\n"
2006 << "\\makeatother\n";
2012 ofs << "\\documentclass";
2014 ostringstream options; // the document class options.
2016 if (tokenPos(tclass.opt_fontsize(),
2017 '|', params.fontsize) >= 0) {
2018 // only write if existing in list (and not default)
2019 options << params.fontsize << "pt,";
2023 if (!params.use_geometry &&
2024 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2025 switch (params.papersize) {
2026 case BufferParams::PAPER_A4PAPER:
2027 options << "a4paper,";
2029 case BufferParams::PAPER_USLETTER:
2030 options << "letterpaper,";
2032 case BufferParams::PAPER_A5PAPER:
2033 options << "a5paper,";
2035 case BufferParams::PAPER_B5PAPER:
2036 options << "b5paper,";
2038 case BufferParams::PAPER_EXECUTIVEPAPER:
2039 options << "executivepaper,";
2041 case BufferParams::PAPER_LEGALPAPER:
2042 options << "legalpaper,";
2048 if (params.sides != tclass.sides()) {
2049 switch (params.sides) {
2050 case LyXTextClass::OneSide:
2051 options << "oneside,";
2053 case LyXTextClass::TwoSides:
2054 options << "twoside,";
2060 if (params.columns != tclass.columns()) {
2061 if (params.columns == 2)
2062 options << "twocolumn,";
2064 options << "onecolumn,";
2067 if (!params.use_geometry
2068 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2069 options << "landscape,";
2071 // language should be a parameter to \documentclass
2073 ostringstream language_options;
2074 if (params.language->babel() == "hebrew"
2075 && default_language->babel() != "hebrew")
2076 // This seems necessary
2077 features.useLanguage(default_language);
2079 if (lyxrc.language_use_babel ||
2080 params.language->lang() != lyxrc.default_language ||
2081 !features.hasLanguages()) {
2083 language_options << features.getLanguages();
2084 language_options << params.language->babel();
2085 if (lyxrc.language_global_options)
2086 options << language_options.str() << ',';
2089 // the user-defined options
2090 if (!params.options.empty()) {
2091 options << params.options << ',';
2094 string strOptions(options.str().c_str());
2095 if (!strOptions.empty()){
2096 strOptions = strip(strOptions, ',');
2097 ofs << '[' << strOptions << ']';
2101 << textclasslist.LatexnameOfClass(params.textclass)
2104 // end of \documentclass defs
2106 // font selection must be done before loading fontenc.sty
2107 // The ae package is not needed when using OT1 font encoding.
2108 if (params.fonts != "default" &&
2109 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2110 ofs << "\\usepackage{" << params.fonts << "}\n";
2112 if (params.fonts == "ae") {
2113 ofs << "\\usepackage{aecompl}\n";
2117 // this one is not per buffer
2118 if (lyxrc.fontenc != "default") {
2119 ofs << "\\usepackage[" << lyxrc.fontenc
2124 if (params.inputenc == "auto") {
2125 string const doc_encoding =
2126 params.language->encoding()->LatexName();
2128 // Create a list with all the input encodings used
2130 set<string> encodings = features.getEncodingSet(doc_encoding);
2132 ofs << "\\usepackage[";
2133 std::copy(encodings.begin(), encodings.end(),
2134 std::ostream_iterator<string>(ofs, ","));
2135 ofs << doc_encoding << "]{inputenc}\n";
2137 } else if (params.inputenc != "default") {
2138 ofs << "\\usepackage[" << params.inputenc
2143 // At the very beginning the text parameters.
2144 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2145 switch (params.paperpackage) {
2146 case BufferParams::PACKAGE_A4:
2147 ofs << "\\usepackage{a4}\n";
2150 case BufferParams::PACKAGE_A4WIDE:
2151 ofs << "\\usepackage{a4wide}\n";
2154 case BufferParams::PACKAGE_WIDEMARGINSA4:
2155 ofs << "\\usepackage[widemargins]{a4}\n";
2160 if (params.use_geometry) {
2161 ofs << "\\usepackage{geometry}\n";
2163 ofs << "\\geometry{verbose";
2164 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2165 ofs << ",landscape";
2166 switch (params.papersize2) {
2167 case BufferParams::VM_PAPER_CUSTOM:
2168 if (!params.paperwidth.empty())
2169 ofs << ",paperwidth="
2170 << params.paperwidth;
2171 if (!params.paperheight.empty())
2172 ofs << ",paperheight="
2173 << params.paperheight;
2175 case BufferParams::VM_PAPER_USLETTER:
2176 ofs << ",letterpaper";
2178 case BufferParams::VM_PAPER_USLEGAL:
2179 ofs << ",legalpaper";
2181 case BufferParams::VM_PAPER_USEXECUTIVE:
2182 ofs << ",executivepaper";
2184 case BufferParams::VM_PAPER_A3:
2187 case BufferParams::VM_PAPER_A4:
2190 case BufferParams::VM_PAPER_A5:
2193 case BufferParams::VM_PAPER_B3:
2196 case BufferParams::VM_PAPER_B4:
2199 case BufferParams::VM_PAPER_B5:
2203 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2204 switch (lyxrc.default_papersize) {
2205 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2206 case BufferParams::PAPER_USLETTER:
2207 ofs << ",letterpaper";
2209 case BufferParams::PAPER_LEGALPAPER:
2210 ofs << ",legalpaper";
2212 case BufferParams::PAPER_EXECUTIVEPAPER:
2213 ofs << ",executivepaper";
2215 case BufferParams::PAPER_A3PAPER:
2218 case BufferParams::PAPER_A4PAPER:
2221 case BufferParams::PAPER_A5PAPER:
2224 case BufferParams::PAPER_B5PAPER:
2229 if (!params.topmargin.empty())
2230 ofs << ",tmargin=" << params.topmargin;
2231 if (!params.bottommargin.empty())
2232 ofs << ",bmargin=" << params.bottommargin;
2233 if (!params.leftmargin.empty())
2234 ofs << ",lmargin=" << params.leftmargin;
2235 if (!params.rightmargin.empty())
2236 ofs << ",rmargin=" << params.rightmargin;
2237 if (!params.headheight.empty())
2238 ofs << ",headheight=" << params.headheight;
2239 if (!params.headsep.empty())
2240 ofs << ",headsep=" << params.headsep;
2241 if (!params.footskip.empty())
2242 ofs << ",footskip=" << params.footskip;
2247 if (features.isRequired("amsstyle")
2248 && !tclass.provides(LyXTextClass::amsmath)) {
2249 ofs << "\\usepackage{amsmath}\n";
2253 if (tokenPos(tclass.opt_pagestyle(),
2254 '|', params.pagestyle) >= 0) {
2255 if (params.pagestyle == "fancy") {
2256 ofs << "\\usepackage{fancyhdr}\n";
2259 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2263 if (params.secnumdepth != tclass.secnumdepth()) {
2264 ofs << "\\setcounter{secnumdepth}{"
2265 << params.secnumdepth
2269 if (params.tocdepth != tclass.tocdepth()) {
2270 ofs << "\\setcounter{tocdepth}{"
2276 if (params.paragraph_separation) {
2277 switch (params.defskip.kind()) {
2278 case VSpace::SMALLSKIP:
2279 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2281 case VSpace::MEDSKIP:
2282 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2284 case VSpace::BIGSKIP:
2285 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2287 case VSpace::LENGTH:
2288 ofs << "\\setlength\\parskip{"
2289 << params.defskip.length().asLatexString()
2292 default: // should never happen // Then delete it.
2293 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2298 ofs << "\\setlength\\parindent{0pt}\n";
2302 // Now insert the LyX specific LaTeX commands...
2304 // The optional packages;
2305 string preamble(features.getPackages());
2307 // this might be useful...
2308 preamble += "\n\\makeatletter\n";
2310 // Some macros LyX will need
2311 string tmppreamble(features.getMacros());
2313 if (!tmppreamble.empty()) {
2314 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2315 "LyX specific LaTeX commands.\n"
2316 + tmppreamble + '\n';
2319 // the text class specific preamble
2320 tmppreamble = features.getTClassPreamble();
2321 if (!tmppreamble.empty()) {
2322 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2323 "Textclass specific LaTeX commands.\n"
2324 + tmppreamble + '\n';
2327 /* the user-defined preamble */
2328 if (!params.preamble.empty()) {
2329 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2330 "User specified LaTeX commands.\n"
2331 + params.preamble + '\n';
2334 preamble += "\\makeatother\n";
2336 // Itemize bullet settings need to be last in case the user
2337 // defines their own bullets that use a package included
2338 // in the user-defined preamble -- ARRae
2339 // Actually it has to be done much later than that
2340 // since some packages like frenchb make modifications
2341 // at \begin{document} time -- JMarc
2343 for (int i = 0; i < 4; ++i) {
2344 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2345 if (bullets_def.empty())
2346 bullets_def="\\AtBeginDocument{\n";
2347 bullets_def += " \\renewcommand{\\labelitemi";
2349 // `i' is one less than the item to modify
2356 bullets_def += "ii";
2362 bullets_def += "}{" +
2363 params.user_defined_bullets[i].getText()
2368 if (!bullets_def.empty())
2369 preamble += bullets_def + "}\n\n";
2371 for (int j = countChar(preamble, '\n'); j-- ;) {
2377 // We try to load babel late, in case it interferes
2378 // with other packages.
2380 string tmp = lyxrc.language_package;
2381 if (!lyxrc.language_global_options
2382 && tmp == "\\usepackage{babel}")
2383 tmp = string("\\usepackage[") +
2384 language_options.str().c_str() +
2391 ofs << "\\begin{document}\n";
2394 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2396 if (!lyxrc.language_auto_begin) {
2397 ofs << subst(lyxrc.language_command_begin, "$$lang",
2398 params.language->babel())
2403 latexParagraphs(ofs, paragraph, 0, texrow);
2405 // add this just in case after all the paragraphs
2409 if (!lyxrc.language_auto_end) {
2410 ofs << subst(lyxrc.language_command_end, "$$lang",
2411 params.language->babel())
2417 ofs << "\\end{document}\n";
2420 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2422 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2426 // Just to be sure. (Asger)
2429 // tex_code_break_column's value is used to decide
2430 // if we are in batchmode or not (within mathed_write()
2431 // in math_write.C) so we must set it to a non-zero
2432 // value when we leave otherwise we save incorrect .lyx files.
2433 tex_code_break_column = lyxrc.ascii_linelen;
2437 lyxerr << "File was not closed properly." << endl;
2440 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2445 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2447 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2448 Paragraph * endpar, TexRow & texrow) const
2450 bool was_title = false;
2451 bool already_title = false;
2454 while (par != endpar) {
2455 LyXLayout const & layout =
2456 textclasslist.Style(params.textclass,
2459 if (layout.intitle) {
2460 if (already_title) {
2461 lyxerr <<"Error in latexParagraphs: You"
2462 " should not mix title layouts"
2463 " with normal ones." << endl;
2466 } else if (was_title && !already_title) {
2467 ofs << "\\maketitle\n";
2469 already_title = true;
2473 if (layout.isEnvironment()) {
2474 par = par->TeXEnvironment(this, params, ofs, texrow);
2476 par = par->TeXOnePar(this, params, ofs, texrow, false);
2479 // It might be that we only have a title in this document
2480 if (was_title && !already_title) {
2481 ofs << "\\maketitle\n";
2487 bool Buffer::isLatex() const
2489 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2493 bool Buffer::isLinuxDoc() const
2495 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2499 bool Buffer::isLiterate() const
2501 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2505 bool Buffer::isDocBook() const
2507 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2511 bool Buffer::isSGML() const
2513 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2514 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2518 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2519 string const & latexname) const
2521 if (!latexname.empty() && latexname != "!-- --")
2522 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2523 os << string(depth, ' ') << "<" << latexname << ">\n";
2527 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2528 string const & latexname) const
2530 if (!latexname.empty() && latexname != "!-- --")
2531 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2532 os << string(depth, ' ') << "</" << latexname << ">\n";
2536 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2538 ofstream ofs(fname.c_str());
2541 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2545 niceFile = nice; // this will be used by included files.
2547 LyXTextClass const & tclass =
2548 textclasslist.TextClass(params.textclass);
2550 LaTeXFeatures features(params, tclass.numLayouts());
2555 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2558 ofs << "<!doctype linuxdoc system";
2560 string preamble = params.preamble;
2561 preamble += features.getIncludedFiles(fname);
2562 preamble += features.getLyXSGMLEntities();
2564 if (!preamble.empty()) {
2565 ofs << " [ " << preamble << " ]";
2569 if (params.options.empty())
2570 sgmlOpenTag(ofs, 0, top_element);
2572 string top = top_element;
2574 top += params.options;
2575 sgmlOpenTag(ofs, 0, top);
2579 ofs << "<!-- " << lyx_docversion
2580 << " created this file. For more info see http://www.lyx.org/"
2583 Paragraph::depth_type depth = 0; // paragraph depth
2584 Paragraph * par = paragraph;
2586 vector<string> environment_stack(5);
2589 LyXLayout const & style =
2590 textclasslist.Style(params.textclass,
2593 // treat <toc> as a special case for compatibility with old code
2594 if (par->isInset(0)) {
2595 Inset * inset = par->getInset(0);
2596 Inset::Code lyx_code = inset->lyxCode();
2597 if (lyx_code == Inset::TOC_CODE){
2598 string const temp = "toc";
2599 sgmlOpenTag(ofs, depth, temp);
2606 // environment tag closing
2607 for (; depth > par->params().depth(); --depth) {
2608 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2609 environment_stack[depth].erase();
2612 // write opening SGML tags
2613 switch (style.latextype) {
2614 case LATEX_PARAGRAPH:
2615 if (depth == par->params().depth()
2616 && !environment_stack[depth].empty()) {
2617 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2618 environment_stack[depth].erase();
2624 sgmlOpenTag(ofs, depth, style.latexname());
2630 _("Error : Wrong depth for"
2631 " LatexType Command.\n"));
2633 if (!environment_stack[depth].empty()){
2634 sgmlCloseTag(ofs, depth,
2635 environment_stack[depth]);
2639 environment_stack[depth].erase();
2640 sgmlOpenTag(ofs, depth, style.latexname());
2643 case LATEX_ENVIRONMENT:
2644 case LATEX_ITEM_ENVIRONMENT:
2645 if (depth == par->params().depth()
2646 && environment_stack[depth] != style.latexname()) {
2647 sgmlCloseTag(ofs, depth,
2648 environment_stack[depth]);
2649 environment_stack[depth].erase();
2651 if (depth < par->params().depth()) {
2652 depth = par->params().depth();
2653 environment_stack[depth].erase();
2655 if (environment_stack[depth] != style.latexname()) {
2657 sgmlOpenTag(ofs, depth, "p");
2659 sgmlOpenTag(ofs, depth, style.latexname());
2661 if (environment_stack.size() == depth + 1)
2662 environment_stack.push_back("!-- --");
2663 environment_stack[depth] = style.latexname();
2666 if (style.latexparam() == "CDATA")
2669 if (style.latextype == LATEX_ENVIRONMENT) break;
2671 if (style.labeltype == LABEL_MANUAL)
2676 sgmlOpenTag(ofs, depth + 1, item_name);
2679 sgmlOpenTag(ofs, depth, style.latexname());
2683 simpleLinuxDocOnePar(ofs, par, depth);
2688 // write closing SGML tags
2689 switch (style.latextype) {
2692 case LATEX_ENVIRONMENT:
2693 case LATEX_ITEM_ENVIRONMENT:
2694 if (style.latexparam() == "CDATA")
2698 sgmlCloseTag(ofs, depth, style.latexname());
2704 for (int i=depth; i >= 0; --i)
2705 sgmlCloseTag(ofs, depth, environment_stack[i]);
2709 sgmlCloseTag(ofs, 0, top_element);
2713 // How to check for successful close
2717 // checks, if newcol chars should be put into this line
2718 // writes newline, if necessary.
2721 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2722 string::size_type newcol)
2725 if (colcount > lyxrc.ascii_linelen) {
2727 colcount = newcol; // assume write after this call
2742 string tag_name(PAR_TAG const & pt) {
2744 case NONE: return "!-- --";
2745 case TT: return "tt";
2746 case SF: return "sf";
2747 case BF: return "bf";
2748 case IT: return "it";
2749 case SL: return "sl";
2750 case EM: return "em";
2757 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2759 p1 = static_cast<PAR_TAG>(p1 | p2);
2764 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2766 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2772 // Handle internal paragraph parsing -- layout already processed.
2773 void Buffer::simpleLinuxDocOnePar(ostream & os,
2775 Paragraph::depth_type /*depth*/)
2777 LyXLayout const & style = textclasslist.Style(params.textclass,
2779 string::size_type char_line_count = 5; // Heuristic choice ;-)
2781 // gets paragraph main font
2784 if (style.labeltype == LABEL_MANUAL) {
2785 font_old = style.labelfont;
2788 font_old = style.font;
2792 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2793 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2794 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2797 stack<PAR_TAG> tag_state;
2798 // parsing main loop
2799 for (pos_type i = 0; i < par->size(); ++i) {
2801 PAR_TAG tag_close = NONE;
2802 list < PAR_TAG > tag_open;
2804 LyXFont const font = par->getFont(params, i);
2806 if (font_old.family() != font.family()) {
2807 switch (family_type) {
2808 case LyXFont::SANS_FAMILY:
2811 case LyXFont::TYPEWRITER_FAMILY:
2818 family_type = font.family();
2820 switch (family_type) {
2821 case LyXFont::SANS_FAMILY:
2822 tag_open.push_back(SF);
2824 case LyXFont::TYPEWRITER_FAMILY:
2825 tag_open.push_back(TT);
2832 if (font_old.series() != font.series()) {
2833 switch (series_type) {
2834 case LyXFont::BOLD_SERIES:
2841 series_type = font.series();
2843 switch (series_type) {
2844 case LyXFont::BOLD_SERIES:
2845 tag_open.push_back(BF);
2853 if (font_old.shape() != font.shape()) {
2854 switch (shape_type) {
2855 case LyXFont::ITALIC_SHAPE:
2858 case LyXFont::SLANTED_SHAPE:
2865 shape_type = font.shape();
2867 switch (shape_type) {
2868 case LyXFont::ITALIC_SHAPE:
2869 tag_open.push_back(IT);
2871 case LyXFont::SLANTED_SHAPE:
2872 tag_open.push_back(SL);
2879 if (font_old.emph() != font.emph()) {
2880 if (font.emph() == LyXFont::ON) {
2881 tag_open.push_back(EM);
2890 list < PAR_TAG > temp;
2891 while(!tag_state.empty() && tag_close ) {
2892 PAR_TAG k = tag_state.top();
2894 os << "</" << tag_name(k) << ">";
2901 for(list< PAR_TAG >::const_iterator j = temp.begin();
2902 j != temp.end(); ++j) {
2904 os << "<" << tag_name(*j) << ">";
2907 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2908 j != tag_open.end(); ++j) {
2910 os << "<" << tag_name(*j) << ">";
2913 char c = par->getChar(i);
2915 if (c == Paragraph::META_INSET) {
2916 Inset * inset = par->getInset(i);
2917 inset->linuxdoc(this, os);
2922 if (style.latexparam() == "CDATA") {
2923 // "TeX"-Mode on == > SGML-Mode on.
2929 if (par->sgmlConvertChar(c, sgml_string)
2930 && !style.free_spacing) {
2931 // in freespacing mode, spaces are
2932 // non-breaking characters
2933 if (desc_on) {// if char is ' ' then...
2936 sgmlLineBreak(os, char_line_count, 6);
2940 sgmlLineBreak(os, char_line_count, 1);
2945 char_line_count += sgml_string.length();
2951 while (!tag_state.empty()) {
2952 os << "</" << tag_name(tag_state.top()) << ">";
2956 // resets description flag correctly
2958 // <tag> not closed...
2959 sgmlLineBreak(os, char_line_count, 6);
2965 // Print an error message.
2966 void Buffer::sgmlError(Paragraph * par, int pos,
2967 string const & message) const
2969 // insert an error marker in text
2970 InsetError * new_inset = new InsetError(message);
2971 par->insertInset(pos, new_inset);
2972 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT, params.language));
2976 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2978 ofstream ofs(fname.c_str());
2980 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2984 Paragraph * par = paragraph;
2986 niceFile = nice; // this will be used by Insetincludes.
2988 LyXTextClass const & tclass =
2989 textclasslist.TextClass(params.textclass);
2991 LaTeXFeatures features(params, tclass.numLayouts());
2996 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2999 ofs << "<!DOCTYPE " << top_element
3000 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3002 string preamble = params.preamble;
3003 preamble += features.getIncludedFiles(fname);
3004 preamble += features.getLyXSGMLEntities();
3006 if (!preamble.empty()) {
3007 ofs << "\n [ " << preamble << " ]";
3012 string top = top_element;
3014 top += params.language->code();
3017 if (!params.options.empty()) {
3019 top += params.options;
3021 sgmlOpenTag(ofs, 0, top);
3023 ofs << "<!-- DocBook file was created by " << lyx_docversion
3024 << "\n See http://www.lyx.org/ for more information -->\n";
3026 vector<string> environment_stack(10);
3027 vector<string> environment_inner(10);
3028 vector<string> command_stack(10);
3030 bool command_flag = false;
3031 Paragraph::depth_type command_depth = 0;
3032 Paragraph::depth_type command_base = 0;
3033 Paragraph::depth_type cmd_depth = 0;
3034 Paragraph::depth_type depth = 0; // paragraph depth
3037 string command_name;
3043 int desc_on = 0; // description mode
3045 LyXLayout const & style =
3046 textclasslist.Style(params.textclass,
3049 // environment tag closing
3050 for (; depth > par->params().depth(); --depth) {
3051 if (environment_inner[depth] != "!-- --") {
3052 item_name = "listitem";
3053 sgmlCloseTag(ofs, command_depth + depth,
3055 if (environment_inner[depth] == "varlistentry")
3056 sgmlCloseTag(ofs, depth+command_depth,
3057 environment_inner[depth]);
3059 sgmlCloseTag(ofs, depth + command_depth,
3060 environment_stack[depth]);
3061 environment_stack[depth].erase();
3062 environment_inner[depth].erase();
3065 if (depth == par->params().depth()
3066 && environment_stack[depth] != style.latexname()
3067 && !environment_stack[depth].empty()) {
3068 if (environment_inner[depth] != "!-- --") {
3069 item_name= "listitem";
3070 sgmlCloseTag(ofs, command_depth+depth,
3072 if (environment_inner[depth] == "varlistentry")
3074 depth + command_depth,
3075 environment_inner[depth]);
3078 sgmlCloseTag(ofs, depth + command_depth,
3079 environment_stack[depth]);
3081 environment_stack[depth].erase();
3082 environment_inner[depth].erase();
3085 // Write opening SGML tags.
3086 switch (style.latextype) {
3087 case LATEX_PARAGRAPH:
3088 sgmlOpenTag(ofs, depth + command_depth,
3095 _("Error : Wrong depth for "
3096 "LatexType Command.\n"));
3098 command_name = style.latexname();
3100 sgmlparam = style.latexparam();
3101 c_params = split(sgmlparam, c_depth,'|');
3103 cmd_depth = lyx::atoi(c_depth);
3106 if (cmd_depth < command_base) {
3107 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3108 sgmlCloseTag(ofs, j, command_stack[j]);
3109 command_depth = command_base = cmd_depth;
3110 } else if (cmd_depth <= command_depth) {
3111 for (int j = command_depth; j >= int(cmd_depth); --j)
3112 sgmlCloseTag(ofs, j, command_stack[j]);
3113 command_depth = cmd_depth;
3115 command_depth = cmd_depth;
3117 command_depth = command_base = cmd_depth;
3118 command_flag = true;
3120 if (command_stack.size() == command_depth + 1)
3121 command_stack.push_back(string());
3122 command_stack[command_depth] = command_name;
3124 // treat label as a special case for
3125 // more WYSIWYM handling.
3126 if (par->isInset(0)) {
3127 Inset * inset = par->getInset(0);
3128 Inset::Code lyx_code = inset->lyxCode();
3129 if (lyx_code == Inset::LABEL_CODE){
3130 command_name += " id=\"";
3131 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3132 command_name += "\"";
3137 sgmlOpenTag(ofs, depth + command_depth, command_name);
3138 if (c_params.empty())
3139 item_name = "title";
3141 item_name = c_params;
3142 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3145 case LATEX_ENVIRONMENT:
3146 case LATEX_ITEM_ENVIRONMENT:
3147 if (depth < par->params().depth()) {
3148 depth = par->params().depth();
3149 environment_stack[depth].erase();
3152 if (environment_stack[depth] != style.latexname()) {
3153 if(environment_stack.size() == depth + 1) {
3154 environment_stack.push_back("!-- --");
3155 environment_inner.push_back("!-- --");
3157 environment_stack[depth] = style.latexname();
3158 environment_inner[depth] = "!-- --";
3159 sgmlOpenTag(ofs, depth + command_depth,
3160 environment_stack[depth]);
3162 if (environment_inner[depth] != "!-- --") {
3163 item_name= "listitem";
3165 command_depth + depth,
3167 if (environment_inner[depth] == "varlistentry")
3169 depth + command_depth,
3170 environment_inner[depth]);
3174 if (style.latextype == LATEX_ENVIRONMENT) {
3175 if (!style.latexparam().empty()) {
3176 if(style.latexparam() == "CDATA")
3179 sgmlOpenTag(ofs, depth + command_depth,
3180 style.latexparam());
3185 desc_on = (style.labeltype == LABEL_MANUAL);
3188 environment_inner[depth]= "varlistentry";
3190 environment_inner[depth]= "listitem";
3192 sgmlOpenTag(ofs, depth + 1 + command_depth,
3193 environment_inner[depth]);
3197 sgmlOpenTag(ofs, depth + 1 + command_depth,
3201 sgmlOpenTag(ofs, depth + 1 + command_depth,
3206 sgmlOpenTag(ofs, depth + command_depth,
3211 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3215 // write closing SGML tags
3216 switch (style.latextype) {
3218 if (c_params.empty())
3222 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3224 case LATEX_ENVIRONMENT:
3225 if (!style.latexparam().empty()) {
3226 if(style.latexparam() == "CDATA")
3229 sgmlCloseTag(ofs, depth + command_depth,
3230 style.latexparam());
3233 case LATEX_ITEM_ENVIRONMENT:
3234 if (desc_on == 1) break;
3236 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3238 case LATEX_PARAGRAPH:
3239 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3242 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3248 for (int d = depth; d >= 0; --d) {
3249 if (!environment_stack[depth].empty()) {
3250 if (environment_inner[depth] != "!-- --") {
3251 item_name = "listitem";
3252 sgmlCloseTag(ofs, command_depth + depth,
3254 if (environment_inner[depth] == "varlistentry")
3255 sgmlCloseTag(ofs, depth + command_depth,
3256 environment_inner[depth]);
3259 sgmlCloseTag(ofs, depth + command_depth,
3260 environment_stack[depth]);
3264 for (int j = command_depth; j >= 0 ; --j)
3265 if (!command_stack[j].empty())
3266 sgmlCloseTag(ofs, j, command_stack[j]);
3269 sgmlCloseTag(ofs, 0, top_element);
3272 // How to check for successful close
3276 void Buffer::simpleDocBookOnePar(ostream & os,
3277 Paragraph * par, int & desc_on,
3278 Paragraph::depth_type depth) const
3280 bool emph_flag = false;
3282 LyXLayout const & style = textclasslist.Style(params.textclass,
3285 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3287 int char_line_count = depth;
3288 //if (!style.free_spacing)
3289 // os << string(depth,' ');
3291 // parsing main loop
3292 for (pos_type i = 0; i < par->size(); ++i) {
3293 LyXFont font = par->getFont(params, i);
3295 // handle <emphasis> tag
3296 if (font_old.emph() != font.emph()) {
3297 if (font.emph() == LyXFont::ON) {
3301 os << "</emphasis>";
3306 char c = par->getChar(i);
3308 if (c == Paragraph::META_INSET) {
3309 Inset * inset = par->getInset(i);
3310 inset->docbook(this, os);
3313 par->sgmlConvertChar(c, sgml_string);
3315 if (style.pass_thru) {
3317 } else if(style.free_spacing || c != ' ') {
3319 } else if (desc_on ==1) {
3321 os << "\n</term><listitem><para>";
3331 os << "</emphasis>";
3334 // resets description flag correctly
3336 // <term> not closed...
3339 if(style.free_spacing) os << '\n';
3343 // This should be enabled when the Chktex class is implemented. (Asger)
3344 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3345 // Other flags: -wall -v0 -x
3346 int Buffer::runChktex()
3348 if (!users->text) return 0;
3350 users->owner()->prohibitInput();
3352 // get LaTeX-Filename
3353 string const name = getLatexName();
3354 string path = OnlyPath(filename);
3356 string const org_path = path;
3357 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3361 Path p(path); // path to LaTeX file
3362 users->owner()->message(_("Running chktex..."));
3364 // Remove all error insets
3365 bool const removedErrorInsets = users->removeAutoInsets();
3367 // Generate the LaTeX file if neccessary
3368 makeLaTeXFile(name, org_path, false);
3371 Chktex chktex(lyxrc.chktex_command, name, filepath);
3372 int res = chktex.run(terr); // run chktex
3375 Alert::alert(_("chktex did not work!"),
3376 _("Could not run with file:"), name);
3377 } else if (res > 0) {
3378 // Insert all errors as errors boxes
3379 users->insertErrors(terr);
3382 // if we removed error insets before we ran chktex or if we inserted
3383 // error insets after we ran chktex, this must be run:
3384 if (removedErrorInsets || res){
3388 users->owner()->allowInput();
3394 void Buffer::validate(LaTeXFeatures & features) const
3396 Paragraph * par = paragraph;
3397 LyXTextClass const & tclass =
3398 textclasslist.TextClass(params.textclass);
3400 // AMS Style is at document level
3401 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3402 features.require("amsstyle");
3405 // We don't use "lyxerr.debug" because of speed. (Asger)
3406 if (lyxerr.debugging(Debug::LATEX))
3407 lyxerr << "Paragraph: " << par << endl;
3409 // Now just follow the list of paragraphs and run
3410 // validate on each of them.
3411 par->validate(features);
3413 // and then the next paragraph
3417 // the bullet shapes are buffer level not paragraph level
3418 // so they are tested here
3419 for (int i = 0; i < 4; ++i) {
3420 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3421 int const font = params.user_defined_bullets[i].getFont();
3423 int const c = params
3424 .user_defined_bullets[i]
3431 features.require("latexsym");
3433 } else if (font == 1) {
3434 features.require("amssymb");
3435 } else if ((font >= 2 && font <= 5)) {
3436 features.require("pifont");
3441 if (lyxerr.debugging(Debug::LATEX)) {
3442 features.showStruct();
3447 // This function should be in Buffer because it's a buffer's property (ale)
3448 string const Buffer::getIncludeonlyList(char delim)
3451 for (inset_iterator it = inset_iterator_begin();
3452 it != inset_iterator_end(); ++it) {
3453 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3454 InsetInclude * insetinc =
3455 static_cast<InsetInclude *>(*it);
3456 if (insetinc->isIncludeOnly()) {
3459 lst += insetinc->getRelFileBaseName();
3463 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3468 vector<string> const Buffer::getLabelList()
3470 /// if this is a child document and the parent is already loaded
3471 /// Use the parent's list instead [ale990407]
3472 if (!params.parentname.empty()
3473 && bufferlist.exists(params.parentname)) {
3474 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3476 return tmp->getLabelList();
3479 vector<string> label_list;
3480 for (inset_iterator it = inset_iterator_begin();
3481 it != inset_iterator_end(); ++it) {
3482 vector<string> const l = (*it)->getLabelList();
3483 label_list.insert(label_list.end(), l.begin(), l.end());
3489 Buffer::Lists const Buffer::getLists() const
3492 Paragraph * par = paragraph;
3495 std::pair<bool, LyXTextClassList::size_type> const tmp =
3496 textclasslist.NumberOfLayout(params.textclass, "Caption");
3497 bool const found = tmp.first;
3498 LyXTextClassList::size_type const cap = tmp.second;
3501 // This is the prefered way to to this, but boost::tie can break
3504 LyXTextClassList::size_type cap;
3505 boost::tie(found, cap) = textclasslist
3506 .NumberOfLayout(params.textclass, "Caption");
3510 char const labeltype =
3511 textclasslist.Style(params.textclass,
3512 par->getLayout()).labeltype;
3514 if (labeltype >= LABEL_COUNTER_CHAPTER
3515 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3516 // insert this into the table of contents
3517 SingleList & item = l["TOC"];
3520 textclasslist.TextClass(params.textclass).maxcounter());
3521 item.push_back(TocItem(par, depth, par->asString(this, true)));
3523 // For each paragrph, traverse its insets and look for
3527 Paragraph::inset_iterator it =
3528 par->inset_iterator_begin();
3529 Paragraph::inset_iterator end =
3530 par->inset_iterator_end();
3532 for (; it != end; ++it) {
3533 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3535 static_cast<InsetFloat*>(*it);
3537 string const type = il->type();
3539 // Now find the caption in the float...
3540 // We now tranverse the paragraphs of
3542 Paragraph * tmp = il->inset.paragraph();
3544 if (tmp->layout == cap) {
3545 SingleList & item = l[type];
3547 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3548 item.push_back(TocItem(tmp, 0 , str));
3555 lyxerr << "caption not found" << endl;
3564 // This is also a buffer property (ale)
3565 vector<pair<string, string> > const Buffer::getBibkeyList()
3567 /// if this is a child document and the parent is already loaded
3568 /// Use the parent's list instead [ale990412]
3569 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3570 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3572 return tmp->getBibkeyList();
3575 vector<pair<string, string> > keys;
3576 Paragraph * par = paragraph;
3579 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3580 par->asString(this, false)));
3584 // Might be either using bibtex or a child has bibliography
3586 for (inset_iterator it = inset_iterator_begin();
3587 it != inset_iterator_end(); ++it) {
3588 // Search for Bibtex or Include inset
3589 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3590 vector<pair<string,string> > tmp =
3591 static_cast<InsetBibtex*>(*it)->getKeys(this);
3592 keys.insert(keys.end(), tmp.begin(), tmp.end());
3593 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3594 vector<pair<string,string> > const tmp =
3595 static_cast<InsetInclude*>(*it)->getKeys();
3596 keys.insert(keys.end(), tmp.begin(), tmp.end());
3605 bool Buffer::isDepClean(string const & name) const
3607 DEPCLEAN * item = dep_clean;
3608 while (item && item->master != name)
3610 if (!item) return true;
3615 void Buffer::markDepClean(string const & name)
3618 dep_clean = new DEPCLEAN;
3619 dep_clean->clean = true;
3620 dep_clean->master = name;
3621 dep_clean->next = 0;
3623 DEPCLEAN * item = dep_clean;
3624 while (item && item->master != name)
3629 item = new DEPCLEAN;
3631 item->master = name;
3638 bool Buffer::dispatch(string const & command)
3640 // Split command string into command and argument
3642 string line = frontStrip(command);
3643 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3645 return dispatch(lyxaction.LookupFunc(cmd), arg);
3649 bool Buffer::dispatch(int action, string const & argument)
3651 bool dispatched = true;
3654 Exporter::Export(this, argument, false);
3664 void Buffer::resizeInsets(BufferView * bv)
3666 /// then remove all LyXText in text-insets
3667 Paragraph * par = paragraph;
3668 for (; par; par = par->next()) {
3669 par->resizeInsetsLyXText(bv);
3674 void Buffer::redraw()
3681 void Buffer::changeLanguage(Language const * from, Language const * to)
3684 ParIterator end = par_iterator_end();
3685 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3686 (*it)->changeLanguage(params, from, to);
3690 bool Buffer::isMultiLingual()
3692 ParIterator end = par_iterator_end();
3693 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3694 if ((*it)->isMultiLingual(params))
3701 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3704 it = par->InsetIterator(pos);
3705 if (it == par->inset_iterator_end()) {
3712 void Buffer::inset_iterator::setParagraph()
3715 it = par->inset_iterator_begin();
3716 if (it != par->inset_iterator_end())
3721 // We maintain an invariant that whenever par = 0 then it = 0
3725 Inset * Buffer::getInsetFromID(int id_arg) const
3727 for (inset_iterator it = inset_const_iterator_begin();
3728 it != inset_const_iterator_end(); ++it)
3730 if ((*it)->id() == id_arg)
3732 Inset * in = (*it)->getInsetFromID(id_arg);
3740 Paragraph * Buffer::getParFromID(int id) const
3742 if (id < 0) return 0;
3743 Paragraph * par = paragraph;
3745 if (par->id() == id) {
3748 Paragraph * tmp = par->getParFromID(id);
3758 ParIterator Buffer::par_iterator_begin()
3760 return ParIterator(paragraph);
3764 ParIterator Buffer::par_iterator_end()
3766 return ParIterator();