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 * ======================================================
18 #pragma implementation
22 #include "bufferlist.h"
24 #include "lyx_gui_misc.h"
25 #include "LyXAction.h"
28 #include "tex-strings.h"
30 #include "bufferview_funcs.h"
37 #include "LaTeXFeatures.h"
44 #include "converter.h"
45 #include "BufferView.h"
46 #include "ParagraphParameters.h"
47 #include "iterators.h"
48 #include "lyxtextclasslist.h"
50 #include "mathed/formulamacro.h"
51 #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"
85 #include "frontends/Dialogs.h"
86 #include "frontends/Alert.h"
88 #include "support/textutils.h"
89 #include "support/filetools.h"
90 #include "support/path.h"
91 #include "support/os.h"
92 #include "support/syscall.h"
93 #include "support/lyxlib.h"
94 #include "support/FileInfo.h"
95 #include "support/lyxmanip.h"
107 #include <sys/types.h>
124 using std::make_pair;
133 using lyx::layout_type;
134 using lyx::textclass_type;
136 // all these externs should eventually be removed.
137 extern BufferList bufferlist;
139 extern LyXAction lyxaction;
143 const int LYX_FORMAT = 220;
147 extern int tex_code_break_column;
150 Buffer::Buffer(string const & file, bool ronly)
152 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
154 filepath = OnlyPath(file);
163 if (read_only || (lyxrc.use_tempdir)) {
164 tmppath = CreateBufferTmpDir();
165 } else tmppath.erase();
171 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
172 // here the buffer should take care that it is
173 // saved properly, before it goes into the void.
175 // make sure that views using this buffer
180 if (!tmppath.empty()) {
181 DestroyBufferTmpDir(tmppath);
184 Paragraph * par = paragraph;
187 tmppar = par->next();
195 string const Buffer::getLatexName(bool no_path) const
197 string const name = ChangeExtension(MakeLatexName(filename), ".tex");
199 return OnlyFilename(name);
205 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
207 string const filename = getLatexName(false);
209 if (filename.empty())
210 return make_pair(Buffer::latexlog, string());
212 string path = OnlyPath(filename);
214 if (lyxrc.use_tempdir || !IsDirWriteable(path))
217 string const fname = AddName(path,
218 OnlyFilename(ChangeExtension(filename,
221 AddName(path, OnlyFilename(
222 ChangeExtension(filename,
223 formats.extension("literate") + ".out")));
225 // If no Latex log or Build log is newer, show Build log
227 FileInfo const f_fi(fname);
228 FileInfo const b_fi(bname);
231 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
232 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
233 return make_pair(Buffer::buildlog, bname);
235 lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
236 return make_pair(Buffer::latexlog, fname);
240 void Buffer::setReadonly(bool flag)
242 if (read_only != flag) {
245 users->owner()->getDialogs()->updateBufferDependent(false);
250 /// Update window titles of all users
251 // Should work on a list
252 void Buffer::updateTitles() const
255 users->owner()->updateWindowTitle();
259 /// Reset autosave timer of all users
260 // Should work on a list
261 void Buffer::resetAutosaveTimers() const
264 users->owner()->resetAutosaveTimer();
268 void Buffer::setFileName(string const & newfile)
270 filename = MakeAbsPath(newfile);
271 filepath = OnlyPath(filename);
272 setReadonly(IsFileWriteable(filename) == 0);
277 // We'll remove this later. (Lgb)
280 string last_inset_read;
282 #ifndef NO_COMPABILITY
285 ErtComp() : active(false), in_tabular(false) {
292 std::stack<ErtComp> ert_stack;
296 #warning And _why_ is this here? (Lgb)
303 // candidate for move to BufferView
304 // (at least some parts in the beginning of the func)
307 // changed to be public and have one parameter
308 // if par = 0 normal behavior
309 // else insert behavior
310 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
311 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
315 #ifndef NO_COMPABILITY
316 ert_comp.contents.erase();
317 ert_comp.active = false;
318 ert_comp.in_tabular = false;
321 Paragraph::depth_type depth = 0;
322 bool the_end_read = false;
324 Paragraph * first_par = 0;
325 LyXFont font(LyXFont::ALL_INHERIT, params.language);
326 if (file_format < 216 && params.language->lang() == "hebrew")
327 font.setLanguage(default_language);
332 // We are inserting into an existing document
333 users->text->breakParagraph(users);
334 first_par = users->text->firstParagraph();
337 // We don't want to adopt the parameters from the
338 // document we insert, so we skip until the text begins:
341 string const pretoken = lex.getString();
342 if (pretoken == "\\layout") {
343 lex.pushToken(pretoken);
351 string const token = lex.getString();
353 if (token.empty()) continue;
355 lyxerr[Debug::PARSER] << "Handling token: `"
356 << token << "'" << endl;
359 parseSingleLyXformat2Token(lex, par, first_par,
367 paragraph = first_par;
369 if (unknown_layouts > 0) {
370 string s = _("Couldn't set the layout for ");
371 if (unknown_layouts == 1) {
372 s += _("one paragraph");
374 s += tostr(unknown_layouts);
375 s += _(" paragraphs");
377 Alert::alert(_("Textclass Loading Error!"), s,
378 _("When reading " + fileName()));
381 if (unknown_tokens > 0) {
382 string s = _("Encountered ");
383 if (unknown_tokens == 1) {
384 s += _("one unknown token");
386 s += tostr(unknown_tokens);
387 s += _(" unknown tokens");
389 Alert::alert(_("Textclass Loading Error!"), s,
390 _("When reading " + fileName()));
397 #ifndef NO_COMPABILITY
398 void Buffer::insertErtContents(Paragraph * par, int & pos,
399 LyXFont const & f, bool set_inactive)
401 if (!ert_comp.contents.empty()) {
402 lyxerr[Debug::INSETS] << "ERT contents:\n'"
403 << ert_comp.contents << "'" << endl;
404 Inset * inset = new InsetERT(ert_comp.contents, true);
406 font.setLanguage(f.language());
407 par->insertInset(pos++, inset, font);
408 ert_comp.contents.erase();
411 ert_comp.active = false;
418 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
419 Paragraph *& first_par,
420 string const & token, int & pos,
421 Paragraph::depth_type & depth,
425 bool the_end_read = false;
426 #ifndef NO_COMPABILITY
427 #ifndef NO_PEXTRA_REALLY
428 // This is super temporary but is needed to get the compability
429 // mode for minipages work correctly together with new tabulars.
430 static int call_depth;
432 bool checkminipage = false;
433 static Paragraph * minipar;
434 static Paragraph * parBeforeMinipage;
437 if (token[0] != '\\') {
438 #ifndef NO_COMPABILITY
439 if (ert_comp.active) {
440 ert_comp.contents += token;
443 for (string::const_iterator cit = token.begin();
444 cit != token.end(); ++cit) {
445 par->insertChar(pos, (*cit), font);
448 #ifndef NO_COMPABILITY
451 } else if (token == "\\i") {
452 Inset * inset = new InsetLatexAccent;
453 inset->read(this, lex);
454 par->insertInset(pos, inset, font);
456 } else if (token == "\\layout") {
457 #ifndef NO_COMPABILITY
458 ert_comp.in_tabular = false;
460 insertErtContents(par, pos, font);
463 string const layoutname = lex.getString();
464 //lyxerr << "Looking for layout '"
465 // << layoutname << "'!" << endl;
467 pair<bool, layout_type> pp
468 = textclasslist.NumberOfLayout(params.textclass, layoutname);
470 //lyxerr << "Result: " << pp.first << "/" << pp.second << endl;
472 #ifndef NO_COMPABILITY
473 if (compare_no_case(layoutname, "latex") == 0) {
474 ert_comp.active = true;
478 // The is the compability reading of layout caption.
479 // It can be removed in LyX version 1.3.0. (Lgb)
480 if (compare_no_case(layoutname, "caption") == 0) {
481 // We expect that the par we are now working on is
482 // really inside a InsetText inside a InsetFloat.
483 // We also know that captions can only be
484 // one paragraph. (Lgb)
486 // We should now read until the next "\layout"
488 // This is probably not good enough, what if the
489 // caption is the last par in the document (Lgb)
490 istream & ist = lex.getStream();
496 if (prefixIs(line, "\\layout")) {
500 if (prefixIs(line, "\\begin_inset"))
502 if (prefixIs(line, "\\end_inset")) {
513 // Now we should have the whole layout in ss
514 // we should now be able to give this to the
516 ss << "\\end_inset\n";
518 // This seems like a bug in stringstream.
519 // We really should be able to use ss
521 istringstream is(ss.str());
523 tmplex.setStream(is);
524 Inset * inset = new InsetCaption;
525 inset->Read(this, tmplex);
526 par->InsertInset(pos, inset, font);
533 par = new Paragraph(par);
537 par->layout = pp.second;
538 #ifndef NO_COMPABILITY
539 } else if (ert_comp.active) {
544 // use default layout "Standard" (0)
545 //lyxerr << "Layout '" << layoutname
546 // << "' was not found!" << endl;
550 string const s = _("Layout had to be changed from\n")
551 + layoutname + _(" to ")
552 + textclasslist.NameOfLayout(params.textclass, par->layout);
553 InsetError * new_inset = new InsetError(s);
554 par->insertInset(0, new_inset,
555 LyXFont(LyXFont::ALL_INHERIT,
558 // Test whether the layout is obsolete.
559 LyXLayout const & layout =
560 textclasslist.Style(params.textclass,
562 if (!layout.obsoleted_by().empty())
563 par->layout = textclasslist
564 .NumberOfLayout(params.textclass,
565 layout.obsoleted_by())
567 par->params().depth(depth);
568 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
569 if (file_format < 216
570 && params.language->lang() == "hebrew")
571 font.setLanguage(default_language);
576 #ifndef NO_COMPABILITY
577 } else if (token == "\\begin_float") {
578 insertErtContents(par, pos, font);
579 //insertErtContents(par, pos, font, false);
580 //ert_stack.push(ert_comp);
581 //ert_comp = ErtComp();
583 // This is the compability reader. It can be removed in
584 // LyX version 1.3.0. (Lgb)
586 string const tmptok = lex.getString();
587 //lyxerr << "old float: " << tmptok << endl;
590 stringstream old_float;
592 if (tmptok == "footnote") {
593 inset = new InsetFoot;
594 old_float << "collapsed true\n";
595 } else if (tmptok == "margin") {
596 inset = new InsetMarginal;
597 old_float << "collapsed true\n";
598 } else if (tmptok == "fig") {
599 inset = new InsetFloat("figure");
600 old_float << "placement htbp\n"
602 << "collapsed false\n";
603 } else if (tmptok == "tab") {
604 inset = new InsetFloat("table");
605 old_float << "placement htbp\n"
607 << "collapsed false\n";
608 } else if (tmptok == "alg") {
609 inset = new InsetFloat("algorithm");
610 old_float << "placement htbp\n"
612 << "collapsed false\n";
613 } else if (tmptok == "wide-fig") {
614 inset = new InsetFloat("figure");
615 //InsetFloat * tmp = new InsetFloat("figure");
618 old_float << "placement htbp\n"
620 << "collapsed false\n";
621 } else if (tmptok == "wide-tab") {
622 inset = new InsetFloat("table");
623 //InsetFloat * tmp = new InsetFloat("table");
626 old_float << "placement htbp\n"
628 << "collapsed false\n";
632 #ifndef NO_PEXTRA_REALLY
635 return false; // no end read yet
638 // Here we need to check for \end_deeper and handle that
639 // before we do the footnote parsing.
640 // This _is_ a hack! (Lgb)
643 string const tmp = lex.getString();
644 if (tmp == "\\end_deeper") {
645 //lyxerr << "\\end_deeper caught!" << endl;
647 lex.printError("\\end_deeper: "
648 "depth is already null");
653 old_float << tmp << ' ';
658 old_float << lex.getLongString("\\end_float")
659 << "\n\\end_inset\n";
660 //lyxerr << "Float Body:\n" << old_float.str() << endl;
661 // That this does not work seems like a bug
662 // in stringstream. (Lgb)
663 istringstream istr(old_float.str());
665 nylex.setStream(istr);
666 inset->read(this, nylex);
667 par->insertInset(pos, inset, font);
669 insertErtContents(par, pos, font);
671 } else if (token == "\\begin_deeper") {
673 } else if (token == "\\end_deeper") {
675 lex.printError("\\end_deeper: "
676 "depth is already null");
680 } else if (token == "\\begin_preamble") {
681 params.readPreamble(lex);
682 } else if (token == "\\textclass") {
684 pair<bool, textclass_type> pp =
685 textclasslist.NumberOfClass(lex.getString());
687 params.textclass = pp.second;
689 Alert::alert(string(_("Textclass error")),
690 string(_("The document uses an unknown textclass \"")) +
691 lex.getString() + string("\"."),
692 string(_("LyX will not be able to produce output correctly.")));
693 params.textclass = 0;
695 if (!textclasslist.Load(params.textclass)) {
696 // if the textclass wasn't loaded properly
697 // we need to either substitute another
698 // or stop loading the file.
699 // I can substitute but I don't see how I can
700 // stop loading... ideas?? ARRae980418
701 Alert::alert(_("Textclass Loading Error!"),
702 string(_("Can't load textclass ")) +
703 textclasslist.NameOfClass(params.textclass),
704 _("-- substituting default"));
705 params.textclass = 0;
707 } else if (token == "\\options") {
709 params.options = lex.getString();
710 } else if (token == "\\language") {
711 params.readLanguage(lex);
712 } else if (token == "\\fontencoding") {
714 } else if (token == "\\inputencoding") {
716 params.inputenc = lex.getString();
717 } else if (token == "\\graphics") {
718 params.readGraphicsDriver(lex);
719 } else if (token == "\\fontscheme") {
721 params.fonts = lex.getString();
722 } else if (token == "\\noindent") {
723 par->params().noindent(true);
724 } else if (token == "\\fill_top") {
725 par->params().spaceTop(VSpace(VSpace::VFILL));
726 } else if (token == "\\fill_bottom") {
727 par->params().spaceBottom(VSpace(VSpace::VFILL));
728 } else if (token == "\\line_top") {
729 par->params().lineTop(true);
730 } else if (token == "\\line_bottom") {
731 par->params().lineBottom(true);
732 } else if (token == "\\pagebreak_top") {
733 par->params().pagebreakTop(true);
734 } else if (token == "\\pagebreak_bottom") {
735 par->params().pagebreakBottom(true);
736 } else if (token == "\\start_of_appendix") {
737 par->params().startOfAppendix(true);
738 } else if (token == "\\paragraph_separation") {
739 int tmpret = lex.findToken(string_paragraph_separation);
742 if (tmpret != LYX_LAYOUT_DEFAULT)
743 params.paragraph_separation =
744 static_cast<BufferParams::PARSEP>(tmpret);
745 } else if (token == "\\defskip") {
747 params.defskip = VSpace(lex.getString());
748 #ifndef NO_COMPABILITY
749 } else if (token == "\\epsfig") { // obsolete
750 // Indeed it is obsolete, but we HAVE to be backwards
751 // compatible until 0.14, because otherwise all figures
752 // in existing documents are irretrivably lost. (Asger)
753 params.readGraphicsDriver(lex);
755 } else if (token == "\\quotes_language") {
756 int tmpret = lex.findToken(string_quotes_language);
759 if (tmpret != LYX_LAYOUT_DEFAULT) {
760 InsetQuotes::quote_language tmpl =
761 InsetQuotes::EnglishQ;
764 tmpl = InsetQuotes::EnglishQ;
767 tmpl = InsetQuotes::SwedishQ;
770 tmpl = InsetQuotes::GermanQ;
773 tmpl = InsetQuotes::PolishQ;
776 tmpl = InsetQuotes::FrenchQ;
779 tmpl = InsetQuotes::DanishQ;
782 params.quotes_language = tmpl;
784 } else if (token == "\\quotes_times") {
786 switch (lex.getInteger()) {
788 params.quotes_times = InsetQuotes::SingleQ;
791 params.quotes_times = InsetQuotes::DoubleQ;
794 } else if (token == "\\papersize") {
795 int tmpret = lex.findToken(string_papersize);
799 params.papersize2 = tmpret;
800 } else if (token == "\\paperpackage") {
801 int tmpret = lex.findToken(string_paperpackages);
804 params.paperpackage = BufferParams::PACKAGE_NONE;
806 params.paperpackage = tmpret;
807 } else if (token == "\\use_geometry") {
809 params.use_geometry = lex.getInteger();
810 } else if (token == "\\use_amsmath") {
812 params.use_amsmath = lex.getInteger();
813 } else if (token == "\\use_natbib") {
815 params.use_natbib = lex.getInteger();
816 } else if (token == "\\use_numerical_citations") {
818 params.use_numerical_citations = lex.getInteger();
819 } else if (token == "\\paperorientation") {
820 int tmpret = lex.findToken(string_orientation);
823 if (tmpret != LYX_LAYOUT_DEFAULT)
824 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
825 } else if (token == "\\paperwidth") {
827 params.paperwidth = lex.getString();
828 } else if (token == "\\paperheight") {
830 params.paperheight = lex.getString();
831 } else if (token == "\\leftmargin") {
833 params.leftmargin = lex.getString();
834 } else if (token == "\\topmargin") {
836 params.topmargin = lex.getString();
837 } else if (token == "\\rightmargin") {
839 params.rightmargin = lex.getString();
840 } else if (token == "\\bottommargin") {
842 params.bottommargin = lex.getString();
843 } else if (token == "\\headheight") {
845 params.headheight = lex.getString();
846 } else if (token == "\\headsep") {
848 params.headsep = lex.getString();
849 } else if (token == "\\footskip") {
851 params.footskip = lex.getString();
852 } else if (token == "\\paperfontsize") {
854 params.fontsize = strip(lex.getString());
855 } else if (token == "\\papercolumns") {
857 params.columns = lex.getInteger();
858 } else if (token == "\\papersides") {
860 switch (lex.getInteger()) {
862 case 1: params.sides = LyXTextClass::OneSide; break;
863 case 2: params.sides = LyXTextClass::TwoSides; break;
865 } else if (token == "\\paperpagestyle") {
867 params.pagestyle = strip(lex.getString());
868 } else if (token == "\\bullet") {
870 int const index = lex.getInteger();
872 int temp_int = lex.getInteger();
873 params.user_defined_bullets[index].setFont(temp_int);
874 params.temp_bullets[index].setFont(temp_int);
876 temp_int = lex.getInteger();
877 params.user_defined_bullets[index].setCharacter(temp_int);
878 params.temp_bullets[index].setCharacter(temp_int);
880 temp_int = lex.getInteger();
881 params.user_defined_bullets[index].setSize(temp_int);
882 params.temp_bullets[index].setSize(temp_int);
884 string const temp_str = lex.getString();
885 if (temp_str != "\\end_bullet") {
886 // this element isn't really necessary for
887 // parsing but is easier for humans
888 // to understand bullets. Put it back and
889 // set a debug message?
890 lex.printError("\\end_bullet expected, got" + temp_str);
891 //how can I put it back?
893 } else if (token == "\\bulletLaTeX") {
895 int const index = lex.getInteger();
897 string temp_str = lex.getString();
899 while (temp_str != "\\end_bullet") {
900 // this loop structure is needed when user
901 // enters an empty string since the first
902 // thing returned will be the \\end_bullet
904 // if the LaTeX entry has spaces. Each element
905 // therefore needs to be read in turn
908 temp_str = lex.getString();
910 params.user_defined_bullets[index].setText(sum_str);
911 params.temp_bullets[index].setText(sum_str);
912 } else if (token == "\\secnumdepth") {
914 params.secnumdepth = lex.getInteger();
915 } else if (token == "\\tocdepth") {
917 params.tocdepth = lex.getInteger();
918 } else if (token == "\\spacing") {
920 string const tmp = strip(lex.getString());
921 Spacing::Space tmp_space = Spacing::Default;
923 if (tmp == "single") {
924 tmp_space = Spacing::Single;
925 } else if (tmp == "onehalf") {
926 tmp_space = Spacing::Onehalf;
927 } else if (tmp == "double") {
928 tmp_space = Spacing::Double;
929 } else if (tmp == "other") {
931 tmp_space = Spacing::Other;
932 tmp_val = lex.getFloat();
934 lex.printError("Unknown spacing token: '$$Token'");
936 // Small hack so that files written with klyx will be
939 par->params().spacing(Spacing(tmp_space, tmp_val));
941 params.spacing.set(tmp_space, tmp_val);
943 } else if (token == "\\paragraph_spacing") {
945 string const tmp = strip(lex.getString());
946 if (tmp == "single") {
947 par->params().spacing(Spacing(Spacing::Single));
948 } else if (tmp == "onehalf") {
949 par->params().spacing(Spacing(Spacing::Onehalf));
950 } else if (tmp == "double") {
951 par->params().spacing(Spacing(Spacing::Double));
952 } else if (tmp == "other") {
954 par->params().spacing(Spacing(Spacing::Other,
957 lex.printError("Unknown spacing token: '$$Token'");
959 } else if (token == "\\float_placement") {
961 params.float_placement = lex.getString();
962 } else if (token == "\\family") {
964 font.setLyXFamily(lex.getString());
965 } else if (token == "\\series") {
967 font.setLyXSeries(lex.getString());
968 } else if (token == "\\shape") {
970 font.setLyXShape(lex.getString());
971 } else if (token == "\\size") {
973 font.setLyXSize(lex.getString());
974 #ifndef NO_COMPABILITY
975 } else if (token == "\\latex") {
977 string const tok = lex.getString();
978 if (tok == "no_latex") {
980 insertErtContents(par, pos, font);
981 } else if (tok == "latex") {
982 ert_comp.active = true;
983 } else if (tok == "default") {
985 insertErtContents(par, pos, font);
987 lex.printError("Unknown LaTeX font flag "
991 } else if (token == "\\lang") {
993 string const tok = lex.getString();
994 Language const * lang = languages.getLanguage(tok);
996 font.setLanguage(lang);
998 font.setLanguage(params.language);
999 lex.printError("Unknown language `$$Token'");
1001 } else if (token == "\\numeric") {
1003 font.setNumber(font.setLyXMisc(lex.getString()));
1004 } else if (token == "\\emph") {
1006 font.setEmph(font.setLyXMisc(lex.getString()));
1007 } else if (token == "\\bar") {
1009 string const tok = lex.getString();
1010 // This is dirty, but gone with LyX3. (Asger)
1012 font.setUnderbar(LyXFont::ON);
1013 else if (tok == "no")
1014 font.setUnderbar(LyXFont::OFF);
1015 else if (tok == "default")
1016 font.setUnderbar(LyXFont::INHERIT);
1018 lex.printError("Unknown bar font flag "
1020 } else if (token == "\\noun") {
1022 font.setNoun(font.setLyXMisc(lex.getString()));
1023 } else if (token == "\\color") {
1025 font.setLyXColor(lex.getString());
1026 } else if (token == "\\align") {
1027 int tmpret = lex.findToken(string_align);
1028 if (tmpret == -1) ++tmpret;
1029 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1030 int const tmpret2 = int(pow(2.0, tmpret));
1031 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1032 par->params().align(LyXAlignment(tmpret2));
1034 } else if (token == "\\added_space_top") {
1036 par->params().spaceTop(VSpace(lex.getString()));
1037 } else if (token == "\\added_space_bottom") {
1039 par->params().spaceBottom(VSpace(lex.getString()));
1040 #ifndef NO_COMPABILITY
1041 #ifndef NO_PEXTRA_REALLY
1042 } else if (token == "\\pextra_type") {
1044 par->params().pextraType(lex.getInteger());
1045 } else if (token == "\\pextra_width") {
1047 par->params().pextraWidth(lex.getString());
1048 } else if (token == "\\pextra_widthp") {
1050 par->params().pextraWidthp(lex.getString());
1051 } else if (token == "\\pextra_alignment") {
1053 par->params().pextraAlignment(lex.getInteger());
1054 } else if (token == "\\pextra_hfill") {
1056 par->params().pextraHfill(lex.getInteger());
1057 } else if (token == "\\pextra_start_minipage") {
1059 par->params().pextraStartMinipage(lex.getInteger());
1062 } else if (token == "\\labelwidthstring") {
1064 par->params().labelWidthString(lex.getString());
1065 // do not delete this token, it is still needed!
1066 } else if (token == "\\end_inset") {
1067 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1068 << "Last inset read was: " << last_inset_read
1070 // Simply ignore this. The insets do not have
1072 // But insets should read it, it is a part of
1073 // the inset isn't it? Lgb.
1074 } else if (token == "\\begin_inset") {
1075 #ifndef NO_COMPABILITY
1076 insertErtContents(par, pos, font, false);
1077 ert_stack.push(ert_comp);
1078 ert_comp = ErtComp();
1080 readInset(lex, par, pos, font);
1081 #ifndef NO_COMPABILITY
1082 ert_comp = ert_stack.top();
1084 insertErtContents(par, pos, font);
1086 } else if (token == "\\SpecialChar") {
1087 LyXLayout const & layout =
1088 textclasslist.Style(params.textclass,
1091 // Insets don't make sense in a free-spacing context! ---Kayvan
1092 if (layout.free_spacing || par->isFreeSpacing()) {
1095 string next_token = lex.getString();
1096 if (next_token == "\\-") {
1097 par->insertChar(pos, '-', font);
1098 } else if (next_token == "\\protected_separator"
1099 || next_token == "~") {
1100 par->insertChar(pos, ' ', font);
1102 lex.printError("Token `$$Token' "
1104 "paragraph layout!");
1109 Inset * inset = new InsetSpecialChar;
1110 inset->read(this, lex);
1111 par->insertInset(pos, inset, font);
1114 } else if (token == "\\newline") {
1115 #ifndef NO_COMPABILITY
1116 if (!ert_comp.in_tabular && ert_comp.active) {
1117 ert_comp.contents += char(Paragraph::META_NEWLINE);
1119 // Since we cannot know it this is only a regular
1120 // newline or a tabular cell delimter we have to
1121 // handle the ERT here.
1122 insertErtContents(par, pos, font, false);
1124 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1128 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1131 } else if (token == "\\LyXTable") {
1132 #ifndef NO_COMPABILITY
1133 ert_comp.in_tabular = true;
1135 Inset * inset = new InsetTabular(*this);
1136 inset->read(this, lex);
1137 par->insertInset(pos, inset, font);
1139 } else if (token == "\\hfill") {
1140 par->insertChar(pos, Paragraph::META_HFILL, font);
1142 } else if (token == "\\protected_separator") { // obsolete
1143 // This is a backward compability thingie. (Lgb)
1144 // Remove it later some time...introduced with fileformat
1146 LyXLayout const & layout =
1147 textclasslist.Style(params.textclass,
1150 if (layout.free_spacing || par->isFreeSpacing()) {
1151 par->insertChar(pos, ' ', font);
1153 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1154 par->insertInset(pos, inset, font);
1157 } else if (token == "\\bibitem") { // ale970302
1159 InsetCommandParams p("bibitem", "dummy");
1160 par->bibkey = new InsetBibKey(p);
1162 par->bibkey->read(this, lex);
1163 } else if (token == "\\backslash") {
1164 #ifndef NO_COMPABILITY
1165 if (ert_comp.active) {
1166 ert_comp.contents += "\\";
1169 par->insertChar(pos, '\\', font);
1171 #ifndef NO_COMPABILITY
1174 } else if (token == "\\the_end") {
1175 #ifndef NO_COMPABILITY
1176 // If we still have some ert active here we have to insert
1177 // it so we don't loose it. (Lgb)
1178 insertErtContents(par, pos, font);
1180 the_end_read = true;
1181 #ifndef NO_COMPABILITY
1182 #ifndef NO_PEXTRA_REALLY
1183 minipar = parBeforeMinipage = 0;
1187 #ifndef NO_COMPABILITY
1188 if (ert_comp.active) {
1189 ert_comp.contents += token;
1192 // This should be insurance for the future: (Asger)
1195 string const s = _("Unknown token: ") + token
1196 + " " + lex.text() + "\n";
1198 InsetError * new_inset = new InsetError(s);
1199 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1202 #ifndef NO_COMPABILITY
1207 #ifndef NO_COMPABILITY
1208 #ifndef NO_PEXTRA_REALLY
1209 // I wonder if we could use this blanket fix for all the
1210 // checkminipage cases...
1211 // don't forget about ert paragraphs and compatibility read for'em
1212 if (par && (par->size() || !ert_comp.contents.empty())) {
1213 // It is possible that this will check to often,
1214 // but that should not be an correctness issue.
1215 // Only a speed issue.
1216 checkminipage = true;
1219 // now check if we have a minipage paragraph as at this
1220 // point we already read all the necessary data!
1221 // this cannot be done in layout because there we did
1222 // not read yet the paragraph PEXTRA-params (Jug)
1224 // BEGIN pextra_minipage compability
1225 // This should be removed in 1.3.x (Lgb)
1226 // I don't think we should remove this so fast (Jug)
1228 // This compability code is not perfect. In a couple
1229 // of rand cases it fails. When the minipage par is
1230 // the first par in the document, and when there are
1231 // none or only one regular paragraphs after the
1232 // minipage. Currently I am not investing any effort
1233 // in fixing those cases.
1235 //lyxerr << "Call depth: " << call_depth << endl;
1236 if (checkminipage && (call_depth == 1)) {
1237 checkminipage = false;
1238 if (minipar && (minipar != par) &&
1239 (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1241 lyxerr << "minipages in a row" << endl;
1242 if (par->params().pextraStartMinipage()) {
1243 lyxerr << "start new minipage" << endl;
1244 // minipages in a row
1245 par->previous()->next(0);
1248 Paragraph * tmp = minipar;
1250 tmp->params().pextraType(0);
1251 tmp->params().pextraWidth(string());
1252 tmp->params().pextraWidthp(string());
1253 tmp->params().pextraAlignment(0);
1254 tmp->params().pextraHfill(false);
1255 tmp->params().pextraStartMinipage(false);
1258 // create a new paragraph to insert the
1259 // minipages in the following case
1260 if (par->params().pextraStartMinipage() &&
1261 !par->params().pextraHfill())
1263 Paragraph * p = new Paragraph;
1265 p->previous(parBeforeMinipage);
1266 parBeforeMinipage->next(p);
1268 p->params().depth(parBeforeMinipage->params().depth());
1269 parBeforeMinipage = p;
1271 InsetMinipage * mini = new InsetMinipage;
1272 mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1273 mini->width(par->params().pextraWidth());
1274 if (!par->params().pextraWidthp().empty()) {
1275 lyxerr << "WP:" << mini->width() << endl;
1276 mini->width(tostr(par->params().pextraWidthp())+"%");
1278 Paragraph * op = mini->firstParagraph();
1279 mini->inset.paragraph(par);
1281 // and free the old ones!
1284 Paragraph * pp = op->next();
1288 // Insert the minipage last in the
1289 // previous paragraph.
1290 if (par->params().pextraHfill()) {
1291 parBeforeMinipage->insertChar
1292 (parBeforeMinipage->size(), Paragraph::META_HFILL);
1294 parBeforeMinipage->insertInset
1295 (parBeforeMinipage->size(), mini);
1299 lyxerr << "new minipage par" << endl;
1300 //nothing to do just continue reading
1303 } else if (minipar && (minipar != par)) {
1304 lyxerr << "last minipage par read" << endl;
1305 // The last paragraph read was not part of a
1306 // minipage but the par linked list is...
1307 // So we need to remove the last par from the
1309 if (par->previous())
1310 par->previous()->next(0);
1311 par->previous(parBeforeMinipage);
1312 parBeforeMinipage->next(par);
1313 Paragraph * tmp = minipar;
1315 tmp->params().pextraType(0);
1316 tmp->params().pextraWidth(string());
1317 tmp->params().pextraWidthp(string());
1318 tmp->params().pextraAlignment(0);
1319 tmp->params().pextraHfill(false);
1320 tmp->params().pextraStartMinipage(false);
1323 depth = parBeforeMinipage->params().depth();
1324 // and set this depth on the par as it has not been set already
1325 par->params().depth(depth);
1326 minipar = parBeforeMinipage = 0;
1327 } else if (!minipar &&
1328 (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1330 // par is the first paragraph in a minipage
1331 lyxerr << "begin minipage" << endl;
1332 // To minimize problems for
1333 // the users we will insert
1334 // the first minipage in
1335 // a sequence of minipages
1336 // in its own paragraph.
1337 Paragraph * p = new Paragraph;
1339 p->previous(par->previous());
1341 p->params().depth(depth);
1342 par->params().depth(0);
1344 if (par->previous())
1345 par->previous()->next(p);
1347 parBeforeMinipage = p;
1349 if (!first_par || (first_par == par))
1352 InsetMinipage * mini = new InsetMinipage;
1353 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1354 mini->width(minipar->params().pextraWidth());
1355 if (!par->params().pextraWidthp().empty()) {
1356 lyxerr << "WP:" << mini->width() << endl;
1357 mini->width(tostr(par->params().pextraWidthp())+"%");
1359 mini->inset.paragraph(minipar);
1361 // Insert the minipage last in the
1362 // previous paragraph.
1363 if (minipar->params().pextraHfill()) {
1364 parBeforeMinipage->insertChar
1365 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1367 parBeforeMinipage->insertInset
1368 (parBeforeMinipage->size(), mini);
1371 // End of pextra_minipage compability
1375 return the_end_read;
1378 // needed to insert the selection
1379 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1380 LyXFont const & fn,string const & str) const
1382 LyXLayout const & layout = textclasslist.Style(params.textclass,
1386 (void)par->checkInsertChar(font);
1387 // insert the string, don't insert doublespace
1388 bool space_inserted = true;
1389 for(string::const_iterator cit = str.begin();
1390 cit != str.end(); ++cit) {
1392 if (par->size() || layout.keepempty) {
1393 par->breakParagraph(params, pos,
1394 layout.isEnvironment());
1397 space_inserted = true;
1401 // do not insert consecutive spaces if !free_spacing
1402 } else if ((*cit == ' ' || *cit == '\t') &&
1403 space_inserted && !layout.free_spacing &&
1404 !par->isFreeSpacing())
1407 } else if (*cit == '\t') {
1408 if (!layout.free_spacing && !par->isFreeSpacing()) {
1409 // tabs are like spaces here
1410 par->insertChar(pos, ' ', font);
1412 space_inserted = true;
1414 const pos_type nb = 8 - pos % 8;
1415 for (pos_type a = 0; a < nb ; ++a) {
1416 par->insertChar(pos, ' ', font);
1419 space_inserted = true;
1421 } else if (!IsPrintable(*cit)) {
1422 // Ignore unprintables
1425 // just insert the character
1426 par->insertChar(pos, *cit, font);
1428 space_inserted = (*cit == ' ');
1435 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1436 int & pos, LyXFont & font)
1438 // consistency check
1439 if (lex.getString() != "\\begin_inset") {
1440 lyxerr << "Buffer::readInset: Consistency check failed."
1447 string const tmptok = lex.getString();
1448 last_inset_read = tmptok;
1450 // test the different insets
1451 if (tmptok == "LatexCommand") {
1452 InsetCommandParams inscmd;
1455 string const cmdName = inscmd.getCmdName();
1457 // This strange command allows LyX to recognize "natbib" style
1458 // citations: citet, citep, Citet etc.
1459 if (compare_no_case(cmdName, "cite", 4) == 0) {
1460 inset = new InsetCitation(inscmd);
1461 } else if (cmdName == "bibitem") {
1462 lex.printError("Wrong place for bibitem");
1463 inset = new InsetBibKey(inscmd);
1464 } else if (cmdName == "BibTeX") {
1465 inset = new InsetBibtex(inscmd);
1466 } else if (cmdName == "index") {
1467 inset = new InsetIndex(inscmd);
1468 } else if (cmdName == "include") {
1469 inset = new InsetInclude(inscmd, *this);
1470 } else if (cmdName == "label") {
1471 inset = new InsetLabel(inscmd);
1472 } else if (cmdName == "url"
1473 || cmdName == "htmlurl") {
1474 inset = new InsetUrl(inscmd);
1475 } else if (cmdName == "ref"
1476 || cmdName == "pageref"
1477 || cmdName == "vref"
1478 || cmdName == "vpageref"
1479 || cmdName == "prettyref") {
1480 if (!inscmd.getOptions().empty()
1481 || !inscmd.getContents().empty()) {
1482 inset = new InsetRef(inscmd, *this);
1484 } else if (cmdName == "tableofcontents") {
1485 inset = new InsetTOC(inscmd);
1486 } else if (cmdName == "listofalgorithms") {
1487 inset = new InsetFloatList("algorithm");
1488 } else if (cmdName == "listoffigures") {
1489 inset = new InsetFloatList("figure");
1490 } else if (cmdName == "listoftables") {
1491 inset = new InsetFloatList("table");
1492 } else if (cmdName == "printindex") {
1493 inset = new InsetPrintIndex(inscmd);
1494 } else if (cmdName == "lyxparent") {
1495 inset = new InsetParent(inscmd, *this);
1498 bool alreadyread = false;
1499 if (tmptok == "Quotes") {
1500 inset = new InsetQuotes;
1501 } else if (tmptok == "External") {
1502 inset = new InsetExternal;
1503 } else if (tmptok == "FormulaMacro") {
1504 inset = new InsetFormulaMacro;
1505 } else if (tmptok == "Formula") {
1506 inset = new InsetFormula;
1507 } else if (tmptok == "Figure") { // Backward compatibility
1508 inset = new InsetFig(100, 100, *this);
1509 //inset = new InsetGraphics;
1510 } else if (tmptok == "Graphics") {
1511 inset = new InsetGraphics;
1512 } else if (tmptok == "Info") {// backwards compatibility
1513 inset = new InsetNote(this,
1514 lex.getLongString("\\end_inset"),
1517 } else if (tmptok == "Note") {
1518 inset = new InsetNote;
1519 } else if (tmptok == "Include") {
1520 InsetCommandParams p( "Include" );
1521 inset = new InsetInclude(p, *this);
1522 } else if (tmptok == "ERT") {
1523 inset = new InsetERT;
1524 } else if (tmptok == "Tabular") {
1525 inset = new InsetTabular(*this);
1526 } else if (tmptok == "Text") {
1527 inset = new InsetText;
1528 } else if (tmptok == "Foot") {
1529 inset = new InsetFoot;
1530 } else if (tmptok == "Marginal") {
1531 inset = new InsetMarginal;
1532 } else if (tmptok == "Minipage") {
1533 inset = new InsetMinipage;
1534 } else if (tmptok == "Float") {
1536 string tmptok = lex.getString();
1537 inset = new InsetFloat(tmptok);
1539 } else if (tmptok == "List") {
1540 inset = new InsetList;
1541 } else if (tmptok == "Theorem") {
1542 inset = new InsetList;
1544 } else if (tmptok == "Caption") {
1545 inset = new InsetCaption;
1546 } else if (tmptok == "FloatList") {
1547 inset = new InsetFloatList;
1550 if (inset && !alreadyread) inset->read(this, lex);
1554 par->insertInset(pos, inset, font);
1560 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1564 string const token(lex.getString());
1565 if (token == "\\lyxformat") { // the first token _must_ be...
1567 string tmp_format = lex.getString();
1568 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1569 // if present remove ".," from string.
1570 string::size_type dot = tmp_format.find_first_of(".,");
1571 //lyxerr << " dot found at " << dot << endl;
1572 if (dot != string::npos)
1573 tmp_format.erase(dot, 1);
1574 file_format = strToInt(tmp_format);
1575 if (file_format == LYX_FORMAT) {
1577 } else if (file_format > LYX_FORMAT) {
1579 Alert::alert(_("Warning!"),
1580 _("LyX file format is newer that what"),
1581 _("is supported in this LyX version. Expect some problems."));
1583 } else if (file_format < LYX_FORMAT) {
1585 if (file_format < 200) {
1586 Alert::alert(_("ERROR!"),
1587 _("Old LyX file format found. "
1588 "Use LyX 0.10.x to read this!"));
1592 bool the_end = readLyXformat2(lex, par);
1593 params.setPaperStuff();
1594 // the_end was added in 213
1595 if (file_format < 213)
1599 Alert::alert(_("Warning!"),
1600 _("Reading of document is not complete"),
1601 _("Maybe the document is truncated"));
1604 } else { // "\\lyxformat" not found
1605 Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1608 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1613 // Should probably be moved to somewhere else: BufferView? LyXView?
1614 bool Buffer::save() const
1616 // We don't need autosaves in the immediate future. (Asger)
1617 resetAutosaveTimers();
1621 if (lyxrc.make_backup) {
1622 s = fileName() + '~';
1623 if (!lyxrc.backupdir_path.empty())
1624 s = AddName(lyxrc.backupdir_path,
1625 subst(os::slashify_path(s),'/','!'));
1627 // Rename is the wrong way of making a backup,
1628 // this is the correct way.
1629 /* truss cp fil fil2:
1630 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1631 stat("LyXVC.lyx", 0xEFFFF688) = 0
1632 open("LyXVC.lyx", O_RDONLY) = 3
1633 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1634 fstat(4, 0xEFFFF508) = 0
1635 fstat(3, 0xEFFFF508) = 0
1636 read(3, " # T h i s f i l e w".., 8192) = 5579
1637 write(4, " # T h i s f i l e w".., 5579) = 5579
1638 read(3, 0xEFFFD4A0, 8192) = 0
1641 chmod("LyXVC3.lyx", 0100644) = 0
1642 lseek(0, 0, SEEK_CUR) = 46440
1646 // Should probably have some more error checking here.
1647 // Should be cleaned up in 0.13, at least a bit.
1648 // Doing it this way, also makes the inodes stay the same.
1649 // This is still not a very good solution, in particular we
1650 // might loose the owner of the backup.
1651 FileInfo finfo(fileName());
1652 if (finfo.exist()) {
1653 mode_t fmode = finfo.getMode();
1654 struct utimbuf times = {
1655 finfo.getAccessTime(),
1656 finfo.getModificationTime() };
1658 ifstream ifs(fileName().c_str());
1659 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1664 ::chmod(s.c_str(), fmode);
1666 if (::utime(s.c_str(), ×)) {
1667 lyxerr << "utime error." << endl;
1670 lyxerr << "LyX was not able to make "
1671 "backup copy. Beware." << endl;
1676 if (writeFile(fileName(), false)) {
1678 removeAutosaveFile(fileName());
1680 // Saving failed, so backup is not backup
1681 if (lyxrc.make_backup) {
1682 lyx::rename(s, fileName());
1690 // Returns false if unsuccesful
1691 bool Buffer::writeFile(string const & fname, bool flag) const
1693 // if flag is false writeFile will not create any GUI
1694 // warnings, only cerr.
1695 // Needed for autosave in background or panic save (Matthias 120496)
1697 if (read_only && (fname == filename)) {
1698 // Here we should come with a question if we should
1699 // perform the write anyway.
1701 lyxerr << _("Error! Document is read-only: ")
1704 Alert::alert(_("Error! Document is read-only: "),
1709 FileInfo finfo(fname);
1710 if (finfo.exist() && !finfo.writable()) {
1711 // Here we should come with a question if we should
1712 // try to do the save anyway. (i.e. do a chmod first)
1714 lyxerr << _("Error! Cannot write file: ")
1717 Alert::err_alert(_("Error! Cannot write file: "),
1722 ofstream ofs(fname.c_str());
1725 lyxerr << _("Error! Cannot open file: ")
1728 Alert::err_alert(_("Error! Cannot open file: "),
1734 // Use the standard "C" locale for file output.
1735 ofs.imbue(std::locale::classic());
1738 // The top of the file should not be written by params.
1740 // write out a comment in the top of the file
1741 ofs << '#' << lyx_docversion
1742 << " created this file. For more info see http://www.lyx.org/\n"
1743 << "\\lyxformat " << LYX_FORMAT << "\n";
1745 // now write out the buffer paramters.
1746 params.writeFile(ofs);
1748 Paragraph::depth_type depth = 0;
1750 // this will write out all the paragraphs
1751 // using recursive descent.
1752 paragraph->writeFile(this, ofs, params, depth);
1754 // Write marker that shows file is complete
1755 ofs << "\n\\the_end" << endl;
1759 // how to check if close went ok?
1760 // Following is an attempt... (BE 20001011)
1762 // good() returns false if any error occured, including some
1763 // formatting error.
1764 // bad() returns true if something bad happened in the buffer,
1765 // which should include file system full errors.
1772 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1774 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1784 string const Buffer::asciiParagraph(Paragraph const * par,
1785 unsigned int linelen,
1786 bool noparbreak) const
1788 ostringstream buffer;
1790 Paragraph::depth_type depth = 0;
1792 Paragraph::depth_type ltype_depth = 0;
1793 string::size_type currlinelen = 0;
1794 bool ref_printed = false;
1795 // if (!par->previous()) {
1797 // begins or ends a deeper area ?
1798 if (depth != par->params().depth()) {
1799 if (par->params().depth() > depth) {
1800 while (par->params().depth() > depth) {
1804 while (par->params().depth() < depth) {
1810 depth = par->params().depth();
1813 // First write the layout
1814 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1815 if (tmp == "Itemize") {
1817 ltype_depth = depth + 1;
1818 } else if (tmp == "Enumerate") {
1820 ltype_depth = depth + 1;
1821 } else if (contains(tmp, "ection")) {
1823 ltype_depth = depth + 1;
1824 } else if (contains(tmp, "aragraph")) {
1826 ltype_depth = depth + 1;
1827 } else if (tmp == "Description") {
1829 ltype_depth = depth + 1;
1830 } else if (tmp == "Abstract") {
1833 } else if (tmp == "Bibliography") {
1841 /* maybe some vertical spaces */
1843 /* the labelwidthstring used in lists */
1847 /* some pagebreaks? */
1851 /* what about the alignment */
1853 // lyxerr << "Should this ever happen?" << endl;
1856 // linelen <= 0 is special and means we don't have pargraph breaks
1860 for (Paragraph::depth_type j = 0; j < depth; ++j)
1862 currlinelen = depth * 2;
1864 // we should probably change to the paragraph language in the
1865 // gettext here (if possible) so that strings are outputted in
1866 // the correct language! (20012712 Jug)
1870 case 4: // (Sub)Paragraph
1871 case 5: // Description
1875 buffer << _("Abstract") << "\n\n";
1877 buffer << _("Abstract: ");
1879 case 7: // Bibliography
1882 buffer << _("References") << "\n\n";
1884 buffer << _("References: ");
1889 buffer << par->params().labelString() << " ";
1893 string s = buffer.str();
1894 if (s.rfind('\n') != string::npos) {
1896 s = rsplit(buffer.str().c_str(), dummy, '\n');
1898 currlinelen = s.length();
1900 for (Paragraph::depth_type j = 0; j < depth; ++j)
1902 currlinelen = depth * 2;
1903 if (ltype_depth > depth) {
1904 for (Paragraph::depth_type j = ltype_depth;
1909 currlinelen += (ltype_depth-depth)*2;
1912 // this is to change the linebreak to do it by word a bit more intelligent
1913 // hopefully! (only in the case where we have a max linelenght!) (Jug)
1914 for (pos_type i = 0; i < par->size(); ++i) {
1915 char c = par->getUChar(params, i);
1917 case Paragraph::META_INSET:
1919 Inset const * inset = par->getInset(i);
1922 buffer << word.str();
1923 if (inset->ascii(this, buffer, linelen)) {
1924 // to be sure it breaks paragraph
1925 currlinelen += linelen;
1931 rsplit(buffer.str().c_str(),
1933 currlinelen = s.length();
1940 case Paragraph::META_NEWLINE:
1942 buffer << word.str() << "\n";
1944 for (Paragraph::depth_type j = 0;
1947 currlinelen = depth * 2;
1948 if (ltype_depth > depth) {
1949 for (Paragraph::depth_type j = ltype_depth;
1952 currlinelen += (ltype_depth - depth) * 2;
1957 case Paragraph::META_HFILL:
1958 buffer << word.str() << "\t";
1959 currlinelen += word.str().length() + 1;
1965 buffer << word.str() << ' ';
1966 currlinelen += word.str().length() + 1;
1972 lyxerr[Debug::INFO] <<
1973 "writeAsciiFile: NULL char in structure." << endl;
1975 if ((linelen > 0) &&
1976 (currlinelen+word.str().length()) > linelen)
1979 for (Paragraph::depth_type j = 0; j < depth; ++j)
1981 currlinelen = depth * 2;
1982 if (ltype_depth > depth) {
1983 for (Paragraph::depth_type j = ltype_depth;
1988 currlinelen += (ltype_depth-depth)*2;
1995 buffer << word.str();
1996 return buffer.str().c_str();
2000 void Buffer::writeFileAscii(string const & fname, int linelen)
2002 ofstream ofs(fname.c_str());
2004 Alert::err_alert(_("Error: Cannot write file:"), fname);
2007 writeFileAscii(ofs, linelen);
2011 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2013 Paragraph * par = paragraph;
2015 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2025 void Buffer::makeLaTeXFile(string const & fname,
2026 string const & original_path,
2027 bool nice, bool only_body)
2029 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2031 niceFile = nice; // this will be used by Insetincludes.
2033 tex_code_break_column = lyxrc.ascii_linelen;
2035 LyXTextClass const & tclass =
2036 textclasslist.TextClass(params.textclass);
2038 ofstream ofs(fname.c_str());
2040 Alert::err_alert(_("Error: Cannot open file: "), fname);
2044 // validate the buffer.
2045 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2046 LaTeXFeatures features(params, tclass.numLayouts());
2048 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2051 // The starting paragraph of the coming rows is the
2052 // first paragraph of the document. (Asger)
2053 texrow.start(paragraph, 0);
2055 if (!only_body && nice) {
2056 ofs << "%% " << lyx_docversion << " created this file. "
2057 "For more info, see http://www.lyx.org/.\n"
2058 "%% Do not edit unless you really know what "
2063 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2064 // There are a few differences between nice LaTeX and usual files:
2065 // usual is \batchmode and has a
2066 // special input@path to allow the including of figures
2067 // with either \input or \includegraphics (what figinsets do).
2068 // batchmode is not set if there is a tex_code_break_column.
2069 // In this case somebody is interested in the generated LaTeX,
2070 // so this is OK. input@path is set when the actual parameter
2071 // original_path is set. This is done for usual tex-file, but not
2072 // for nice-latex-file. (Matthias 250696)
2075 // code for usual, NOT nice-latex-file
2076 ofs << "\\batchmode\n"; // changed
2077 // from \nonstopmode
2080 if (!original_path.empty()) {
2081 ofs << "\\makeatletter\n"
2082 << "\\def\\input@path{{"
2083 << os::external_path(original_path) << "/}}\n"
2084 << "\\makeatother\n";
2090 ofs << "\\documentclass";
2092 ostringstream options; // the document class options.
2094 if (tokenPos(tclass.opt_fontsize(),
2095 '|', params.fontsize) >= 0) {
2096 // only write if existing in list (and not default)
2097 options << params.fontsize << "pt,";
2101 if (!params.use_geometry &&
2102 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2103 switch (params.papersize) {
2104 case BufferParams::PAPER_A4PAPER:
2105 options << "a4paper,";
2107 case BufferParams::PAPER_USLETTER:
2108 options << "letterpaper,";
2110 case BufferParams::PAPER_A5PAPER:
2111 options << "a5paper,";
2113 case BufferParams::PAPER_B5PAPER:
2114 options << "b5paper,";
2116 case BufferParams::PAPER_EXECUTIVEPAPER:
2117 options << "executivepaper,";
2119 case BufferParams::PAPER_LEGALPAPER:
2120 options << "legalpaper,";
2126 if (params.sides != tclass.sides()) {
2127 switch (params.sides) {
2128 case LyXTextClass::OneSide:
2129 options << "oneside,";
2131 case LyXTextClass::TwoSides:
2132 options << "twoside,";
2138 if (params.columns != tclass.columns()) {
2139 if (params.columns == 2)
2140 options << "twocolumn,";
2142 options << "onecolumn,";
2145 if (!params.use_geometry
2146 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2147 options << "landscape,";
2149 // language should be a parameter to \documentclass
2151 ostringstream language_options;
2152 if (params.language->babel() == "hebrew"
2153 && default_language->babel() != "hebrew")
2154 // This seems necessary
2155 features.useLanguage(default_language);
2157 if (lyxrc.language_use_babel ||
2158 params.language->lang() != lyxrc.default_language ||
2159 !features.hasLanguages()) {
2161 language_options << features.getLanguages();
2162 language_options << params.language->babel();
2163 if (lyxrc.language_global_options)
2164 options << language_options.str() << ',';
2167 // the user-defined options
2168 if (!params.options.empty()) {
2169 options << params.options << ',';
2172 string strOptions(options.str().c_str());
2173 if (!strOptions.empty()){
2174 strOptions = strip(strOptions, ',');
2175 ofs << '[' << strOptions << ']';
2179 << textclasslist.LatexnameOfClass(params.textclass)
2182 // end of \documentclass defs
2184 // font selection must be done before loading fontenc.sty
2185 // The ae package is not needed when using OT1 font encoding.
2186 if (params.fonts != "default" &&
2187 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2188 ofs << "\\usepackage{" << params.fonts << "}\n";
2190 if (params.fonts == "ae") {
2191 ofs << "\\usepackage{aecompl}\n";
2195 // this one is not per buffer
2196 if (lyxrc.fontenc != "default") {
2197 ofs << "\\usepackage[" << lyxrc.fontenc
2202 if (params.inputenc == "auto") {
2203 string const doc_encoding =
2204 params.language->encoding()->LatexName();
2206 // Create a list with all the input encodings used
2208 set<string> encodings = features.getEncodingSet(doc_encoding);
2210 ofs << "\\usepackage[";
2211 std::copy(encodings.begin(), encodings.end(),
2212 std::ostream_iterator<string>(ofs, ","));
2213 ofs << doc_encoding << "]{inputenc}\n";
2215 } else if (params.inputenc != "default") {
2216 ofs << "\\usepackage[" << params.inputenc
2221 // At the very beginning the text parameters.
2222 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2223 switch (params.paperpackage) {
2224 case BufferParams::PACKAGE_A4:
2225 ofs << "\\usepackage{a4}\n";
2228 case BufferParams::PACKAGE_A4WIDE:
2229 ofs << "\\usepackage{a4wide}\n";
2232 case BufferParams::PACKAGE_WIDEMARGINSA4:
2233 ofs << "\\usepackage[widemargins]{a4}\n";
2238 if (params.use_geometry) {
2239 ofs << "\\usepackage{geometry}\n";
2241 ofs << "\\geometry{verbose";
2242 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2243 ofs << ",landscape";
2244 switch (params.papersize2) {
2245 case BufferParams::VM_PAPER_CUSTOM:
2246 if (!params.paperwidth.empty())
2247 ofs << ",paperwidth="
2248 << params.paperwidth;
2249 if (!params.paperheight.empty())
2250 ofs << ",paperheight="
2251 << params.paperheight;
2253 case BufferParams::VM_PAPER_USLETTER:
2254 ofs << ",letterpaper";
2256 case BufferParams::VM_PAPER_USLEGAL:
2257 ofs << ",legalpaper";
2259 case BufferParams::VM_PAPER_USEXECUTIVE:
2260 ofs << ",executivepaper";
2262 case BufferParams::VM_PAPER_A3:
2265 case BufferParams::VM_PAPER_A4:
2268 case BufferParams::VM_PAPER_A5:
2271 case BufferParams::VM_PAPER_B3:
2274 case BufferParams::VM_PAPER_B4:
2277 case BufferParams::VM_PAPER_B5:
2281 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2282 switch (lyxrc.default_papersize) {
2283 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2284 case BufferParams::PAPER_USLETTER:
2285 ofs << ",letterpaper";
2287 case BufferParams::PAPER_LEGALPAPER:
2288 ofs << ",legalpaper";
2290 case BufferParams::PAPER_EXECUTIVEPAPER:
2291 ofs << ",executivepaper";
2293 case BufferParams::PAPER_A3PAPER:
2296 case BufferParams::PAPER_A4PAPER:
2299 case BufferParams::PAPER_A5PAPER:
2302 case BufferParams::PAPER_B5PAPER:
2307 if (!params.topmargin.empty())
2308 ofs << ",tmargin=" << params.topmargin;
2309 if (!params.bottommargin.empty())
2310 ofs << ",bmargin=" << params.bottommargin;
2311 if (!params.leftmargin.empty())
2312 ofs << ",lmargin=" << params.leftmargin;
2313 if (!params.rightmargin.empty())
2314 ofs << ",rmargin=" << params.rightmargin;
2315 if (!params.headheight.empty())
2316 ofs << ",headheight=" << params.headheight;
2317 if (!params.headsep.empty())
2318 ofs << ",headsep=" << params.headsep;
2319 if (!params.footskip.empty())
2320 ofs << ",footskip=" << params.footskip;
2325 if (features.isRequired("amsstyle")
2326 && !tclass.provides(LyXTextClass::amsmath)) {
2327 ofs << "\\usepackage{amsmath}\n";
2331 if (tokenPos(tclass.opt_pagestyle(),
2332 '|', params.pagestyle) >= 0) {
2333 if (params.pagestyle == "fancy") {
2334 ofs << "\\usepackage{fancyhdr}\n";
2337 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2341 if (params.secnumdepth != tclass.secnumdepth()) {
2342 ofs << "\\setcounter{secnumdepth}{"
2343 << params.secnumdepth
2347 if (params.tocdepth != tclass.tocdepth()) {
2348 ofs << "\\setcounter{tocdepth}{"
2354 if (params.paragraph_separation) {
2355 switch (params.defskip.kind()) {
2356 case VSpace::SMALLSKIP:
2357 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2359 case VSpace::MEDSKIP:
2360 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2362 case VSpace::BIGSKIP:
2363 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2365 case VSpace::LENGTH:
2366 ofs << "\\setlength\\parskip{"
2367 << params.defskip.length().asLatexString()
2370 default: // should never happen // Then delete it.
2371 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2376 ofs << "\\setlength\\parindent{0pt}\n";
2380 // Now insert the LyX specific LaTeX commands...
2382 // The optional packages;
2383 string preamble(features.getPackages());
2385 // this might be useful...
2386 preamble += "\n\\makeatletter\n";
2388 // Some macros LyX will need
2389 string tmppreamble(features.getMacros());
2391 if (!tmppreamble.empty()) {
2392 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2393 "LyX specific LaTeX commands.\n"
2394 + tmppreamble + '\n';
2397 // the text class specific preamble
2398 tmppreamble = features.getTClassPreamble();
2399 if (!tmppreamble.empty()) {
2400 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2401 "Textclass specific LaTeX commands.\n"
2402 + tmppreamble + '\n';
2405 /* the user-defined preamble */
2406 if (!params.preamble.empty()) {
2407 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2408 "User specified LaTeX commands.\n"
2409 + params.preamble + '\n';
2412 preamble += "\\makeatother\n";
2414 // Itemize bullet settings need to be last in case the user
2415 // defines their own bullets that use a package included
2416 // in the user-defined preamble -- ARRae
2417 // Actually it has to be done much later than that
2418 // since some packages like frenchb make modifications
2419 // at \begin{document} time -- JMarc
2421 for (int i = 0; i < 4; ++i) {
2422 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2423 if (bullets_def.empty())
2424 bullets_def="\\AtBeginDocument{\n";
2425 bullets_def += " \\renewcommand{\\labelitemi";
2427 // `i' is one less than the item to modify
2434 bullets_def += "ii";
2440 bullets_def += "}{" +
2441 params.user_defined_bullets[i].getText()
2446 if (!bullets_def.empty())
2447 preamble += bullets_def + "}\n\n";
2449 for (int j = countChar(preamble, '\n'); j-- ;) {
2455 // We try to load babel late, in case it interferes
2456 // with other packages.
2458 string tmp = lyxrc.language_package;
2459 if (!lyxrc.language_global_options
2460 && tmp == "\\usepackage{babel}")
2461 tmp = string("\\usepackage[") +
2462 language_options.str().c_str() +
2469 ofs << "\\begin{document}\n";
2472 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2474 if (!lyxrc.language_auto_begin) {
2475 ofs << subst(lyxrc.language_command_begin, "$$lang",
2476 params.language->babel())
2481 latexParagraphs(ofs, paragraph, 0, texrow);
2483 // add this just in case after all the paragraphs
2487 if (!lyxrc.language_auto_end) {
2488 ofs << subst(lyxrc.language_command_end, "$$lang",
2489 params.language->babel())
2495 ofs << "\\end{document}\n";
2498 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2500 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2504 // Just to be sure. (Asger)
2507 // tex_code_break_column's value is used to decide
2508 // if we are in batchmode or not (within mathed_write()
2509 // in math_write.C) so we must set it to a non-zero
2510 // value when we leave otherwise we save incorrect .lyx files.
2511 tex_code_break_column = lyxrc.ascii_linelen;
2515 lyxerr << "File was not closed properly." << endl;
2518 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2519 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2524 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2526 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2527 Paragraph * endpar, TexRow & texrow) const
2529 bool was_title = false;
2530 bool already_title = false;
2533 while (par != endpar) {
2534 LyXLayout const & layout =
2535 textclasslist.Style(params.textclass,
2538 if (layout.intitle) {
2539 if (already_title) {
2540 lyxerr <<"Error in latexParagraphs: You"
2541 " should not mix title layouts"
2542 " with normal ones." << endl;
2545 } else if (was_title && !already_title) {
2546 ofs << "\\maketitle\n";
2548 already_title = true;
2552 if (layout.isEnvironment()) {
2553 par = par->TeXEnvironment(this, params, ofs, texrow);
2555 par = par->TeXOnePar(this, params, ofs, texrow, false);
2558 // It might be that we only have a title in this document
2559 if (was_title && !already_title) {
2560 ofs << "\\maketitle\n";
2566 bool Buffer::isLatex() const
2568 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2572 bool Buffer::isLinuxDoc() const
2574 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2578 bool Buffer::isLiterate() const
2580 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2584 bool Buffer::isDocBook() const
2586 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2590 bool Buffer::isSGML() const
2592 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2593 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2597 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2598 string const & latexname) const
2600 if (!latexname.empty() && latexname != "!-- --")
2601 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2602 os << string(depth, ' ') << "<" << latexname << ">\n";
2606 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2607 string const & latexname) const
2609 if (!latexname.empty() && latexname != "!-- --")
2610 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2611 os << string(depth, ' ') << "</" << latexname << ">\n";
2615 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2617 ofstream ofs(fname.c_str());
2620 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2624 niceFile = nice; // this will be used by included files.
2626 LyXTextClass const & tclass =
2627 textclasslist.TextClass(params.textclass);
2629 LaTeXFeatures features(params, tclass.numLayouts());
2634 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2637 ofs << "<!doctype linuxdoc system";
2639 string preamble = params.preamble;
2640 preamble += features.getIncludedFiles(fname);
2641 preamble += features.getLyXSGMLEntities();
2643 if (!preamble.empty()) {
2644 ofs << " [ " << preamble << " ]";
2648 if (params.options.empty())
2649 sgmlOpenTag(ofs, 0, top_element);
2651 string top = top_element;
2653 top += params.options;
2654 sgmlOpenTag(ofs, 0, top);
2658 ofs << "<!-- " << lyx_docversion
2659 << " created this file. For more info see http://www.lyx.org/"
2662 Paragraph::depth_type depth = 0; // paragraph depth
2663 Paragraph * par = paragraph;
2665 vector<string> environment_stack(5);
2668 LyXLayout const & style =
2669 textclasslist.Style(params.textclass,
2672 // treat <toc> as a special case for compatibility with old code
2673 if (par->isInset(0)) {
2674 Inset * inset = par->getInset(0);
2675 Inset::Code lyx_code = inset->lyxCode();
2676 if (lyx_code == Inset::TOC_CODE){
2677 string const temp = "toc";
2678 sgmlOpenTag(ofs, depth, temp);
2685 // environment tag closing
2686 for (; depth > par->params().depth(); --depth) {
2687 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2688 environment_stack[depth].erase();
2691 // write opening SGML tags
2692 switch (style.latextype) {
2693 case LATEX_PARAGRAPH:
2694 if (depth == par->params().depth()
2695 && !environment_stack[depth].empty()) {
2696 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2697 environment_stack[depth].erase();
2703 sgmlOpenTag(ofs, depth, style.latexname());
2709 _("Error : Wrong depth for"
2710 " LatexType Command.\n"));
2712 if (!environment_stack[depth].empty()){
2713 sgmlCloseTag(ofs, depth,
2714 environment_stack[depth]);
2718 environment_stack[depth].erase();
2719 sgmlOpenTag(ofs, depth, style.latexname());
2722 case LATEX_ENVIRONMENT:
2723 case LATEX_ITEM_ENVIRONMENT:
2724 if (depth == par->params().depth()
2725 && environment_stack[depth] != style.latexname()) {
2726 sgmlCloseTag(ofs, depth,
2727 environment_stack[depth]);
2728 environment_stack[depth].erase();
2730 if (depth < par->params().depth()) {
2731 depth = par->params().depth();
2732 environment_stack[depth].erase();
2734 if (environment_stack[depth] != style.latexname()) {
2736 sgmlOpenTag(ofs, depth, "p");
2738 sgmlOpenTag(ofs, depth, style.latexname());
2740 if (environment_stack.size() == depth + 1)
2741 environment_stack.push_back("!-- --");
2742 environment_stack[depth] = style.latexname();
2745 if (style.latexparam() == "CDATA")
2748 if (style.latextype == LATEX_ENVIRONMENT) break;
2750 if (style.labeltype == LABEL_MANUAL)
2755 sgmlOpenTag(ofs, depth + 1, item_name);
2758 sgmlOpenTag(ofs, depth, style.latexname());
2762 simpleLinuxDocOnePar(ofs, par, depth);
2767 // write closing SGML tags
2768 switch (style.latextype) {
2771 case LATEX_ENVIRONMENT:
2772 case LATEX_ITEM_ENVIRONMENT:
2773 if (style.latexparam() == "CDATA")
2777 sgmlCloseTag(ofs, depth, style.latexname());
2783 for (int i=depth; i >= 0; --i)
2784 sgmlCloseTag(ofs, depth, environment_stack[i]);
2788 sgmlCloseTag(ofs, 0, top_element);
2792 // How to check for successful close
2796 // checks, if newcol chars should be put into this line
2797 // writes newline, if necessary.
2800 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2801 string::size_type newcol)
2804 if (colcount > lyxrc.ascii_linelen) {
2806 colcount = newcol; // assume write after this call
2821 string tag_name(PAR_TAG const & pt) {
2823 case NONE: return "!-- --";
2824 case TT: return "tt";
2825 case SF: return "sf";
2826 case BF: return "bf";
2827 case IT: return "it";
2828 case SL: return "sl";
2829 case EM: return "em";
2836 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2838 p1 = static_cast<PAR_TAG>(p1 | p2);
2843 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2845 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2851 // Handle internal paragraph parsing -- layout already processed.
2852 void Buffer::simpleLinuxDocOnePar(ostream & os,
2854 Paragraph::depth_type /*depth*/)
2856 LyXLayout const & style = textclasslist.Style(params.textclass,
2858 string::size_type char_line_count = 5; // Heuristic choice ;-)
2860 // gets paragraph main font
2863 if (style.labeltype == LABEL_MANUAL) {
2864 font_old = style.labelfont;
2867 font_old = style.font;
2871 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2872 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2873 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2876 stack<PAR_TAG> tag_state;
2877 // parsing main loop
2878 for (pos_type i = 0; i < par->size(); ++i) {
2880 PAR_TAG tag_close = NONE;
2881 list < PAR_TAG > tag_open;
2883 LyXFont const font = par->getFont(params, i);
2885 if (font_old.family() != font.family()) {
2886 switch (family_type) {
2887 case LyXFont::SANS_FAMILY:
2890 case LyXFont::TYPEWRITER_FAMILY:
2897 family_type = font.family();
2899 switch (family_type) {
2900 case LyXFont::SANS_FAMILY:
2901 tag_open.push_back(SF);
2903 case LyXFont::TYPEWRITER_FAMILY:
2904 tag_open.push_back(TT);
2911 if (font_old.series() != font.series()) {
2912 switch (series_type) {
2913 case LyXFont::BOLD_SERIES:
2920 series_type = font.series();
2922 switch (series_type) {
2923 case LyXFont::BOLD_SERIES:
2924 tag_open.push_back(BF);
2932 if (font_old.shape() != font.shape()) {
2933 switch (shape_type) {
2934 case LyXFont::ITALIC_SHAPE:
2937 case LyXFont::SLANTED_SHAPE:
2944 shape_type = font.shape();
2946 switch (shape_type) {
2947 case LyXFont::ITALIC_SHAPE:
2948 tag_open.push_back(IT);
2950 case LyXFont::SLANTED_SHAPE:
2951 tag_open.push_back(SL);
2958 if (font_old.emph() != font.emph()) {
2959 if (font.emph() == LyXFont::ON) {
2960 tag_open.push_back(EM);
2969 list < PAR_TAG > temp;
2970 while (!tag_state.empty() && tag_close ) {
2971 PAR_TAG k = tag_state.top();
2973 os << "</" << tag_name(k) << ">";
2980 for(list< PAR_TAG >::const_iterator j = temp.begin();
2981 j != temp.end(); ++j) {
2983 os << "<" << tag_name(*j) << ">";
2986 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2987 j != tag_open.end(); ++j) {
2989 os << "<" << tag_name(*j) << ">";
2992 char c = par->getChar(i);
2994 if (c == Paragraph::META_INSET) {
2995 Inset * inset = par->getInset(i);
2996 inset->linuxdoc(this, os);
3001 if (style.latexparam() == "CDATA") {
3002 // "TeX"-Mode on == > SGML-Mode on.
3008 if (par->sgmlConvertChar(c, sgml_string)
3009 && !style.free_spacing && !par->isFreeSpacing())
3011 // in freespacing mode, spaces are
3012 // non-breaking characters
3013 if (desc_on) {// if char is ' ' then...
3016 sgmlLineBreak(os, char_line_count, 6);
3020 sgmlLineBreak(os, char_line_count, 1);
3025 char_line_count += sgml_string.length();
3031 while (!tag_state.empty()) {
3032 os << "</" << tag_name(tag_state.top()) << ">";
3036 // resets description flag correctly
3038 // <tag> not closed...
3039 sgmlLineBreak(os, char_line_count, 6);
3045 // Print an error message.
3046 void Buffer::sgmlError(Paragraph * par, int pos,
3047 string const & message) const
3049 // insert an error marker in text
3050 InsetError * new_inset = new InsetError(message);
3051 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3056 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3058 ofstream ofs(fname.c_str());
3060 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3064 Paragraph * par = paragraph;
3066 niceFile = nice; // this will be used by Insetincludes.
3068 LyXTextClass const & tclass =
3069 textclasslist.TextClass(params.textclass);
3071 LaTeXFeatures features(params, tclass.numLayouts());
3076 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3079 ofs << "<!DOCTYPE " << top_element
3080 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3082 string preamble = params.preamble;
3083 preamble += features.getIncludedFiles(fname);
3084 preamble += features.getLyXSGMLEntities();
3086 if (!preamble.empty()) {
3087 ofs << "\n [ " << preamble << " ]";
3092 string top = top_element;
3094 top += params.language->code();
3097 if (!params.options.empty()) {
3099 top += params.options;
3101 sgmlOpenTag(ofs, 0, top);
3103 ofs << "<!-- DocBook file was created by " << lyx_docversion
3104 << "\n See http://www.lyx.org/ for more information -->\n";
3106 vector<string> environment_stack(10);
3107 vector<string> environment_inner(10);
3108 vector<string> command_stack(10);
3110 bool command_flag = false;
3111 Paragraph::depth_type command_depth = 0;
3112 Paragraph::depth_type command_base = 0;
3113 Paragraph::depth_type cmd_depth = 0;
3114 Paragraph::depth_type depth = 0; // paragraph depth
3117 string command_name;
3123 int desc_on = 0; // description mode
3125 LyXLayout const & style =
3126 textclasslist.Style(params.textclass,
3129 // environment tag closing
3130 for (; depth > par->params().depth(); --depth) {
3131 if (environment_inner[depth] != "!-- --") {
3132 item_name = "listitem";
3133 sgmlCloseTag(ofs, command_depth + depth,
3135 if (environment_inner[depth] == "varlistentry")
3136 sgmlCloseTag(ofs, depth+command_depth,
3137 environment_inner[depth]);
3139 sgmlCloseTag(ofs, depth + command_depth,
3140 environment_stack[depth]);
3141 environment_stack[depth].erase();
3142 environment_inner[depth].erase();
3145 if (depth == par->params().depth()
3146 && environment_stack[depth] != style.latexname()
3147 && !environment_stack[depth].empty()) {
3148 if (environment_inner[depth] != "!-- --") {
3149 item_name= "listitem";
3150 sgmlCloseTag(ofs, command_depth+depth,
3152 if (environment_inner[depth] == "varlistentry")
3154 depth + command_depth,
3155 environment_inner[depth]);
3158 sgmlCloseTag(ofs, depth + command_depth,
3159 environment_stack[depth]);
3161 environment_stack[depth].erase();
3162 environment_inner[depth].erase();
3165 // Write opening SGML tags.
3166 switch (style.latextype) {
3167 case LATEX_PARAGRAPH:
3168 sgmlOpenTag(ofs, depth + command_depth,
3175 _("Error : Wrong depth for "
3176 "LatexType Command.\n"));
3178 command_name = style.latexname();
3180 sgmlparam = style.latexparam();
3181 c_params = split(sgmlparam, c_depth,'|');
3183 cmd_depth = lyx::atoi(c_depth);
3186 if (cmd_depth < command_base) {
3187 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3188 sgmlCloseTag(ofs, j, command_stack[j]);
3189 command_depth = command_base = cmd_depth;
3190 } else if (cmd_depth <= command_depth) {
3191 for (int j = command_depth; j >= int(cmd_depth); --j)
3192 sgmlCloseTag(ofs, j, command_stack[j]);
3193 command_depth = cmd_depth;
3195 command_depth = cmd_depth;
3197 command_depth = command_base = cmd_depth;
3198 command_flag = true;
3200 if (command_stack.size() == command_depth + 1)
3201 command_stack.push_back(string());
3202 command_stack[command_depth] = command_name;
3204 // treat label as a special case for
3205 // more WYSIWYM handling.
3206 // This is a hack while paragraphs can't have
3207 // attributes, like id in this case.
3208 if (par->isInset(0)) {
3209 Inset * inset = par->getInset(0);
3210 Inset::Code lyx_code = inset->lyxCode();
3211 if (lyx_code == Inset::LABEL_CODE){
3212 command_name += " id=\"";
3213 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3214 command_name += "\"";
3219 sgmlOpenTag(ofs, depth + command_depth, command_name);
3220 if (c_params.empty())
3221 item_name = "title";
3223 item_name = c_params;
3224 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3227 case LATEX_ENVIRONMENT:
3228 case LATEX_ITEM_ENVIRONMENT:
3229 if (depth < par->params().depth()) {
3230 depth = par->params().depth();
3231 environment_stack[depth].erase();
3234 if (environment_stack[depth] != style.latexname()) {
3235 if(environment_stack.size() == depth + 1) {
3236 environment_stack.push_back("!-- --");
3237 environment_inner.push_back("!-- --");
3239 environment_stack[depth] = style.latexname();
3240 environment_inner[depth] = "!-- --";
3241 sgmlOpenTag(ofs, depth + command_depth,
3242 environment_stack[depth]);
3244 if (environment_inner[depth] != "!-- --") {
3245 item_name= "listitem";
3247 command_depth + depth,
3249 if (environment_inner[depth] == "varlistentry")
3251 depth + command_depth,
3252 environment_inner[depth]);
3256 if (style.latextype == LATEX_ENVIRONMENT) {
3257 if (!style.latexparam().empty()) {
3258 if(style.latexparam() == "CDATA")
3261 sgmlOpenTag(ofs, depth + command_depth,
3262 style.latexparam());
3267 desc_on = (style.labeltype == LABEL_MANUAL);
3270 environment_inner[depth]= "varlistentry";
3272 environment_inner[depth]= "listitem";
3274 sgmlOpenTag(ofs, depth + 1 + command_depth,
3275 environment_inner[depth]);
3279 sgmlOpenTag(ofs, depth + 1 + command_depth,
3283 sgmlOpenTag(ofs, depth + 1 + command_depth,
3288 sgmlOpenTag(ofs, depth + command_depth,
3293 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3297 // write closing SGML tags
3298 switch (style.latextype) {
3300 if (c_params.empty())
3304 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3306 case LATEX_ENVIRONMENT:
3307 if (!style.latexparam().empty()) {
3308 if(style.latexparam() == "CDATA")
3311 sgmlCloseTag(ofs, depth + command_depth,
3312 style.latexparam());
3315 case LATEX_ITEM_ENVIRONMENT:
3316 if (desc_on == 1) break;
3318 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3320 case LATEX_PARAGRAPH:
3321 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3324 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3330 for (int d = depth; d >= 0; --d) {
3331 if (!environment_stack[depth].empty()) {
3332 if (environment_inner[depth] != "!-- --") {
3333 item_name = "listitem";
3334 sgmlCloseTag(ofs, command_depth + depth,
3336 if (environment_inner[depth] == "varlistentry")
3337 sgmlCloseTag(ofs, depth + command_depth,
3338 environment_inner[depth]);
3341 sgmlCloseTag(ofs, depth + command_depth,
3342 environment_stack[depth]);
3346 for (int j = command_depth; j >= 0 ; --j)
3347 if (!command_stack[j].empty())
3348 sgmlCloseTag(ofs, j, command_stack[j]);
3351 sgmlCloseTag(ofs, 0, top_element);
3354 // How to check for successful close
3358 void Buffer::simpleDocBookOnePar(ostream & os,
3359 Paragraph * par, int & desc_on,
3360 Paragraph::depth_type depth) const
3362 bool emph_flag = false;
3364 LyXLayout const & style = textclasslist.Style(params.textclass,
3367 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3369 int char_line_count = depth;
3370 //if (!style.free_spacing)
3371 // os << string(depth,' ');
3373 // parsing main loop
3374 for (pos_type i = 0; i < par->size(); ++i) {
3375 LyXFont font = par->getFont(params, i);
3377 // handle <emphasis> tag
3378 if (font_old.emph() != font.emph()) {
3379 if (font.emph() == LyXFont::ON) {
3383 os << "</emphasis>";
3389 if ( par->isInset(i) ) {
3390 Inset * inset = par->getInset(i);
3391 // don't print the inset in position 0 if desc_on == 3 (label)
3392 if ( i || desc_on != 3)
3393 inset->docbook(this, os);
3395 char c = par->getChar(i);
3397 par->sgmlConvertChar(c, sgml_string);
3399 if (style.pass_thru) {
3401 } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
3403 } else if (desc_on ==1) {
3405 os << "\n</term><listitem><para>";
3415 os << "</emphasis>";
3418 // resets description flag correctly
3420 // <term> not closed...
3423 if(style.free_spacing) os << '\n';
3427 // This should be enabled when the Chktex class is implemented. (Asger)
3428 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3429 // Other flags: -wall -v0 -x
3430 int Buffer::runChktex()
3432 if (!users->text) return 0;
3434 users->owner()->prohibitInput();
3436 // get LaTeX-Filename
3437 string const name = getLatexName();
3438 string path = OnlyPath(filename);
3440 string const org_path = path;
3441 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3445 Path p(path); // path to LaTeX file
3446 users->owner()->message(_("Running chktex..."));
3448 // Remove all error insets
3449 bool const removedErrorInsets = users->removeAutoInsets();
3451 // Generate the LaTeX file if neccessary
3452 makeLaTeXFile(name, org_path, false);
3455 Chktex chktex(lyxrc.chktex_command, name, filepath);
3456 int res = chktex.run(terr); // run chktex
3459 Alert::alert(_("chktex did not work!"),
3460 _("Could not run with file:"), name);
3461 } else if (res > 0) {
3462 // Insert all errors as errors boxes
3463 users->insertErrors(terr);
3466 // if we removed error insets before we ran chktex or if we inserted
3467 // error insets after we ran chktex, this must be run:
3468 if (removedErrorInsets || res){
3472 users->owner()->allowInput();
3478 void Buffer::validate(LaTeXFeatures & features) const
3480 Paragraph * par = paragraph;
3481 LyXTextClass const & tclass =
3482 textclasslist.TextClass(params.textclass);
3484 // AMS Style is at document level
3485 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3486 features.require("amsstyle");
3489 // We don't use "lyxerr.debug" because of speed. (Asger)
3490 if (lyxerr.debugging(Debug::LATEX))
3491 lyxerr << "Paragraph: " << par << endl;
3493 // Now just follow the list of paragraphs and run
3494 // validate on each of them.
3495 par->validate(features);
3497 // and then the next paragraph
3501 // the bullet shapes are buffer level not paragraph level
3502 // so they are tested here
3503 for (int i = 0; i < 4; ++i) {
3504 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3505 int const font = params.user_defined_bullets[i].getFont();
3507 int const c = params
3508 .user_defined_bullets[i]
3515 features.require("latexsym");
3517 } else if (font == 1) {
3518 features.require("amssymb");
3519 } else if ((font >= 2 && font <= 5)) {
3520 features.require("pifont");
3525 if (lyxerr.debugging(Debug::LATEX)) {
3526 features.showStruct();
3531 // This function should be in Buffer because it's a buffer's property (ale)
3532 string const Buffer::getIncludeonlyList(char delim)
3535 for (inset_iterator it = inset_iterator_begin();
3536 it != inset_iterator_end(); ++it) {
3537 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3538 InsetInclude * insetinc =
3539 static_cast<InsetInclude *>(*it);
3540 if (insetinc->isIncludeOnly()) {
3543 lst += insetinc->getRelFileBaseName();
3547 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3552 vector<string> const Buffer::getLabelList()
3554 /// if this is a child document and the parent is already loaded
3555 /// Use the parent's list instead [ale990407]
3556 if (!params.parentname.empty()
3557 && bufferlist.exists(params.parentname)) {
3558 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3560 return tmp->getLabelList();
3563 vector<string> label_list;
3564 for (inset_iterator it = inset_iterator_begin();
3565 it != inset_iterator_end(); ++it) {
3566 vector<string> const l = (*it)->getLabelList();
3567 label_list.insert(label_list.end(), l.begin(), l.end());
3573 Buffer::Lists const Buffer::getLists() const
3576 Paragraph * par = paragraph;
3579 std::pair<bool, textclass_type> const tmp =
3580 textclasslist.NumberOfLayout(params.textclass, "Caption");
3581 bool const found = tmp.first;
3582 textclass_type const cap = tmp.second;
3585 // This is the prefered way to to this, but boost::tie can break
3589 boost::tie(found, cap) = textclasslist
3590 .NumberOfLayout(params.textclass, "Caption");
3594 char const labeltype =
3595 textclasslist.Style(params.textclass,
3596 par->getLayout()).labeltype;
3598 if (labeltype >= LABEL_COUNTER_CHAPTER
3599 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3600 // insert this into the table of contents
3601 SingleList & item = l["TOC"];
3604 textclasslist.TextClass(params.textclass).maxcounter());
3605 item.push_back(TocItem(par, depth, par->asString(this, true)));
3607 // For each paragrph, traverse its insets and look for
3611 Paragraph::inset_iterator it =
3612 par->inset_iterator_begin();
3613 Paragraph::inset_iterator end =
3614 par->inset_iterator_end();
3616 for (; it != end; ++it) {
3617 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3619 static_cast<InsetFloat*>(*it);
3621 string const type = il->type();
3623 // Now find the caption in the float...
3624 // We now tranverse the paragraphs of
3626 Paragraph * tmp = il->inset.paragraph();
3628 if (tmp->layout == cap) {
3629 SingleList & item = l[type];
3631 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3632 item.push_back(TocItem(tmp, 0 , str));
3639 lyxerr << "caption not found" << endl;
3648 // This is also a buffer property (ale)
3649 vector<pair<string, string> > const Buffer::getBibkeyList()
3651 /// if this is a child document and the parent is already loaded
3652 /// Use the parent's list instead [ale990412]
3653 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3654 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3656 return tmp->getBibkeyList();
3659 vector<pair<string, string> > keys;
3660 Paragraph * par = paragraph;
3663 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3664 par->asString(this, false)));
3668 // Might be either using bibtex or a child has bibliography
3670 for (inset_iterator it = inset_iterator_begin();
3671 it != inset_iterator_end(); ++it) {
3672 // Search for Bibtex or Include inset
3673 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3674 vector<pair<string,string> > tmp =
3675 static_cast<InsetBibtex*>(*it)->getKeys(this);
3676 keys.insert(keys.end(), tmp.begin(), tmp.end());
3677 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3678 vector<pair<string,string> > const tmp =
3679 static_cast<InsetInclude*>(*it)->getKeys();
3680 keys.insert(keys.end(), tmp.begin(), tmp.end());
3689 bool Buffer::isDepClean(string const & name) const
3691 DEPCLEAN * item = dep_clean;
3692 while (item && item->master != name)
3694 if (!item) return true;
3699 void Buffer::markDepClean(string const & name)
3702 dep_clean = new DEPCLEAN;
3703 dep_clean->clean = true;
3704 dep_clean->master = name;
3705 dep_clean->next = 0;
3707 DEPCLEAN * item = dep_clean;
3708 while (item && item->master != name)
3713 item = new DEPCLEAN;
3715 item->master = name;
3722 bool Buffer::dispatch(string const & command)
3724 // Split command string into command and argument
3726 string line = frontStrip(command);
3727 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3729 return dispatch(lyxaction.LookupFunc(cmd), arg);
3733 bool Buffer::dispatch(int action, string const & argument)
3735 bool dispatched = true;
3738 Exporter::Export(this, argument, false);
3748 void Buffer::resizeInsets(BufferView * bv)
3750 /// then remove all LyXText in text-insets
3751 Paragraph * par = paragraph;
3752 for (; par; par = par->next()) {
3753 par->resizeInsetsLyXText(bv);
3758 void Buffer::redraw()
3765 void Buffer::changeLanguage(Language const * from, Language const * to)
3768 ParIterator end = par_iterator_end();
3769 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3770 (*it)->changeLanguage(params, from, to);
3774 bool Buffer::isMultiLingual()
3776 ParIterator end = par_iterator_end();
3777 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3778 if ((*it)->isMultiLingual(params))
3785 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3788 it = par->InsetIterator(pos);
3789 if (it == par->inset_iterator_end()) {
3796 void Buffer::inset_iterator::setParagraph()
3799 it = par->inset_iterator_begin();
3800 if (it != par->inset_iterator_end())
3805 // We maintain an invariant that whenever par = 0 then it = 0
3809 Inset * Buffer::getInsetFromID(int id_arg) const
3811 for (inset_iterator it = inset_const_iterator_begin();
3812 it != inset_const_iterator_end(); ++it)
3814 if ((*it)->id() == id_arg)
3816 Inset * in = (*it)->getInsetFromID(id_arg);
3824 Paragraph * Buffer::getParFromID(int id) const
3826 if (id < 0) return 0;
3827 Paragraph * par = paragraph;
3829 if (par->id() == id) {
3832 Paragraph * tmp = par->getParFromID(id);
3842 ParIterator Buffer::par_iterator_begin()
3844 return ParIterator(paragraph);
3848 ParIterator Buffer::par_iterator_end()
3850 return ParIterator();