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;
126 // all these externs should eventually be removed.
127 extern BufferList bufferlist;
129 extern LyXAction lyxaction;
133 const int LYX_FORMAT = 220;
137 extern int tex_code_break_column;
140 Buffer::Buffer(string const & file, bool ronly)
142 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
144 filepath = OnlyPath(file);
153 if (read_only || (lyxrc.use_tempdir)) {
154 tmppath = CreateBufferTmpDir();
155 } else tmppath.erase();
161 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
162 // here the buffer should take care that it is
163 // saved properly, before it goes into the void.
165 // make sure that views using this buffer
170 if (!tmppath.empty()) {
171 DestroyBufferTmpDir(tmppath);
174 Paragraph * par = paragraph;
177 tmppar = par->next();
185 string const Buffer::getLatexName(bool no_path) const
187 string name = ChangeExtension(MakeLatexName(filename), ".tex");
189 return OnlyFilename(name);
195 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
197 string const filename = getLatexName(false);
199 if (filename.empty())
200 return make_pair(Buffer::latexlog, string());
202 string path = OnlyPath(filename);
204 if (lyxrc.use_tempdir || !IsDirWriteable(path))
207 string const fname = AddName(path,
208 OnlyFilename(ChangeExtension(filename,
211 AddName(path, OnlyFilename(
212 ChangeExtension(filename,
213 formats.extension("literate") + ".out")));
215 // If no Latex log or Build log is newer, show Build log
217 FileInfo const f_fi(fname);
218 FileInfo const b_fi(bname);
221 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
222 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
223 return make_pair(Buffer::buildlog, bname);
225 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
226 return make_pair(Buffer::latexlog, fname);
230 void Buffer::setReadonly(bool flag)
232 if (read_only != flag) {
235 users->owner()->getDialogs()->updateBufferDependent(false);
240 /// Update window titles of all users
241 // Should work on a list
242 void Buffer::updateTitles() const
244 if (users) users->owner()->updateWindowTitle();
248 /// Reset autosave timer of all users
249 // Should work on a list
250 void Buffer::resetAutosaveTimers() const
252 if (users) users->owner()->resetAutosaveTimer();
256 void Buffer::setFileName(string const & newfile)
258 filename = MakeAbsPath(newfile);
259 filepath = OnlyPath(filename);
260 setReadonly(IsFileWriteable(filename) == 0);
265 // We'll remove this later. (Lgb)
268 string last_inset_read;
270 #ifndef NO_COMPABILITY
273 ErtComp() : active(false), in_tabular(false) {
280 std::stack<ErtComp> ert_stack;
284 #warning And _why_ is this here? (Lgb)
291 // candidate for move to BufferView
292 // (at least some parts in the beginning of the func)
295 // changed to be public and have one parameter
296 // if par = 0 normal behavior
297 // else insert behavior
298 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
299 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
303 #ifndef NO_COMPABILITY
304 ert_comp.contents.erase();
305 ert_comp.active = false;
306 ert_comp.in_tabular = false;
309 Paragraph::depth_type depth = 0;
310 bool the_end_read = false;
312 Paragraph * first_par = 0;
313 LyXFont font(LyXFont::ALL_INHERIT, params.language);
314 if (file_format < 216 && params.language->lang() == "hebrew")
315 font.setLanguage(default_language);
320 // We are inserting into an existing document
321 users->text->breakParagraph(users);
322 first_par = users->text->firstParagraph();
325 // We don't want to adopt the parameters from the
326 // document we insert, so we skip until the text begins:
329 string const pretoken = lex.getString();
330 if (pretoken == "\\layout") {
331 lex.pushToken(pretoken);
339 string const token = lex.getString();
341 if (token.empty()) continue;
343 lyxerr[Debug::PARSER] << "Handling token: `"
344 << token << "'" << endl;
347 parseSingleLyXformat2Token(lex, par, first_par,
355 paragraph = first_par;
357 if (unknown_layouts > 0) {
358 string s = _("Couldn't set the layout for ");
359 if (unknown_layouts == 1) {
360 s += _("one paragraph");
362 s += tostr(unknown_layouts);
363 s += _(" paragraphs");
365 Alert::alert(_("Textclass Loading Error!"), s,
366 _("When reading " + fileName()));
369 if (unknown_tokens > 0) {
370 string s = _("Encountered ");
371 if (unknown_tokens == 1) {
372 s += _("one unknown token");
374 s += tostr(unknown_tokens);
375 s += _(" unknown tokens");
377 Alert::alert(_("Textclass Loading Error!"), s,
378 _("When reading " + fileName()));
385 #ifndef NO_COMPABILITY
386 void Buffer::insertErtContents(Paragraph * par, int & pos,
387 LyXFont const & font, bool set_inactive)
389 if (!ert_comp.contents.empty()) {
390 lyxerr[Debug::INSETS] << "ERT contents:\n"
391 << ert_comp.contents << endl;
392 Inset * inset = new InsetERT(ert_comp.contents, true);
393 par->insertInset(pos++, inset, font);
394 ert_comp.contents.erase();
397 ert_comp.active = false;
404 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
405 Paragraph *& first_par,
406 string const & token, int & pos,
407 Paragraph::depth_type & depth,
411 bool the_end_read = false;
412 #ifndef NO_COMPABILITY
413 #ifndef NO_PEXTRA_REALLY
414 // This is super temporary but is needed to get the compability
415 // mode for minipages work correctly together with new tabulars.
416 static int call_depth;
418 bool checkminipage = false;
419 static Paragraph * minipar;
420 static Paragraph * parBeforeMinipage;
423 if (token[0] != '\\') {
424 #ifndef NO_COMPABILITY
425 if (ert_comp.active) {
426 ert_comp.contents += token;
429 for (string::const_iterator cit = token.begin();
430 cit != token.end(); ++cit) {
431 par->insertChar(pos, (*cit), font);
434 #ifndef NO_COMPABILITY
437 } else if (token == "\\i") {
438 Inset * inset = new InsetLatexAccent;
439 inset->read(this, lex);
440 par->insertInset(pos, inset, font);
442 } else if (token == "\\layout") {
443 #ifndef NO_COMPABILITY
444 ert_comp.in_tabular = false;
446 insertErtContents(par, pos, font);
449 string const layoutname = lex.getString();
450 pair<bool, LyXTextClass::LayoutList::size_type> pp
451 = textclasslist.NumberOfLayout(params.textclass,
454 #ifndef NO_COMPABILITY
455 if (compare_no_case(layoutname, "latex") == 0) {
456 ert_comp.active = true;
460 // The is the compability reading of layout caption.
461 // It can be removed in LyX version 1.3.0. (Lgb)
462 if (compare_no_case(layoutname, "caption") == 0) {
463 // We expect that the par we are now working on is
464 // really inside a InsetText inside a InsetFloat.
465 // We also know that captions can only be
466 // one paragraph. (Lgb)
468 // We should now read until the next "\layout"
470 // This is probably not good enough, what if the
471 // caption is the last par in the document (Lgb)
472 istream & ist = lex.getStream();
478 if (prefixIs(line, "\\layout")) {
482 if (prefixIs(line, "\\begin_inset"))
484 if (prefixIs(line, "\\end_inset")) {
495 // Now we should have the whole layout in ss
496 // we should now be able to give this to the
498 ss << "\\end_inset\n";
500 // This seems like a bug in stringstream.
501 // We really should be able to use ss
503 istringstream is(ss.str());
505 tmplex.setStream(is);
506 Inset * inset = new InsetCaption;
507 inset->Read(this, tmplex);
508 par->InsertInset(pos, inset, font);
515 par = new Paragraph(par);
519 par->layout = pp.second;
520 #ifndef NO_COMPABILITY
521 } else if (ert_comp.active) {
526 // use default layout "Standard" (0)
529 string const s = _("Layout had to be changed from\n")
530 + layoutname + _(" to ")
531 + textclasslist.NameOfLayout(params.textclass, par->layout);
532 InsetError * new_inset = new InsetError(s);
533 par->insertInset(0, new_inset);
534 par->setFont(0, LyXFont(LyXFont::ALL_INHERIT,
537 // Test whether the layout is obsolete.
538 LyXLayout const & layout =
539 textclasslist.Style(params.textclass,
541 if (!layout.obsoleted_by().empty())
542 par->layout = textclasslist
543 .NumberOfLayout(params.textclass,
544 layout.obsoleted_by())
546 par->params().depth(depth);
547 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
548 if (file_format < 216
549 && params.language->lang() == "hebrew")
550 font.setLanguage(default_language);
555 #ifndef NO_COMPABILITY
556 } else if (token == "\\begin_float") {
557 insertErtContents(par, pos, font);
558 //insertErtContents(par, pos, font, false);
559 //ert_stack.push(ert_comp);
560 //ert_comp = ErtComp();
562 // This is the compability reader. It can be removed in
563 // LyX version 1.3.0. (Lgb)
565 string const tmptok = lex.getString();
566 //lyxerr << "old float: " << tmptok << endl;
569 stringstream old_float;
571 if (tmptok == "footnote") {
572 inset = new InsetFoot;
573 old_float << "collapsed true\n";
574 } else if (tmptok == "margin") {
575 inset = new InsetMarginal;
576 old_float << "collapsed true\n";
577 } else if (tmptok == "fig") {
578 inset = new InsetFloat("figure");
579 old_float << "placement htbp\n"
581 << "collapsed false\n";
582 } else if (tmptok == "tab") {
583 inset = new InsetFloat("table");
584 old_float << "placement htbp\n"
586 << "collapsed false\n";
587 } else if (tmptok == "alg") {
588 inset = new InsetFloat("algorithm");
589 old_float << "placement htbp\n"
591 << "collapsed false\n";
592 } else if (tmptok == "wide-fig") {
593 inset = new InsetFloat("figure");
594 //InsetFloat * tmp = new InsetFloat("figure");
597 old_float << "placement htbp\n"
599 << "collapsed false\n";
600 } else if (tmptok == "wide-tab") {
601 inset = new InsetFloat("table");
602 //InsetFloat * tmp = new InsetFloat("table");
605 old_float << "placement htbp\n"
607 << "collapsed false\n";
611 #ifndef NO_PEXTRA_REALLY
614 return false; // no end read yet
617 // Here we need to check for \end_deeper and handle that
618 // before we do the footnote parsing.
619 // This _is_ a hack! (Lgb)
622 string const tmp = lex.getString();
623 if (tmp == "\\end_deeper") {
624 //lyxerr << "\\end_deeper caught!" << endl;
626 lex.printError("\\end_deeper: "
627 "depth is already null");
632 old_float << tmp << ' ';
637 old_float << lex.getLongString("\\end_float")
638 << "\n\\end_inset\n";
639 //lyxerr << "Float Body:\n" << old_float.str() << endl;
640 // That this does not work seems like a bug
641 // in stringstream. (Lgb)
642 istringstream istr(old_float.str());
644 nylex.setStream(istr);
645 inset->read(this, nylex);
646 par->insertInset(pos, inset, font);
648 insertErtContents(par, pos, font);
650 } else if (token == "\\begin_deeper") {
652 } else if (token == "\\end_deeper") {
654 lex.printError("\\end_deeper: "
655 "depth is already null");
659 } else if (token == "\\begin_preamble") {
660 params.readPreamble(lex);
661 } else if (token == "\\textclass") {
663 pair<bool, LyXTextClassList::size_type> pp =
664 textclasslist.NumberOfClass(lex.getString());
666 params.textclass = pp.second;
668 Alert::alert(string(_("Textclass error")),
669 string(_("The document uses an unknown textclass \"")) +
670 lex.getString() + string("\"."),
671 string(_("LyX will not be able to produce output correctly.")));
672 params.textclass = 0;
674 if (!textclasslist.Load(params.textclass)) {
675 // if the textclass wasn't loaded properly
676 // we need to either substitute another
677 // or stop loading the file.
678 // I can substitute but I don't see how I can
679 // stop loading... ideas?? ARRae980418
680 Alert::alert(_("Textclass Loading Error!"),
681 string(_("Can't load textclass ")) +
682 textclasslist.NameOfClass(params.textclass),
683 _("-- substituting default"));
684 params.textclass = 0;
686 } else if (token == "\\options") {
688 params.options = lex.getString();
689 } else if (token == "\\language") {
690 params.readLanguage(lex);
691 } else if (token == "\\fontencoding") {
693 } else if (token == "\\inputencoding") {
695 params.inputenc = lex.getString();
696 } else if (token == "\\graphics") {
697 params.readGraphicsDriver(lex);
698 } else if (token == "\\fontscheme") {
700 params.fonts = lex.getString();
701 } else if (token == "\\noindent") {
702 par->params().noindent(true);
703 } else if (token == "\\fill_top") {
704 par->params().spaceTop(VSpace(VSpace::VFILL));
705 } else if (token == "\\fill_bottom") {
706 par->params().spaceBottom(VSpace(VSpace::VFILL));
707 } else if (token == "\\line_top") {
708 par->params().lineTop(true);
709 } else if (token == "\\line_bottom") {
710 par->params().lineBottom(true);
711 } else if (token == "\\pagebreak_top") {
712 par->params().pagebreakTop(true);
713 } else if (token == "\\pagebreak_bottom") {
714 par->params().pagebreakBottom(true);
715 } else if (token == "\\start_of_appendix") {
716 par->params().startOfAppendix(true);
717 } else if (token == "\\paragraph_separation") {
718 int tmpret = lex.findToken(string_paragraph_separation);
719 if (tmpret == -1) ++tmpret;
720 if (tmpret != LYX_LAYOUT_DEFAULT)
721 params.paragraph_separation =
722 static_cast<BufferParams::PARSEP>(tmpret);
723 } else if (token == "\\defskip") {
725 params.defskip = VSpace(lex.getString());
726 } else if (token == "\\epsfig") { // obsolete
727 // Indeed it is obsolete, but we HAVE to be backwards
728 // compatible until 0.14, because otherwise all figures
729 // in existing documents are irretrivably lost. (Asger)
730 params.readGraphicsDriver(lex);
731 } else if (token == "\\quotes_language") {
732 int tmpret = lex.findToken(string_quotes_language);
733 if (tmpret == -1) ++tmpret;
734 if (tmpret != LYX_LAYOUT_DEFAULT) {
735 InsetQuotes::quote_language tmpl =
736 InsetQuotes::EnglishQ;
739 tmpl = InsetQuotes::EnglishQ;
742 tmpl = InsetQuotes::SwedishQ;
745 tmpl = InsetQuotes::GermanQ;
748 tmpl = InsetQuotes::PolishQ;
751 tmpl = InsetQuotes::FrenchQ;
754 tmpl = InsetQuotes::DanishQ;
757 params.quotes_language = tmpl;
759 } else if (token == "\\quotes_times") {
761 switch (lex.getInteger()) {
763 params.quotes_times = InsetQuotes::SingleQ;
766 params.quotes_times = InsetQuotes::DoubleQ;
769 } else if (token == "\\papersize") {
770 int tmpret = lex.findToken(string_papersize);
774 params.papersize2 = tmpret;
775 } else if (token == "\\paperpackage") {
776 int tmpret = lex.findToken(string_paperpackages);
779 params.paperpackage = BufferParams::PACKAGE_NONE;
781 params.paperpackage = tmpret;
782 } else if (token == "\\use_geometry") {
784 params.use_geometry = lex.getInteger();
785 } else if (token == "\\use_amsmath") {
787 params.use_amsmath = lex.getInteger();
788 } else if (token == "\\use_natbib") {
790 params.use_natbib = lex.getInteger();
791 } else if (token == "\\use_numerical_citations") {
793 params.use_numerical_citations = lex.getInteger();
794 } else if (token == "\\paperorientation") {
795 int tmpret = lex.findToken(string_orientation);
796 if (tmpret == -1) ++tmpret;
797 if (tmpret != LYX_LAYOUT_DEFAULT)
798 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
799 } else if (token == "\\paperwidth") {
801 params.paperwidth = lex.getString();
802 } else if (token == "\\paperheight") {
804 params.paperheight = lex.getString();
805 } else if (token == "\\leftmargin") {
807 params.leftmargin = lex.getString();
808 } else if (token == "\\topmargin") {
810 params.topmargin = lex.getString();
811 } else if (token == "\\rightmargin") {
813 params.rightmargin = lex.getString();
814 } else if (token == "\\bottommargin") {
816 params.bottommargin = lex.getString();
817 } else if (token == "\\headheight") {
819 params.headheight = lex.getString();
820 } else if (token == "\\headsep") {
822 params.headsep = lex.getString();
823 } else if (token == "\\footskip") {
825 params.footskip = lex.getString();
826 } else if (token == "\\paperfontsize") {
828 params.fontsize = strip(lex.getString());
829 } else if (token == "\\papercolumns") {
831 params.columns = lex.getInteger();
832 } else if (token == "\\papersides") {
834 switch (lex.getInteger()) {
836 case 1: params.sides = LyXTextClass::OneSide; break;
837 case 2: params.sides = LyXTextClass::TwoSides; break;
839 } else if (token == "\\paperpagestyle") {
841 params.pagestyle = strip(lex.getString());
842 } else if (token == "\\bullet") {
844 int const index = lex.getInteger();
846 int temp_int = lex.getInteger();
847 params.user_defined_bullets[index].setFont(temp_int);
848 params.temp_bullets[index].setFont(temp_int);
850 temp_int = lex.getInteger();
851 params.user_defined_bullets[index].setCharacter(temp_int);
852 params.temp_bullets[index].setCharacter(temp_int);
854 temp_int = lex.getInteger();
855 params.user_defined_bullets[index].setSize(temp_int);
856 params.temp_bullets[index].setSize(temp_int);
858 string const temp_str = lex.getString();
859 if (temp_str != "\\end_bullet") {
860 // this element isn't really necessary for
861 // parsing but is easier for humans
862 // to understand bullets. Put it back and
863 // set a debug message?
864 lex.printError("\\end_bullet expected, got" + temp_str);
865 //how can I put it back?
867 } else if (token == "\\bulletLaTeX") {
869 int const index = lex.getInteger();
871 string temp_str = lex.getString();
873 while (temp_str != "\\end_bullet") {
874 // this loop structure is needed when user
875 // enters an empty string since the first
876 // thing returned will be the \\end_bullet
878 // if the LaTeX entry has spaces. Each element
879 // therefore needs to be read in turn
882 temp_str = lex.getString();
884 params.user_defined_bullets[index].setText(sum_str);
885 params.temp_bullets[index].setText(sum_str);
886 } else if (token == "\\secnumdepth") {
888 params.secnumdepth = lex.getInteger();
889 } else if (token == "\\tocdepth") {
891 params.tocdepth = lex.getInteger();
892 } else if (token == "\\spacing") {
894 string const tmp = strip(lex.getString());
895 Spacing::Space tmp_space = Spacing::Default;
897 if (tmp == "single") {
898 tmp_space = Spacing::Single;
899 } else if (tmp == "onehalf") {
900 tmp_space = Spacing::Onehalf;
901 } else if (tmp == "double") {
902 tmp_space = Spacing::Double;
903 } else if (tmp == "other") {
905 tmp_space = Spacing::Other;
906 tmp_val = lex.getFloat();
908 lex.printError("Unknown spacing token: '$$Token'");
910 // Small hack so that files written with klyx will be
913 par->params().spacing(Spacing(tmp_space, tmp_val));
915 params.spacing.set(tmp_space, tmp_val);
917 } else if (token == "\\paragraph_spacing") {
919 string const tmp = strip(lex.getString());
920 if (tmp == "single") {
921 par->params().spacing(Spacing(Spacing::Single));
922 } else if (tmp == "onehalf") {
923 par->params().spacing(Spacing(Spacing::Onehalf));
924 } else if (tmp == "double") {
925 par->params().spacing(Spacing(Spacing::Double));
926 } else if (tmp == "other") {
928 par->params().spacing(Spacing(Spacing::Other,
931 lex.printError("Unknown spacing token: '$$Token'");
933 } else if (token == "\\float_placement") {
935 params.float_placement = lex.getString();
936 } else if (token == "\\family") {
938 font.setLyXFamily(lex.getString());
939 } else if (token == "\\series") {
941 font.setLyXSeries(lex.getString());
942 } else if (token == "\\shape") {
944 font.setLyXShape(lex.getString());
945 } else if (token == "\\size") {
947 font.setLyXSize(lex.getString());
948 #ifndef NO_COMPABILITY
949 } else if (token == "\\latex") {
951 string const tok = lex.getString();
952 if (tok == "no_latex") {
954 insertErtContents(par, pos, font);
955 } else if (tok == "latex") {
956 ert_comp.active = true;
957 } else if (tok == "default") {
959 insertErtContents(par, pos, font);
961 lex.printError("Unknown LaTeX font flag "
965 } else if (token == "\\lang") {
967 string const tok = lex.getString();
968 Language const * lang = languages.getLanguage(tok);
970 font.setLanguage(lang);
972 font.setLanguage(params.language);
973 lex.printError("Unknown language `$$Token'");
975 } else if (token == "\\numeric") {
977 font.setNumber(font.setLyXMisc(lex.getString()));
978 } else if (token == "\\emph") {
980 font.setEmph(font.setLyXMisc(lex.getString()));
981 } else if (token == "\\bar") {
983 string const tok = lex.getString();
984 // This is dirty, but gone with LyX3. (Asger)
986 font.setUnderbar(LyXFont::ON);
987 else if (tok == "no")
988 font.setUnderbar(LyXFont::OFF);
989 else if (tok == "default")
990 font.setUnderbar(LyXFont::INHERIT);
992 lex.printError("Unknown bar font flag "
994 } else if (token == "\\noun") {
996 font.setNoun(font.setLyXMisc(lex.getString()));
997 } else if (token == "\\color") {
999 font.setLyXColor(lex.getString());
1000 } else if (token == "\\align") {
1001 int tmpret = lex.findToken(string_align);
1002 if (tmpret == -1) ++tmpret;
1003 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1004 int const tmpret2 = int(pow(2.0, tmpret));
1005 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1006 par->params().align(LyXAlignment(tmpret2));
1008 } else if (token == "\\added_space_top") {
1010 par->params().spaceTop(VSpace(lex.getString()));
1011 } else if (token == "\\added_space_bottom") {
1013 par->params().spaceBottom(VSpace(lex.getString()));
1014 #ifndef NO_COMPABILITY
1015 #ifndef NO_PEXTRA_REALLY
1016 } else if (token == "\\pextra_type") {
1018 par->params().pextraType(lex.getInteger());
1019 } else if (token == "\\pextra_width") {
1021 par->params().pextraWidth(lex.getString());
1022 } else if (token == "\\pextra_widthp") {
1024 par->params().pextraWidthp(lex.getString());
1025 } else if (token == "\\pextra_alignment") {
1027 par->params().pextraAlignment(lex.getInteger());
1028 } else if (token == "\\pextra_hfill") {
1030 par->params().pextraHfill(lex.getInteger());
1031 } else if (token == "\\pextra_start_minipage") {
1033 par->params().pextraStartMinipage(lex.getInteger());
1036 } else if (token == "\\labelwidthstring") {
1038 par->params().labelWidthString(lex.getString());
1039 // do not delete this token, it is still needed!
1040 } else if (token == "\\end_inset") {
1041 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1042 << "Last inset read was: " << last_inset_read
1044 // Simply ignore this. The insets do not have
1046 // But insets should read it, it is a part of
1047 // the inset isn't it? Lgb.
1048 } else if (token == "\\begin_inset") {
1049 #ifndef NO_COMPABILITY
1050 insertErtContents(par, pos, font, false);
1051 ert_stack.push(ert_comp);
1052 ert_comp = ErtComp();
1054 readInset(lex, par, pos, font);
1055 #ifndef NO_COMPABILITY
1056 ert_comp = ert_stack.top();
1058 insertErtContents(par, pos, font);
1060 } else if (token == "\\SpecialChar") {
1061 LyXLayout const & layout =
1062 textclasslist.Style(params.textclass,
1065 // Insets don't make sense in a free-spacing context! ---Kayvan
1066 if (layout.free_spacing) {
1069 string next_token = lex.getString();
1070 if (next_token == "\\-") {
1071 par->insertChar(pos, '-', font);
1072 } else if (next_token == "\\protected_separator"
1073 || next_token == "~") {
1074 par->insertChar(pos, ' ', font);
1076 lex.printError("Token `$$Token' "
1078 "paragraph layout!");
1083 Inset * inset = new InsetSpecialChar;
1084 inset->read(this, lex);
1085 par->insertInset(pos, inset, font);
1088 } else if (token == "\\newline") {
1089 #ifndef NO_COMPABILITY
1090 if (!ert_comp.in_tabular && ert_comp.active) {
1091 ert_comp.contents += char(Paragraph::META_NEWLINE);
1093 // Since we cannot know it this is only a regular
1094 // newline or a tabular cell delimter we have to
1095 // handle the ERT here.
1096 insertErtContents(par, pos, font, false);
1098 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1102 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1105 } else if (token == "\\LyXTable") {
1106 #ifndef NO_COMPABILITY
1107 ert_comp.in_tabular = true;
1109 Inset * inset = new InsetTabular(*this);
1110 inset->read(this, lex);
1111 par->insertInset(pos, inset, font);
1113 } else if (token == "\\hfill") {
1114 par->insertChar(pos, Paragraph::META_HFILL, font);
1116 } else if (token == "\\protected_separator") { // obsolete
1117 // This is a backward compability thingie. (Lgb)
1118 // Remove it later some time...introduced with fileformat
1120 LyXLayout const & layout =
1121 textclasslist.Style(params.textclass,
1124 if (layout.free_spacing) {
1125 par->insertChar(pos, ' ', font);
1127 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1128 par->insertInset(pos, inset, font);
1131 } else if (token == "\\bibitem") { // ale970302
1133 InsetCommandParams p("bibitem", "dummy");
1134 par->bibkey = new InsetBibKey(p);
1136 par->bibkey->read(this, lex);
1137 } else if (token == "\\backslash") {
1138 #ifndef NO_COMPABILITY
1139 if (ert_comp.active) {
1140 ert_comp.contents += "\\";
1143 par->insertChar(pos, '\\', font);
1145 #ifndef NO_COMPABILITY
1148 } else if (token == "\\the_end") {
1149 #ifndef NO_COMPABILITY
1150 // If we still have some ert active here we have to insert
1151 // it so we don't loose it. (Lgb)
1152 insertErtContents(par, pos, font);
1154 the_end_read = true;
1155 #ifndef NO_COMPABILITY
1156 #ifndef NO_PEXTRA_REALLY
1157 minipar = parBeforeMinipage = 0;
1161 #ifndef NO_COMPABILITY
1162 if (ert_comp.active) {
1163 ert_comp.contents += token;
1166 // This should be insurance for the future: (Asger)
1169 string const s = _("Unknown token: ") + token
1170 + " " + lex.text() + "\n";
1172 InsetError * new_inset = new InsetError(s);
1173 par->insertInset(pos, new_inset);
1174 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT,
1177 #ifndef NO_COMPABILITY
1182 #ifndef NO_COMPABILITY
1183 #ifndef NO_PEXTRA_REALLY
1184 // I wonder if we could use this blanket fix for all the
1185 // checkminipage cases...
1186 if (par && par->size()) {
1187 // It is possible that this will check to often,
1188 // but that should not be an correctness issue.
1189 // Only a speed issue.
1190 checkminipage = true;
1193 // now check if we have a minipage paragraph as at this
1194 // point we already read all the necessary data!
1195 // this cannot be done in layout because there we did
1196 // not read yet the paragraph PEXTRA-params (Jug)
1198 // BEGIN pextra_minipage compability
1199 // This should be removed in 1.3.x (Lgb)
1201 // This compability code is not perfect. In a couple
1202 // of rand cases it fails. When the minipage par is
1203 // the first par in the document, and when there are
1204 // none or only one regular paragraphs after the
1205 // minipage. Currently I am not investing any effort
1206 // in fixing those cases.
1208 //lyxerr << "Call depth: " << call_depth << endl;
1209 if (checkminipage && (call_depth == 1)) {
1210 checkminipage = false;
1211 if (minipar && (minipar != par) &&
1212 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1214 lyxerr << "minipages in a row" << endl;
1215 if (par->params().pextraStartMinipage()) {
1216 lyxerr << "start new minipage" << endl;
1217 // minipages in a row
1218 par->previous()->next(0);
1221 Paragraph * tmp = minipar;
1223 tmp->params().pextraType(0);
1224 tmp->params().pextraWidth(string());
1225 tmp->params().pextraWidthp(string());
1226 tmp->params().pextraAlignment(0);
1227 tmp->params().pextraHfill(false);
1228 tmp->params().pextraStartMinipage(false);
1231 // create a new paragraph to insert the
1232 // minipages in the following case
1233 if (par->params().pextraStartMinipage() &&
1234 !par->params().pextraHfill())
1236 Paragraph * p = new Paragraph;
1238 p->previous(parBeforeMinipage);
1239 parBeforeMinipage->next(p);
1241 p->params().depth(parBeforeMinipage->params().depth());
1242 parBeforeMinipage = p;
1244 InsetMinipage * mini = new InsetMinipage;
1245 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1246 mini->width(par->params().pextraWidth());
1247 if (!par->params().pextraWidthp().empty()) {
1248 lyxerr << "WP:" << mini->width() << endl;
1249 mini->width(tostr(par->params().pextraWidthp())+"%");
1251 mini->inset.paragraph(par);
1252 // Insert the minipage last in the
1253 // previous paragraph.
1254 if (par->params().pextraHfill()) {
1255 parBeforeMinipage->insertChar
1256 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1258 parBeforeMinipage->insertInset
1259 (parBeforeMinipage->size(), mini);
1263 lyxerr << "new minipage par" << endl;
1264 //nothing to do just continue reading
1267 } else if (minipar && (minipar != par)) {
1268 lyxerr << "last minipage par read" << endl;
1269 // The last paragraph read was not part of a
1270 // minipage but the par linked list is...
1271 // So we need to remove the last par from the
1273 if (par->previous())
1274 par->previous()->next(0);
1275 par->previous(parBeforeMinipage);
1276 parBeforeMinipage->next(par);
1277 Paragraph * tmp = minipar;
1279 tmp->params().pextraType(0);
1280 tmp->params().pextraWidth(string());
1281 tmp->params().pextraWidthp(string());
1282 tmp->params().pextraAlignment(0);
1283 tmp->params().pextraHfill(false);
1284 tmp->params().pextraStartMinipage(false);
1287 depth = parBeforeMinipage->params().depth();
1288 minipar = parBeforeMinipage = 0;
1289 } else if (!minipar &&
1290 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1292 // par is the first paragraph in a minipage
1293 lyxerr << "begin minipage" << endl;
1294 // To minimize problems for
1295 // the users we will insert
1296 // the first minipage in
1297 // a sequence of minipages
1298 // in its own paragraph.
1299 Paragraph * p = new Paragraph;
1301 p->previous(par->previous());
1303 p->params().depth(depth);
1304 par->params().depth(0);
1306 if (par->previous())
1307 par->previous()->next(p);
1309 parBeforeMinipage = p;
1311 if (!first_par || (first_par == par))
1314 InsetMinipage * mini = new InsetMinipage;
1315 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1316 mini->width(minipar->params().pextraWidth());
1317 if (!par->params().pextraWidthp().empty()) {
1318 lyxerr << "WP:" << mini->width() << endl;
1319 mini->width(tostr(par->params().pextraWidthp())+"%");
1321 mini->inset.paragraph(minipar);
1323 // Insert the minipage last in the
1324 // previous paragraph.
1325 if (minipar->params().pextraHfill()) {
1326 parBeforeMinipage->insertChar
1327 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1329 parBeforeMinipage->insertInset
1330 (parBeforeMinipage->size(), mini);
1333 // End of pextra_minipage compability
1337 return the_end_read;
1340 // needed to insert the selection
1341 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::pos_type & pos,
1342 LyXFont const & fn,string const & str) const
1344 LyXLayout const & layout = textclasslist.Style(params.textclass,
1348 (void)par->checkInsertChar(font);
1349 // insert the string, don't insert doublespace
1350 bool space_inserted = true;
1351 for(string::const_iterator cit = str.begin();
1352 cit != str.end(); ++cit) {
1354 if (par->size() || layout.keepempty) {
1355 par->breakParagraph(params, pos,
1356 layout.isEnvironment());
1359 space_inserted = true;
1363 // do not insert consecutive spaces if !free_spacing
1364 } else if ((*cit == ' ' || *cit == '\t') &&
1365 space_inserted && !layout.free_spacing)
1368 } else if (*cit == '\t') {
1369 if (!layout.free_spacing) {
1370 // tabs are like spaces here
1371 par->insertChar(pos, ' ', font);
1373 space_inserted = true;
1375 const Paragraph::pos_type nb = 8 - pos % 8;
1376 for (Paragraph::pos_type a = 0;
1378 par->insertChar(pos, ' ', font);
1381 space_inserted = true;
1383 } else if (!IsPrintable(*cit)) {
1384 // Ignore unprintables
1387 // just insert the character
1388 par->insertChar(pos, *cit, font);
1390 space_inserted = (*cit == ' ');
1397 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1398 int & pos, LyXFont & font)
1400 // consistency check
1401 if (lex.getString() != "\\begin_inset") {
1402 lyxerr << "Buffer::readInset: Consistency check failed."
1409 string const tmptok = lex.getString();
1410 last_inset_read = tmptok;
1412 // test the different insets
1413 if (tmptok == "LatexCommand") {
1414 InsetCommandParams inscmd;
1417 string const cmdName = inscmd.getCmdName();
1419 // This strange command allows LyX to recognize "natbib" style
1420 // citations: citet, citep, Citet etc.
1421 if (compare_no_case(cmdName, "cite", 4) == 0) {
1422 inset = new InsetCitation(inscmd);
1423 } else if (cmdName == "bibitem") {
1424 lex.printError("Wrong place for bibitem");
1425 inset = new InsetBibKey(inscmd);
1426 } else if (cmdName == "BibTeX") {
1427 inset = new InsetBibtex(inscmd);
1428 } else if (cmdName == "index") {
1429 inset = new InsetIndex(inscmd);
1430 } else if (cmdName == "include") {
1431 inset = new InsetInclude(inscmd, *this);
1432 } else if (cmdName == "label") {
1433 inset = new InsetLabel(inscmd);
1434 } else if (cmdName == "url"
1435 || cmdName == "htmlurl") {
1436 inset = new InsetUrl(inscmd);
1437 } else if (cmdName == "ref"
1438 || cmdName == "pageref"
1439 || cmdName == "vref"
1440 || cmdName == "vpageref"
1441 || cmdName == "prettyref") {
1442 if (!inscmd.getOptions().empty()
1443 || !inscmd.getContents().empty()) {
1444 inset = new InsetRef(inscmd, *this);
1446 } else if (cmdName == "tableofcontents") {
1447 inset = new InsetTOC(inscmd);
1448 } else if (cmdName == "listofalgorithms") {
1449 inset = new InsetFloatList("algorithm");
1450 } else if (cmdName == "listoffigures") {
1451 inset = new InsetFloatList("figure");
1452 } else if (cmdName == "listoftables") {
1453 inset = new InsetFloatList("table");
1454 } else if (cmdName == "printindex") {
1455 inset = new InsetPrintIndex(inscmd);
1456 } else if (cmdName == "lyxparent") {
1457 inset = new InsetParent(inscmd, *this);
1460 bool alreadyread = false;
1461 if (tmptok == "Quotes") {
1462 inset = new InsetQuotes;
1463 } else if (tmptok == "External") {
1464 inset = new InsetExternal;
1465 } else if (tmptok == "FormulaMacro") {
1466 inset = new InsetFormulaMacro;
1467 } else if (tmptok == "Formula") {
1468 inset = new InsetFormula;
1469 } else if (tmptok == "Figure") { // Backward compatibility
1470 inset = new InsetFig(100, 100, *this);
1471 //inset = new InsetGraphics;
1472 } else if (tmptok == "Graphics") {
1473 inset = new InsetGraphics;
1474 } else if (tmptok == "Info") {// backwards compatibility
1475 inset = new InsetNote(this,
1476 lex.getLongString("\\end_inset"),
1479 } else if (tmptok == "Note") {
1480 inset = new InsetNote;
1481 } else if (tmptok == "Include") {
1482 InsetCommandParams p( "Include" );
1483 inset = new InsetInclude(p, *this);
1484 } else if (tmptok == "ERT") {
1485 inset = new InsetERT;
1486 } else if (tmptok == "Tabular") {
1487 inset = new InsetTabular(*this);
1488 } else if (tmptok == "Text") {
1489 inset = new InsetText;
1490 } else if (tmptok == "Foot") {
1491 inset = new InsetFoot;
1492 } else if (tmptok == "Marginal") {
1493 inset = new InsetMarginal;
1494 } else if (tmptok == "Minipage") {
1495 inset = new InsetMinipage;
1496 } else if (tmptok == "Float") {
1498 string tmptok = lex.getString();
1499 inset = new InsetFloat(tmptok);
1501 } else if (tmptok == "List") {
1502 inset = new InsetList;
1503 } else if (tmptok == "Theorem") {
1504 inset = new InsetList;
1506 } else if (tmptok == "Caption") {
1507 inset = new InsetCaption;
1508 } else if (tmptok == "FloatList") {
1509 inset = new InsetFloatList;
1512 if (inset && !alreadyread) inset->read(this, lex);
1516 par->insertInset(pos, inset, font);
1522 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1526 string const token(lex.getString());
1527 if (token == "\\lyxformat") { // the first token _must_ be...
1529 string tmp_format = lex.getString();
1530 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1531 // if present remove ".," from string.
1532 string::size_type dot = tmp_format.find_first_of(".,");
1533 //lyxerr << " dot found at " << dot << endl;
1534 if (dot != string::npos)
1535 tmp_format.erase(dot, 1);
1536 file_format = strToInt(tmp_format);
1537 if (file_format == LYX_FORMAT) {
1539 } else if (file_format > LYX_FORMAT) {
1541 Alert::alert(_("Warning!"),
1542 _("LyX file format is newer that what"),
1543 _("is supported in this LyX version. Expect some problems."));
1545 } else if (file_format < LYX_FORMAT) {
1547 if (file_format < 200) {
1548 Alert::alert(_("ERROR!"),
1549 _("Old LyX file format found. "
1550 "Use LyX 0.10.x to read this!"));
1554 bool the_end = readLyXformat2(lex, par);
1555 params.setPaperStuff();
1556 // the_end was added in 213
1557 if (file_format < 213)
1561 Alert::alert(_("Warning!"),
1562 _("Reading of document is not complete"),
1563 _("Maybe the document is truncated"));
1566 } else { // "\\lyxformat" not found
1567 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1570 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1575 // Should probably be moved to somewhere else: BufferView? LyXView?
1576 bool Buffer::save() const
1578 // We don't need autosaves in the immediate future. (Asger)
1579 resetAutosaveTimers();
1583 if (lyxrc.make_backup) {
1584 s = fileName() + '~';
1585 if (!lyxrc.backupdir_path.empty())
1586 s = AddName(lyxrc.backupdir_path,
1587 subst(os::slashify_path(s),'/','!'));
1589 // Rename is the wrong way of making a backup,
1590 // this is the correct way.
1591 /* truss cp fil fil2:
1592 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1593 stat("LyXVC.lyx", 0xEFFFF688) = 0
1594 open("LyXVC.lyx", O_RDONLY) = 3
1595 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1596 fstat(4, 0xEFFFF508) = 0
1597 fstat(3, 0xEFFFF508) = 0
1598 read(3, " # T h i s f i l e w".., 8192) = 5579
1599 write(4, " # T h i s f i l e w".., 5579) = 5579
1600 read(3, 0xEFFFD4A0, 8192) = 0
1603 chmod("LyXVC3.lyx", 0100644) = 0
1604 lseek(0, 0, SEEK_CUR) = 46440
1608 // Should probably have some more error checking here.
1609 // Should be cleaned up in 0.13, at least a bit.
1610 // Doing it this way, also makes the inodes stay the same.
1611 // This is still not a very good solution, in particular we
1612 // might loose the owner of the backup.
1613 FileInfo finfo(fileName());
1614 if (finfo.exist()) {
1615 mode_t fmode = finfo.getMode();
1616 struct utimbuf times = {
1617 finfo.getAccessTime(),
1618 finfo.getModificationTime() };
1620 ifstream ifs(fileName().c_str());
1621 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1626 ::chmod(s.c_str(), fmode);
1628 if (::utime(s.c_str(), ×)) {
1629 lyxerr << "utime error." << endl;
1632 lyxerr << "LyX was not able to make "
1633 "backup copy. Beware." << endl;
1638 if (writeFile(fileName(), false)) {
1640 removeAutosaveFile(fileName());
1642 // Saving failed, so backup is not backup
1643 if (lyxrc.make_backup) {
1644 lyx::rename(s, fileName());
1652 // Returns false if unsuccesful
1653 bool Buffer::writeFile(string const & fname, bool flag) const
1655 // if flag is false writeFile will not create any GUI
1656 // warnings, only cerr.
1657 // Needed for autosave in background or panic save (Matthias 120496)
1659 if (read_only && (fname == filename)) {
1660 // Here we should come with a question if we should
1661 // perform the write anyway.
1663 lyxerr << _("Error! Document is read-only: ")
1666 Alert::alert(_("Error! Document is read-only: "),
1671 FileInfo finfo(fname);
1672 if (finfo.exist() && !finfo.writable()) {
1673 // Here we should come with a question if we should
1674 // try to do the save anyway. (i.e. do a chmod first)
1676 lyxerr << _("Error! Cannot write file: ")
1679 Alert::err_alert(_("Error! Cannot write file: "),
1684 ofstream ofs(fname.c_str());
1687 lyxerr << _("Error! Cannot open file: ")
1690 Alert::err_alert(_("Error! Cannot open file: "),
1696 // Use the standard "C" locale for file output.
1697 ofs.imbue(std::locale::classic());
1700 // The top of the file should not be written by params.
1702 // write out a comment in the top of the file
1703 ofs << '#' << lyx_docversion
1704 << " created this file. For more info see http://www.lyx.org/\n"
1705 << "\\lyxformat " << LYX_FORMAT << "\n";
1707 // now write out the buffer paramters.
1708 params.writeFile(ofs);
1710 Paragraph::depth_type depth = 0;
1712 // this will write out all the paragraphs
1713 // using recursive descent.
1714 paragraph->writeFile(this, ofs, params, depth);
1716 // Write marker that shows file is complete
1717 ofs << "\n\\the_end" << endl;
1721 // how to check if close went ok?
1722 // Following is an attempt... (BE 20001011)
1724 // good() returns false if any error occured, including some
1725 // formatting error.
1726 // bad() returns true if something bad happened in the buffer,
1727 // which should include file system full errors.
1734 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1736 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1746 string const Buffer::asciiParagraph(Paragraph const * par,
1747 unsigned int linelen) const
1749 ostringstream buffer;
1750 Paragraph::depth_type depth = 0;
1752 Paragraph::depth_type ltype_depth = 0;
1753 string::size_type currlinelen = 0;
1754 bool ref_printed = false;
1758 if (!par->previous()) {
1759 // begins or ends a deeper area ?
1760 if (depth != par->params().depth()) {
1761 if (par->params().depth() > depth) {
1762 while (par->params().depth() > depth) {
1766 while (par->params().depth() < depth) {
1772 // First write the layout
1773 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1774 if (tmp == "Itemize") {
1776 ltype_depth = depth + 1;
1777 } else if (tmp == "Enumerate") {
1779 ltype_depth = depth + 1;
1780 } else if (contains(tmp, "ection")) {
1782 ltype_depth = depth + 1;
1783 } else if (contains(tmp, "aragraph")) {
1785 ltype_depth = depth + 1;
1786 } else if (tmp == "Description") {
1788 ltype_depth = depth + 1;
1789 } else if (tmp == "Abstract") {
1792 } else if (tmp == "Bibliography") {
1800 /* maybe some vertical spaces */
1802 /* the labelwidthstring used in lists */
1806 /* some pagebreaks? */
1810 /* what about the alignment */
1812 lyxerr << "Should this ever happen?" << endl;
1815 for (Paragraph::pos_type i = 0; i < par->size(); ++i) {
1816 if (!i && !noparbreak) {
1819 for (Paragraph::depth_type j = 0; j < depth; ++j)
1821 currlinelen = depth * 2;
1824 case 4: // (Sub)Paragraph
1825 case 5: // Description
1829 buffer << "Abstract\n\n";
1831 buffer << "Abstract: ";
1833 case 7: // Bibliography
1836 buffer << "References\n\n";
1838 buffer << "References: ";
1843 buffer << par->params().labelString() << " ";
1846 if (ltype_depth > depth) {
1847 for (Paragraph::depth_type j = ltype_depth - 1;
1850 currlinelen += (ltype_depth-depth)*2;
1854 char c = par->getUChar(params, i);
1858 case Paragraph::META_INSET:
1860 Inset const * inset = par->getInset(i);
1862 if (!inset->ascii(this, buffer)) {
1865 rsplit(buffer.str().c_str(),
1867 currlinelen += s.length();
1869 // to be sure it breaks paragraph
1870 currlinelen += linelen;
1876 case Paragraph::META_NEWLINE:
1879 for (Paragraph::depth_type j = 0;
1883 currlinelen = depth * 2;
1884 if (ltype_depth > depth) {
1885 for (Paragraph::depth_type j = ltype_depth;
1888 currlinelen += (ltype_depth - depth) * 2;
1892 case Paragraph::META_HFILL:
1897 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1898 (c == ' ') && ((i + 2) < par->size()))
1901 for (Paragraph::depth_type j = 0;
1904 currlinelen = depth * 2;
1905 if (ltype_depth > depth) {
1906 for (Paragraph::depth_type j = ltype_depth;
1909 currlinelen += (ltype_depth-depth)*2;
1911 } else if (c != '\0') {
1915 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1919 return buffer.str().c_str();
1923 void Buffer::writeFileAscii(string const & fname, int linelen)
1925 ofstream ofs(fname.c_str());
1927 Alert::err_alert(_("Error: Cannot write file:"), fname);
1930 writeFileAscii(ofs, linelen);
1934 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1936 Paragraph * par = paragraph;
1938 ofs << asciiParagraph(par, linelen);
1946 void Buffer::makeLaTeXFile(string const & fname,
1947 string const & original_path,
1948 bool nice, bool only_body)
1950 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1952 niceFile = nice; // this will be used by Insetincludes.
1954 tex_code_break_column = lyxrc.ascii_linelen;
1956 LyXTextClass const & tclass =
1957 textclasslist.TextClass(params.textclass);
1959 ofstream ofs(fname.c_str());
1961 Alert::err_alert(_("Error: Cannot open file: "), fname);
1965 // validate the buffer.
1966 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1967 LaTeXFeatures features(params, tclass.numLayouts());
1969 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1972 // The starting paragraph of the coming rows is the
1973 // first paragraph of the document. (Asger)
1974 texrow.start(paragraph, 0);
1976 if (!only_body && nice) {
1977 ofs << "%% " << lyx_docversion << " created this file. "
1978 "For more info, see http://www.lyx.org/.\n"
1979 "%% Do not edit unless you really know what "
1984 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1985 // There are a few differences between nice LaTeX and usual files:
1986 // usual is \batchmode and has a
1987 // special input@path to allow the including of figures
1988 // with either \input or \includegraphics (what figinsets do).
1989 // batchmode is not set if there is a tex_code_break_column.
1990 // In this case somebody is interested in the generated LaTeX,
1991 // so this is OK. input@path is set when the actual parameter
1992 // original_path is set. This is done for usual tex-file, but not
1993 // for nice-latex-file. (Matthias 250696)
1996 // code for usual, NOT nice-latex-file
1997 ofs << "\\batchmode\n"; // changed
1998 // from \nonstopmode
2001 if (!original_path.empty()) {
2002 ofs << "\\makeatletter\n"
2003 << "\\def\\input@path{{"
2004 << os::external_path(original_path) << "/}}\n"
2005 << "\\makeatother\n";
2011 ofs << "\\documentclass";
2013 ostringstream options; // the document class options.
2015 if (tokenPos(tclass.opt_fontsize(),
2016 '|', params.fontsize) >= 0) {
2017 // only write if existing in list (and not default)
2018 options << params.fontsize << "pt,";
2022 if (!params.use_geometry &&
2023 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2024 switch (params.papersize) {
2025 case BufferParams::PAPER_A4PAPER:
2026 options << "a4paper,";
2028 case BufferParams::PAPER_USLETTER:
2029 options << "letterpaper,";
2031 case BufferParams::PAPER_A5PAPER:
2032 options << "a5paper,";
2034 case BufferParams::PAPER_B5PAPER:
2035 options << "b5paper,";
2037 case BufferParams::PAPER_EXECUTIVEPAPER:
2038 options << "executivepaper,";
2040 case BufferParams::PAPER_LEGALPAPER:
2041 options << "legalpaper,";
2047 if (params.sides != tclass.sides()) {
2048 switch (params.sides) {
2049 case LyXTextClass::OneSide:
2050 options << "oneside,";
2052 case LyXTextClass::TwoSides:
2053 options << "twoside,";
2059 if (params.columns != tclass.columns()) {
2060 if (params.columns == 2)
2061 options << "twocolumn,";
2063 options << "onecolumn,";
2066 if (!params.use_geometry
2067 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2068 options << "landscape,";
2070 // language should be a parameter to \documentclass
2072 ostringstream language_options;
2073 if (params.language->babel() == "hebrew"
2074 && default_language->babel() != "hebrew")
2075 // This seems necessary
2076 features.useLanguage(default_language);
2078 if (lyxrc.language_use_babel ||
2079 params.language->lang() != lyxrc.default_language ||
2080 !features.hasLanguages()) {
2082 language_options << features.getLanguages();
2083 language_options << params.language->babel();
2084 if (lyxrc.language_global_options)
2085 options << language_options.str() << ',';
2088 // the user-defined options
2089 if (!params.options.empty()) {
2090 options << params.options << ',';
2093 string strOptions(options.str().c_str());
2094 if (!strOptions.empty()){
2095 strOptions = strip(strOptions, ',');
2096 ofs << '[' << strOptions << ']';
2100 << textclasslist.LatexnameOfClass(params.textclass)
2103 // end of \documentclass defs
2105 // font selection must be done before loading fontenc.sty
2106 // The ae package is not needed when using OT1 font encoding.
2107 if (params.fonts != "default" &&
2108 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2109 ofs << "\\usepackage{" << params.fonts << "}\n";
2111 if (params.fonts == "ae") {
2112 ofs << "\\usepackage{aecompl}\n";
2116 // this one is not per buffer
2117 if (lyxrc.fontenc != "default") {
2118 ofs << "\\usepackage[" << lyxrc.fontenc
2123 if (params.inputenc == "auto") {
2124 string const doc_encoding =
2125 params.language->encoding()->LatexName();
2127 // Create a list with all the input encodings used
2129 set<string> encodings = features.getEncodingSet(doc_encoding);
2131 ofs << "\\usepackage[";
2132 std::copy(encodings.begin(), encodings.end(),
2133 std::ostream_iterator<string>(ofs, ","));
2134 ofs << doc_encoding << "]{inputenc}\n";
2136 } else if (params.inputenc != "default") {
2137 ofs << "\\usepackage[" << params.inputenc
2142 // At the very beginning the text parameters.
2143 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2144 switch (params.paperpackage) {
2145 case BufferParams::PACKAGE_A4:
2146 ofs << "\\usepackage{a4}\n";
2149 case BufferParams::PACKAGE_A4WIDE:
2150 ofs << "\\usepackage{a4wide}\n";
2153 case BufferParams::PACKAGE_WIDEMARGINSA4:
2154 ofs << "\\usepackage[widemargins]{a4}\n";
2159 if (params.use_geometry) {
2160 ofs << "\\usepackage{geometry}\n";
2162 ofs << "\\geometry{verbose";
2163 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2164 ofs << ",landscape";
2165 switch (params.papersize2) {
2166 case BufferParams::VM_PAPER_CUSTOM:
2167 if (!params.paperwidth.empty())
2168 ofs << ",paperwidth="
2169 << params.paperwidth;
2170 if (!params.paperheight.empty())
2171 ofs << ",paperheight="
2172 << params.paperheight;
2174 case BufferParams::VM_PAPER_USLETTER:
2175 ofs << ",letterpaper";
2177 case BufferParams::VM_PAPER_USLEGAL:
2178 ofs << ",legalpaper";
2180 case BufferParams::VM_PAPER_USEXECUTIVE:
2181 ofs << ",executivepaper";
2183 case BufferParams::VM_PAPER_A3:
2186 case BufferParams::VM_PAPER_A4:
2189 case BufferParams::VM_PAPER_A5:
2192 case BufferParams::VM_PAPER_B3:
2195 case BufferParams::VM_PAPER_B4:
2198 case BufferParams::VM_PAPER_B5:
2202 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2203 switch (lyxrc.default_papersize) {
2204 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2205 case BufferParams::PAPER_USLETTER:
2206 ofs << ",letterpaper";
2208 case BufferParams::PAPER_LEGALPAPER:
2209 ofs << ",legalpaper";
2211 case BufferParams::PAPER_EXECUTIVEPAPER:
2212 ofs << ",executivepaper";
2214 case BufferParams::PAPER_A3PAPER:
2217 case BufferParams::PAPER_A4PAPER:
2220 case BufferParams::PAPER_A5PAPER:
2223 case BufferParams::PAPER_B5PAPER:
2228 if (!params.topmargin.empty())
2229 ofs << ",tmargin=" << params.topmargin;
2230 if (!params.bottommargin.empty())
2231 ofs << ",bmargin=" << params.bottommargin;
2232 if (!params.leftmargin.empty())
2233 ofs << ",lmargin=" << params.leftmargin;
2234 if (!params.rightmargin.empty())
2235 ofs << ",rmargin=" << params.rightmargin;
2236 if (!params.headheight.empty())
2237 ofs << ",headheight=" << params.headheight;
2238 if (!params.headsep.empty())
2239 ofs << ",headsep=" << params.headsep;
2240 if (!params.footskip.empty())
2241 ofs << ",footskip=" << params.footskip;
2246 if (features.isRequired("amsstyle")
2247 && !tclass.provides(LyXTextClass::amsmath)) {
2248 ofs << "\\usepackage{amsmath}\n";
2252 if (tokenPos(tclass.opt_pagestyle(),
2253 '|', params.pagestyle) >= 0) {
2254 if (params.pagestyle == "fancy") {
2255 ofs << "\\usepackage{fancyhdr}\n";
2258 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2262 if (params.secnumdepth != tclass.secnumdepth()) {
2263 ofs << "\\setcounter{secnumdepth}{"
2264 << params.secnumdepth
2268 if (params.tocdepth != tclass.tocdepth()) {
2269 ofs << "\\setcounter{tocdepth}{"
2275 if (params.paragraph_separation) {
2276 switch (params.defskip.kind()) {
2277 case VSpace::SMALLSKIP:
2278 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2280 case VSpace::MEDSKIP:
2281 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2283 case VSpace::BIGSKIP:
2284 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2286 case VSpace::LENGTH:
2287 ofs << "\\setlength\\parskip{"
2288 << params.defskip.length().asLatexString()
2291 default: // should never happen // Then delete it.
2292 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2297 ofs << "\\setlength\\parindent{0pt}\n";
2301 // Now insert the LyX specific LaTeX commands...
2303 // The optional packages;
2304 string preamble(features.getPackages());
2306 // this might be useful...
2307 preamble += "\n\\makeatletter\n";
2309 // Some macros LyX will need
2310 string tmppreamble(features.getMacros());
2312 if (!tmppreamble.empty()) {
2313 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2314 "LyX specific LaTeX commands.\n"
2315 + tmppreamble + '\n';
2318 // the text class specific preamble
2319 tmppreamble = features.getTClassPreamble();
2320 if (!tmppreamble.empty()) {
2321 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2322 "Textclass specific LaTeX commands.\n"
2323 + tmppreamble + '\n';
2326 /* the user-defined preamble */
2327 if (!params.preamble.empty()) {
2328 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2329 "User specified LaTeX commands.\n"
2330 + params.preamble + '\n';
2333 preamble += "\\makeatother\n";
2335 // Itemize bullet settings need to be last in case the user
2336 // defines their own bullets that use a package included
2337 // in the user-defined preamble -- ARRae
2338 // Actually it has to be done much later than that
2339 // since some packages like frenchb make modifications
2340 // at \begin{document} time -- JMarc
2342 for (int i = 0; i < 4; ++i) {
2343 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2344 if (bullets_def.empty())
2345 bullets_def="\\AtBeginDocument{\n";
2346 bullets_def += " \\renewcommand{\\labelitemi";
2348 // `i' is one less than the item to modify
2355 bullets_def += "ii";
2361 bullets_def += "}{" +
2362 params.user_defined_bullets[i].getText()
2367 if (!bullets_def.empty())
2368 preamble += bullets_def + "}\n\n";
2370 for (int j = countChar(preamble, '\n'); j-- ;) {
2376 // We try to load babel late, in case it interferes
2377 // with other packages.
2379 string tmp = lyxrc.language_package;
2380 if (!lyxrc.language_global_options
2381 && tmp == "\\usepackage{babel}")
2382 tmp = string("\\usepackage[") +
2383 language_options.str().c_str() +
2390 ofs << "\\begin{document}\n";
2393 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2395 if (!lyxrc.language_auto_begin) {
2396 ofs << subst(lyxrc.language_command_begin, "$$lang",
2397 params.language->babel())
2402 latexParagraphs(ofs, paragraph, 0, texrow);
2404 // add this just in case after all the paragraphs
2408 if (!lyxrc.language_auto_end) {
2409 ofs << subst(lyxrc.language_command_end, "$$lang",
2410 params.language->babel())
2416 ofs << "\\end{document}\n";
2419 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2421 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2425 // Just to be sure. (Asger)
2428 // tex_code_break_column's value is used to decide
2429 // if we are in batchmode or not (within mathed_write()
2430 // in math_write.C) so we must set it to a non-zero
2431 // value when we leave otherwise we save incorrect .lyx files.
2432 tex_code_break_column = lyxrc.ascii_linelen;
2436 lyxerr << "File was not closed properly." << endl;
2439 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2444 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2446 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2447 Paragraph * endpar, TexRow & texrow) const
2449 bool was_title = false;
2450 bool already_title = false;
2453 while (par != endpar) {
2454 LyXLayout const & layout =
2455 textclasslist.Style(params.textclass,
2458 if (layout.intitle) {
2459 if (already_title) {
2460 lyxerr <<"Error in latexParagraphs: You"
2461 " should not mix title layouts"
2462 " with normal ones." << endl;
2465 } else if (was_title && !already_title) {
2466 ofs << "\\maketitle\n";
2468 already_title = true;
2472 if (layout.isEnvironment()) {
2473 par = par->TeXEnvironment(this, params, ofs, texrow);
2475 par = par->TeXOnePar(this, params, ofs, texrow, false);
2478 // It might be that we only have a title in this document
2479 if (was_title && !already_title) {
2480 ofs << "\\maketitle\n";
2486 bool Buffer::isLatex() const
2488 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2492 bool Buffer::isLinuxDoc() const
2494 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2498 bool Buffer::isLiterate() const
2500 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2504 bool Buffer::isDocBook() const
2506 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2510 bool Buffer::isSGML() const
2512 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2513 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2517 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2518 string const & latexname) const
2520 if (!latexname.empty() && latexname != "!-- --")
2521 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2522 os << string(depth, ' ') << "<" << latexname << ">\n";
2526 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2527 string const & latexname) const
2529 if (!latexname.empty() && latexname != "!-- --")
2530 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2531 os << string(depth, ' ') << "</" << latexname << ">\n";
2535 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2537 ofstream ofs(fname.c_str());
2540 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2544 niceFile = nice; // this will be used by included files.
2546 LyXTextClass const & tclass =
2547 textclasslist.TextClass(params.textclass);
2549 LaTeXFeatures features(params, tclass.numLayouts());
2554 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2557 ofs << "<!doctype linuxdoc system";
2559 string preamble = params.preamble;
2560 preamble += features.getIncludedFiles(fname);
2561 preamble += features.getLyXSGMLEntities();
2563 if (!preamble.empty()) {
2564 ofs << " [ " << preamble << " ]";
2568 if (params.options.empty())
2569 sgmlOpenTag(ofs, 0, top_element);
2571 string top = top_element;
2573 top += params.options;
2574 sgmlOpenTag(ofs, 0, top);
2578 ofs << "<!-- " << lyx_docversion
2579 << " created this file. For more info see http://www.lyx.org/"
2582 Paragraph::depth_type depth = 0; // paragraph depth
2583 Paragraph * par = paragraph;
2585 vector<string> environment_stack(5);
2588 LyXLayout const & style =
2589 textclasslist.Style(params.textclass,
2592 // treat <toc> as a special case for compatibility with old code
2593 if (par->isInset(0)) {
2594 Inset * inset = par->getInset(0);
2595 Inset::Code lyx_code = inset->lyxCode();
2596 if (lyx_code == Inset::TOC_CODE){
2597 string const temp = "toc";
2598 sgmlOpenTag(ofs, depth, temp);
2605 // environment tag closing
2606 for (; depth > par->params().depth(); --depth) {
2607 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2608 environment_stack[depth].erase();
2611 // write opening SGML tags
2612 switch (style.latextype) {
2613 case LATEX_PARAGRAPH:
2614 if (depth == par->params().depth()
2615 && !environment_stack[depth].empty()) {
2616 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2617 environment_stack[depth].erase();
2623 sgmlOpenTag(ofs, depth, style.latexname());
2629 _("Error : Wrong depth for"
2630 " LatexType Command.\n"));
2632 if (!environment_stack[depth].empty()){
2633 sgmlCloseTag(ofs, depth,
2634 environment_stack[depth]);
2638 environment_stack[depth].erase();
2639 sgmlOpenTag(ofs, depth, style.latexname());
2642 case LATEX_ENVIRONMENT:
2643 case LATEX_ITEM_ENVIRONMENT:
2644 if (depth == par->params().depth()
2645 && environment_stack[depth] != style.latexname()) {
2646 sgmlCloseTag(ofs, depth,
2647 environment_stack[depth]);
2648 environment_stack[depth].erase();
2650 if (depth < par->params().depth()) {
2651 depth = par->params().depth();
2652 environment_stack[depth].erase();
2654 if (environment_stack[depth] != style.latexname()) {
2656 sgmlOpenTag(ofs, depth, "p");
2658 sgmlOpenTag(ofs, depth, style.latexname());
2660 if (environment_stack.size() == depth + 1)
2661 environment_stack.push_back("!-- --");
2662 environment_stack[depth] = style.latexname();
2665 if (style.latexparam() == "CDATA")
2668 if (style.latextype == LATEX_ENVIRONMENT) break;
2670 if (style.labeltype == LABEL_MANUAL)
2675 sgmlOpenTag(ofs, depth + 1, item_name);
2678 sgmlOpenTag(ofs, depth, style.latexname());
2682 simpleLinuxDocOnePar(ofs, par, depth);
2687 // write closing SGML tags
2688 switch (style.latextype) {
2691 case LATEX_ENVIRONMENT:
2692 case LATEX_ITEM_ENVIRONMENT:
2693 if (style.latexparam() == "CDATA")
2697 sgmlCloseTag(ofs, depth, style.latexname());
2703 for (int i=depth; i >= 0; --i)
2704 sgmlCloseTag(ofs, depth, environment_stack[i]);
2708 sgmlCloseTag(ofs, 0, top_element);
2712 // How to check for successful close
2716 // checks, if newcol chars should be put into this line
2717 // writes newline, if necessary.
2720 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2721 string::size_type newcol)
2724 if (colcount > lyxrc.ascii_linelen) {
2726 colcount = newcol; // assume write after this call
2741 string tag_name(PAR_TAG const & pt) {
2743 case NONE: return "!-- --";
2744 case TT: return "tt";
2745 case SF: return "sf";
2746 case BF: return "bf";
2747 case IT: return "it";
2748 case SL: return "sl";
2749 case EM: return "em";
2756 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2758 p1 = static_cast<PAR_TAG>(p1 | p2);
2763 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2765 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2771 // Handle internal paragraph parsing -- layout already processed.
2772 void Buffer::simpleLinuxDocOnePar(ostream & os,
2774 Paragraph::depth_type /*depth*/)
2776 LyXLayout const & style = textclasslist.Style(params.textclass,
2778 string::size_type char_line_count = 5; // Heuristic choice ;-)
2780 // gets paragraph main font
2783 if (style.labeltype == LABEL_MANUAL) {
2784 font_old = style.labelfont;
2787 font_old = style.font;
2791 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2792 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2793 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2796 stack<PAR_TAG> tag_state;
2797 // parsing main loop
2798 for (Paragraph::pos_type i = 0; i < par->size(); ++i) {
2800 PAR_TAG tag_close = NONE;
2801 list < PAR_TAG > tag_open;
2803 LyXFont const font = par->getFont(params, i);
2805 if (font_old.family() != font.family()) {
2806 switch (family_type) {
2807 case LyXFont::SANS_FAMILY:
2810 case LyXFont::TYPEWRITER_FAMILY:
2817 family_type = font.family();
2819 switch (family_type) {
2820 case LyXFont::SANS_FAMILY:
2821 tag_open.push_back(SF);
2823 case LyXFont::TYPEWRITER_FAMILY:
2824 tag_open.push_back(TT);
2831 if (font_old.series() != font.series()) {
2832 switch (series_type) {
2833 case LyXFont::BOLD_SERIES:
2840 series_type = font.series();
2842 switch (series_type) {
2843 case LyXFont::BOLD_SERIES:
2844 tag_open.push_back(BF);
2852 if (font_old.shape() != font.shape()) {
2853 switch (shape_type) {
2854 case LyXFont::ITALIC_SHAPE:
2857 case LyXFont::SLANTED_SHAPE:
2864 shape_type = font.shape();
2866 switch (shape_type) {
2867 case LyXFont::ITALIC_SHAPE:
2868 tag_open.push_back(IT);
2870 case LyXFont::SLANTED_SHAPE:
2871 tag_open.push_back(SL);
2878 if (font_old.emph() != font.emph()) {
2879 if (font.emph() == LyXFont::ON) {
2880 tag_open.push_back(EM);
2889 list < PAR_TAG > temp;
2890 while(!tag_state.empty() && tag_close ) {
2891 PAR_TAG k = tag_state.top();
2893 os << "</" << tag_name(k) << ">";
2900 for(list< PAR_TAG >::const_iterator j = temp.begin();
2901 j != temp.end(); ++j) {
2903 os << "<" << tag_name(*j) << ">";
2906 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2907 j != tag_open.end(); ++j) {
2909 os << "<" << tag_name(*j) << ">";
2912 char c = par->getChar(i);
2914 if (c == Paragraph::META_INSET) {
2915 Inset * inset = par->getInset(i);
2916 inset->linuxdoc(this, os);
2921 if (style.latexparam() == "CDATA") {
2922 // "TeX"-Mode on == > SGML-Mode on.
2928 if (par->sgmlConvertChar(c, sgml_string)
2929 && !style.free_spacing) {
2930 // in freespacing mode, spaces are
2931 // non-breaking characters
2932 if (desc_on) {// if char is ' ' then...
2935 sgmlLineBreak(os, char_line_count, 6);
2939 sgmlLineBreak(os, char_line_count, 1);
2944 char_line_count += sgml_string.length();
2950 while (!tag_state.empty()) {
2951 os << "</" << tag_name(tag_state.top()) << ">";
2955 // resets description flag correctly
2957 // <tag> not closed...
2958 sgmlLineBreak(os, char_line_count, 6);
2964 // Print an error message.
2965 void Buffer::sgmlError(Paragraph * par, int pos,
2966 string const & message) const
2968 // insert an error marker in text
2969 InsetError * new_inset = new InsetError(message);
2970 par->insertInset(pos, new_inset);
2971 par->setFont(pos, LyXFont(LyXFont::ALL_INHERIT, params.language));
2975 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2977 ofstream ofs(fname.c_str());
2979 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2983 Paragraph * par = paragraph;
2985 niceFile = nice; // this will be used by Insetincludes.
2987 LyXTextClass const & tclass =
2988 textclasslist.TextClass(params.textclass);
2990 LaTeXFeatures features(params, tclass.numLayouts());
2995 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2998 ofs << "<!DOCTYPE " << top_element
2999 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3001 string preamble = params.preamble;
3002 preamble += features.getIncludedFiles(fname);
3003 preamble += features.getLyXSGMLEntities();
3005 if (!preamble.empty()) {
3006 ofs << "\n [ " << preamble << " ]";
3011 string top = top_element;
3013 top += params.language->code();
3016 if (!params.options.empty()) {
3018 top += params.options;
3020 sgmlOpenTag(ofs, 0, top);
3022 ofs << "<!-- DocBook file was created by " << lyx_docversion
3023 << "\n See http://www.lyx.org/ for more information -->\n";
3025 vector<string> environment_stack(10);
3026 vector<string> environment_inner(10);
3027 vector<string> command_stack(10);
3029 bool command_flag = false;
3030 Paragraph::depth_type command_depth = 0;
3031 Paragraph::depth_type command_base = 0;
3032 Paragraph::depth_type cmd_depth = 0;
3033 Paragraph::depth_type depth = 0; // paragraph depth
3036 string command_name;
3042 int desc_on = 0; // description mode
3044 LyXLayout const & style =
3045 textclasslist.Style(params.textclass,
3048 // environment tag closing
3049 for (; depth > par->params().depth(); --depth) {
3050 if (environment_inner[depth] != "!-- --") {
3051 item_name = "listitem";
3052 sgmlCloseTag(ofs, command_depth + depth,
3054 if (environment_inner[depth] == "varlistentry")
3055 sgmlCloseTag(ofs, depth+command_depth,
3056 environment_inner[depth]);
3058 sgmlCloseTag(ofs, depth + command_depth,
3059 environment_stack[depth]);
3060 environment_stack[depth].erase();
3061 environment_inner[depth].erase();
3064 if (depth == par->params().depth()
3065 && environment_stack[depth] != style.latexname()
3066 && !environment_stack[depth].empty()) {
3067 if (environment_inner[depth] != "!-- --") {
3068 item_name= "listitem";
3069 sgmlCloseTag(ofs, command_depth+depth,
3071 if (environment_inner[depth] == "varlistentry")
3073 depth + command_depth,
3074 environment_inner[depth]);
3077 sgmlCloseTag(ofs, depth + command_depth,
3078 environment_stack[depth]);
3080 environment_stack[depth].erase();
3081 environment_inner[depth].erase();
3084 // Write opening SGML tags.
3085 switch (style.latextype) {
3086 case LATEX_PARAGRAPH:
3087 sgmlOpenTag(ofs, depth + command_depth,
3094 _("Error : Wrong depth for "
3095 "LatexType Command.\n"));
3097 command_name = style.latexname();
3099 sgmlparam = style.latexparam();
3100 c_params = split(sgmlparam, c_depth,'|');
3102 cmd_depth = lyx::atoi(c_depth);
3105 if (cmd_depth < command_base) {
3106 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3107 sgmlCloseTag(ofs, j, command_stack[j]);
3108 command_depth = command_base = cmd_depth;
3109 } else if (cmd_depth <= command_depth) {
3110 for (int j = command_depth; j >= int(cmd_depth); --j)
3111 sgmlCloseTag(ofs, j, command_stack[j]);
3112 command_depth = cmd_depth;
3114 command_depth = cmd_depth;
3116 command_depth = command_base = cmd_depth;
3117 command_flag = true;
3119 if (command_stack.size() == command_depth + 1)
3120 command_stack.push_back(string());
3121 command_stack[command_depth] = command_name;
3123 // treat label as a special case for
3124 // more WYSIWYM handling.
3125 if (par->isInset(0)) {
3126 Inset * inset = par->getInset(0);
3127 Inset::Code lyx_code = inset->lyxCode();
3128 if (lyx_code == Inset::LABEL_CODE){
3129 command_name += " id=\"";
3130 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3131 command_name += "\"";
3136 sgmlOpenTag(ofs, depth + command_depth, command_name);
3137 if (c_params.empty())
3138 item_name = "title";
3140 item_name = c_params;
3141 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3144 case LATEX_ENVIRONMENT:
3145 case LATEX_ITEM_ENVIRONMENT:
3146 if (depth < par->params().depth()) {
3147 depth = par->params().depth();
3148 environment_stack[depth].erase();
3151 if (environment_stack[depth] != style.latexname()) {
3152 if(environment_stack.size() == depth + 1) {
3153 environment_stack.push_back("!-- --");
3154 environment_inner.push_back("!-- --");
3156 environment_stack[depth] = style.latexname();
3157 environment_inner[depth] = "!-- --";
3158 sgmlOpenTag(ofs, depth + command_depth,
3159 environment_stack[depth]);
3161 if (environment_inner[depth] != "!-- --") {
3162 item_name= "listitem";
3164 command_depth + depth,
3166 if (environment_inner[depth] == "varlistentry")
3168 depth + command_depth,
3169 environment_inner[depth]);
3173 if (style.latextype == LATEX_ENVIRONMENT) {
3174 if (!style.latexparam().empty()) {
3175 if(style.latexparam() == "CDATA")
3178 sgmlOpenTag(ofs, depth + command_depth,
3179 style.latexparam());
3184 desc_on = (style.labeltype == LABEL_MANUAL);
3187 environment_inner[depth]= "varlistentry";
3189 environment_inner[depth]= "listitem";
3191 sgmlOpenTag(ofs, depth + 1 + command_depth,
3192 environment_inner[depth]);
3196 sgmlOpenTag(ofs, depth + 1 + command_depth,
3200 sgmlOpenTag(ofs, depth + 1 + command_depth,
3205 sgmlOpenTag(ofs, depth + command_depth,
3210 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3214 // write closing SGML tags
3215 switch (style.latextype) {
3217 if (c_params.empty())
3221 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3223 case LATEX_ENVIRONMENT:
3224 if (!style.latexparam().empty()) {
3225 if(style.latexparam() == "CDATA")
3228 sgmlCloseTag(ofs, depth + command_depth,
3229 style.latexparam());
3232 case LATEX_ITEM_ENVIRONMENT:
3233 if (desc_on == 1) break;
3235 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3237 case LATEX_PARAGRAPH:
3238 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3241 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3247 for (int d = depth; d >= 0; --d) {
3248 if (!environment_stack[depth].empty()) {
3249 if (environment_inner[depth] != "!-- --") {
3250 item_name = "listitem";
3251 sgmlCloseTag(ofs, command_depth + depth,
3253 if (environment_inner[depth] == "varlistentry")
3254 sgmlCloseTag(ofs, depth + command_depth,
3255 environment_inner[depth]);
3258 sgmlCloseTag(ofs, depth + command_depth,
3259 environment_stack[depth]);
3263 for (int j = command_depth; j >= 0 ; --j)
3264 if (!command_stack[j].empty())
3265 sgmlCloseTag(ofs, j, command_stack[j]);
3268 sgmlCloseTag(ofs, 0, top_element);
3271 // How to check for successful close
3275 void Buffer::simpleDocBookOnePar(ostream & os,
3276 Paragraph * par, int & desc_on,
3277 Paragraph::depth_type depth) const
3279 bool emph_flag = false;
3281 LyXLayout const & style = textclasslist.Style(params.textclass,
3284 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3286 int char_line_count = depth;
3287 //if (!style.free_spacing)
3288 // os << string(depth,' ');
3290 // parsing main loop
3291 for (Paragraph::pos_type i = 0;
3292 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,
3702 Paragraph::pos_type pos)
3705 it = par->InsetIterator(pos);
3706 if (it == par->inset_iterator_end()) {
3713 void Buffer::inset_iterator::setParagraph()
3716 it = par->inset_iterator_begin();
3717 if (it != par->inset_iterator_end())
3722 // We maintain an invariant that whenever par = 0 then it = 0
3726 Inset * Buffer::getInsetFromID(int id_arg) const
3728 for (inset_iterator it = inset_const_iterator_begin();
3729 it != inset_const_iterator_end(); ++it)
3731 if ((*it)->id() == id_arg)
3733 Inset * in = (*it)->getInsetFromID(id_arg);
3741 Paragraph * Buffer::getParFromID(int id) const
3743 if (id < 0) return 0;
3744 Paragraph * par = paragraph;
3746 if (par->id() == id) {
3749 Paragraph * tmp = par->getParFromID(id);
3759 ParIterator Buffer::par_iterator_begin()
3761 return ParIterator(paragraph);
3765 ParIterator Buffer::par_iterator_end()
3767 return ParIterator();