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();
1925 if (inset->ascii(this, buffer, linelen)) {
1926 // to be sure it breaks paragraph
1927 currlinelen += linelen;
1933 rsplit(buffer.str().c_str(),
1935 currlinelen = s.length();
1942 case Paragraph::META_NEWLINE:
1944 buffer << word.str() << "\n";
1946 for (Paragraph::depth_type j = 0;
1949 currlinelen = depth * 2;
1950 if (ltype_depth > depth) {
1951 for (Paragraph::depth_type j = ltype_depth;
1954 currlinelen += (ltype_depth - depth) * 2;
1959 case Paragraph::META_HFILL:
1960 buffer << word.str() << "\t";
1961 currlinelen += word.str().length() + 1;
1967 buffer << word.str() << ' ';
1968 currlinelen += word.str().length() + 1;
1974 lyxerr[Debug::INFO] <<
1975 "writeAsciiFile: NULL char in structure." << endl;
1977 if ((linelen > 0) &&
1978 (currlinelen+word.str().length()) > linelen)
1981 for (Paragraph::depth_type j = 0; j < depth; ++j)
1983 currlinelen = depth * 2;
1984 if (ltype_depth > depth) {
1985 for (Paragraph::depth_type j = ltype_depth;
1990 currlinelen += (ltype_depth-depth)*2;
1997 buffer << word.str();
1998 return buffer.str().c_str();
2002 void Buffer::writeFileAscii(string const & fname, int linelen)
2004 ofstream ofs(fname.c_str());
2006 Alert::err_alert(_("Error: Cannot write file:"), fname);
2009 writeFileAscii(ofs, linelen);
2013 void Buffer::writeFileAscii(ostream & ofs, int linelen)
2015 Paragraph * par = paragraph;
2017 ofs << asciiParagraph(par, linelen, par->previous() == 0);
2027 void Buffer::makeLaTeXFile(string const & fname,
2028 string const & original_path,
2029 bool nice, bool only_body)
2031 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2033 niceFile = nice; // this will be used by Insetincludes.
2035 tex_code_break_column = lyxrc.ascii_linelen;
2037 LyXTextClass const & tclass =
2038 textclasslist.TextClass(params.textclass);
2040 ofstream ofs(fname.c_str());
2042 Alert::err_alert(_("Error: Cannot open file: "), fname);
2046 // validate the buffer.
2047 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
2048 LaTeXFeatures features(params, tclass.numLayouts());
2050 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
2053 // The starting paragraph of the coming rows is the
2054 // first paragraph of the document. (Asger)
2055 texrow.start(paragraph, 0);
2057 if (!only_body && nice) {
2058 ofs << "%% " << lyx_docversion << " created this file. "
2059 "For more info, see http://www.lyx.org/.\n"
2060 "%% Do not edit unless you really know what "
2065 lyxerr[Debug::INFO] << "lyx header finished" << endl;
2066 // There are a few differences between nice LaTeX and usual files:
2067 // usual is \batchmode and has a
2068 // special input@path to allow the including of figures
2069 // with either \input or \includegraphics (what figinsets do).
2070 // batchmode is not set if there is a tex_code_break_column.
2071 // In this case somebody is interested in the generated LaTeX,
2072 // so this is OK. input@path is set when the actual parameter
2073 // original_path is set. This is done for usual tex-file, but not
2074 // for nice-latex-file. (Matthias 250696)
2077 // code for usual, NOT nice-latex-file
2078 ofs << "\\batchmode\n"; // changed
2079 // from \nonstopmode
2082 if (!original_path.empty()) {
2083 ofs << "\\makeatletter\n"
2084 << "\\def\\input@path{{"
2085 << os::external_path(original_path) << "/}}\n"
2086 << "\\makeatother\n";
2092 ofs << "\\documentclass";
2094 ostringstream options; // the document class options.
2096 if (tokenPos(tclass.opt_fontsize(),
2097 '|', params.fontsize) >= 0) {
2098 // only write if existing in list (and not default)
2099 options << params.fontsize << "pt,";
2103 if (!params.use_geometry &&
2104 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2105 switch (params.papersize) {
2106 case BufferParams::PAPER_A4PAPER:
2107 options << "a4paper,";
2109 case BufferParams::PAPER_USLETTER:
2110 options << "letterpaper,";
2112 case BufferParams::PAPER_A5PAPER:
2113 options << "a5paper,";
2115 case BufferParams::PAPER_B5PAPER:
2116 options << "b5paper,";
2118 case BufferParams::PAPER_EXECUTIVEPAPER:
2119 options << "executivepaper,";
2121 case BufferParams::PAPER_LEGALPAPER:
2122 options << "legalpaper,";
2128 if (params.sides != tclass.sides()) {
2129 switch (params.sides) {
2130 case LyXTextClass::OneSide:
2131 options << "oneside,";
2133 case LyXTextClass::TwoSides:
2134 options << "twoside,";
2140 if (params.columns != tclass.columns()) {
2141 if (params.columns == 2)
2142 options << "twocolumn,";
2144 options << "onecolumn,";
2147 if (!params.use_geometry
2148 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2149 options << "landscape,";
2151 // language should be a parameter to \documentclass
2153 ostringstream language_options;
2154 if (params.language->babel() == "hebrew"
2155 && default_language->babel() != "hebrew")
2156 // This seems necessary
2157 features.useLanguage(default_language);
2159 if (lyxrc.language_use_babel ||
2160 params.language->lang() != lyxrc.default_language ||
2161 !features.hasLanguages()) {
2163 language_options << features.getLanguages();
2164 language_options << params.language->babel();
2165 if (lyxrc.language_global_options)
2166 options << language_options.str() << ',';
2169 // the user-defined options
2170 if (!params.options.empty()) {
2171 options << params.options << ',';
2174 string strOptions(options.str().c_str());
2175 if (!strOptions.empty()){
2176 strOptions = strip(strOptions, ',');
2177 ofs << '[' << strOptions << ']';
2181 << textclasslist.LatexnameOfClass(params.textclass)
2184 // end of \documentclass defs
2186 // font selection must be done before loading fontenc.sty
2187 // The ae package is not needed when using OT1 font encoding.
2188 if (params.fonts != "default" &&
2189 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2190 ofs << "\\usepackage{" << params.fonts << "}\n";
2192 if (params.fonts == "ae") {
2193 ofs << "\\usepackage{aecompl}\n";
2197 // this one is not per buffer
2198 if (lyxrc.fontenc != "default") {
2199 ofs << "\\usepackage[" << lyxrc.fontenc
2204 if (params.inputenc == "auto") {
2205 string const doc_encoding =
2206 params.language->encoding()->LatexName();
2208 // Create a list with all the input encodings used
2210 set<string> encodings = features.getEncodingSet(doc_encoding);
2212 ofs << "\\usepackage[";
2213 std::copy(encodings.begin(), encodings.end(),
2214 std::ostream_iterator<string>(ofs, ","));
2215 ofs << doc_encoding << "]{inputenc}\n";
2217 } else if (params.inputenc != "default") {
2218 ofs << "\\usepackage[" << params.inputenc
2223 // At the very beginning the text parameters.
2224 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2225 switch (params.paperpackage) {
2226 case BufferParams::PACKAGE_A4:
2227 ofs << "\\usepackage{a4}\n";
2230 case BufferParams::PACKAGE_A4WIDE:
2231 ofs << "\\usepackage{a4wide}\n";
2234 case BufferParams::PACKAGE_WIDEMARGINSA4:
2235 ofs << "\\usepackage[widemargins]{a4}\n";
2240 if (params.use_geometry) {
2241 ofs << "\\usepackage{geometry}\n";
2243 ofs << "\\geometry{verbose";
2244 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2245 ofs << ",landscape";
2246 switch (params.papersize2) {
2247 case BufferParams::VM_PAPER_CUSTOM:
2248 if (!params.paperwidth.empty())
2249 ofs << ",paperwidth="
2250 << params.paperwidth;
2251 if (!params.paperheight.empty())
2252 ofs << ",paperheight="
2253 << params.paperheight;
2255 case BufferParams::VM_PAPER_USLETTER:
2256 ofs << ",letterpaper";
2258 case BufferParams::VM_PAPER_USLEGAL:
2259 ofs << ",legalpaper";
2261 case BufferParams::VM_PAPER_USEXECUTIVE:
2262 ofs << ",executivepaper";
2264 case BufferParams::VM_PAPER_A3:
2267 case BufferParams::VM_PAPER_A4:
2270 case BufferParams::VM_PAPER_A5:
2273 case BufferParams::VM_PAPER_B3:
2276 case BufferParams::VM_PAPER_B4:
2279 case BufferParams::VM_PAPER_B5:
2283 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2284 switch (lyxrc.default_papersize) {
2285 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2286 case BufferParams::PAPER_USLETTER:
2287 ofs << ",letterpaper";
2289 case BufferParams::PAPER_LEGALPAPER:
2290 ofs << ",legalpaper";
2292 case BufferParams::PAPER_EXECUTIVEPAPER:
2293 ofs << ",executivepaper";
2295 case BufferParams::PAPER_A3PAPER:
2298 case BufferParams::PAPER_A4PAPER:
2301 case BufferParams::PAPER_A5PAPER:
2304 case BufferParams::PAPER_B5PAPER:
2309 if (!params.topmargin.empty())
2310 ofs << ",tmargin=" << params.topmargin;
2311 if (!params.bottommargin.empty())
2312 ofs << ",bmargin=" << params.bottommargin;
2313 if (!params.leftmargin.empty())
2314 ofs << ",lmargin=" << params.leftmargin;
2315 if (!params.rightmargin.empty())
2316 ofs << ",rmargin=" << params.rightmargin;
2317 if (!params.headheight.empty())
2318 ofs << ",headheight=" << params.headheight;
2319 if (!params.headsep.empty())
2320 ofs << ",headsep=" << params.headsep;
2321 if (!params.footskip.empty())
2322 ofs << ",footskip=" << params.footskip;
2327 if (tokenPos(tclass.opt_pagestyle(),
2328 '|', params.pagestyle) >= 0) {
2329 if (params.pagestyle == "fancy") {
2330 ofs << "\\usepackage{fancyhdr}\n";
2333 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2337 if (params.secnumdepth != tclass.secnumdepth()) {
2338 ofs << "\\setcounter{secnumdepth}{"
2339 << params.secnumdepth
2343 if (params.tocdepth != tclass.tocdepth()) {
2344 ofs << "\\setcounter{tocdepth}{"
2350 if (params.paragraph_separation) {
2351 switch (params.defskip.kind()) {
2352 case VSpace::SMALLSKIP:
2353 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2355 case VSpace::MEDSKIP:
2356 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2358 case VSpace::BIGSKIP:
2359 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2361 case VSpace::LENGTH:
2362 ofs << "\\setlength\\parskip{"
2363 << params.defskip.length().asLatexString()
2366 default: // should never happen // Then delete it.
2367 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2372 ofs << "\\setlength\\parindent{0pt}\n";
2376 // Now insert the LyX specific LaTeX commands...
2378 // The optional packages;
2379 string preamble(features.getPackages());
2381 // this might be useful...
2382 preamble += "\n\\makeatletter\n";
2384 // Some macros LyX will need
2385 string tmppreamble(features.getMacros());
2387 if (!tmppreamble.empty()) {
2388 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2389 "LyX specific LaTeX commands.\n"
2390 + tmppreamble + '\n';
2393 // the text class specific preamble
2394 tmppreamble = features.getTClassPreamble();
2395 if (!tmppreamble.empty()) {
2396 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2397 "Textclass specific LaTeX commands.\n"
2398 + tmppreamble + '\n';
2401 /* the user-defined preamble */
2402 if (!params.preamble.empty()) {
2403 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2404 "User specified LaTeX commands.\n"
2405 + params.preamble + '\n';
2408 preamble += "\\makeatother\n";
2410 // Itemize bullet settings need to be last in case the user
2411 // defines their own bullets that use a package included
2412 // in the user-defined preamble -- ARRae
2413 // Actually it has to be done much later than that
2414 // since some packages like frenchb make modifications
2415 // at \begin{document} time -- JMarc
2417 for (int i = 0; i < 4; ++i) {
2418 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2419 if (bullets_def.empty())
2420 bullets_def="\\AtBeginDocument{\n";
2421 bullets_def += " \\renewcommand{\\labelitemi";
2423 // `i' is one less than the item to modify
2430 bullets_def += "ii";
2436 bullets_def += "}{" +
2437 params.user_defined_bullets[i].getText()
2442 if (!bullets_def.empty())
2443 preamble += bullets_def + "}\n\n";
2445 for (int j = countChar(preamble, '\n'); j-- ;) {
2451 // We try to load babel late, in case it interferes
2452 // with other packages.
2454 string tmp = lyxrc.language_package;
2455 if (!lyxrc.language_global_options
2456 && tmp == "\\usepackage{babel}")
2457 tmp = string("\\usepackage[") +
2458 language_options.str().c_str() +
2465 ofs << "\\begin{document}\n";
2468 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2470 if (!lyxrc.language_auto_begin) {
2471 ofs << subst(lyxrc.language_command_begin, "$$lang",
2472 params.language->babel())
2477 latexParagraphs(ofs, paragraph, 0, texrow);
2479 // add this just in case after all the paragraphs
2483 if (!lyxrc.language_auto_end) {
2484 ofs << subst(lyxrc.language_command_end, "$$lang",
2485 params.language->babel())
2491 ofs << "\\end{document}\n";
2494 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2496 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2500 // Just to be sure. (Asger)
2503 // tex_code_break_column's value is used to decide
2504 // if we are in batchmode or not (within mathed_write()
2505 // in math_write.C) so we must set it to a non-zero
2506 // value when we leave otherwise we save incorrect .lyx files.
2507 tex_code_break_column = lyxrc.ascii_linelen;
2511 lyxerr << "File was not closed properly." << endl;
2514 lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2515 lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2520 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2522 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2523 Paragraph * endpar, TexRow & texrow) const
2525 bool was_title = false;
2526 bool already_title = false;
2529 while (par != endpar) {
2530 Inset * in = par->inInset();
2531 // well we have to check if we are in an inset with unlimited
2532 // lenght (all in one row) if that is true then we don't allow
2533 // any special options in the paragraph and also we don't allow
2534 // any environment other then "Standard" to be valid!
2535 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2536 LyXLayout const & layout =
2537 textclasslist.Style(params.textclass, par->layout);
2539 if (layout.intitle) {
2540 if (already_title) {
2541 lyxerr <<"Error in latexParagraphs: You"
2542 " should not mix title layouts"
2543 " with normal ones." << endl;
2546 } else if (was_title && !already_title) {
2547 ofs << "\\maketitle\n";
2549 already_title = true;
2553 if (layout.isEnvironment()) {
2554 par = par->TeXEnvironment(this, params, ofs, texrow);
2556 par = par->TeXOnePar(this, params, ofs, texrow, false);
2559 par = par->TeXOnePar(this, params, ofs, texrow, false);
2562 // It might be that we only have a title in this document
2563 if (was_title && !already_title) {
2564 ofs << "\\maketitle\n";
2570 bool Buffer::isLatex() const
2572 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2576 bool Buffer::isLinuxDoc() const
2578 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2582 bool Buffer::isLiterate() const
2584 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2588 bool Buffer::isDocBook() const
2590 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2594 bool Buffer::isSGML() const
2596 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2597 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2601 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2602 string const & latexname) const
2604 if (!latexname.empty() && latexname != "!-- --")
2605 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2606 os << string(depth, ' ') << "<" << latexname << ">\n";
2610 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2611 string const & latexname) const
2613 if (!latexname.empty() && latexname != "!-- --")
2614 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2615 os << string(depth, ' ') << "</" << latexname << ">\n";
2619 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2621 ofstream ofs(fname.c_str());
2624 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2628 niceFile = nice; // this will be used by included files.
2630 LyXTextClass const & tclass =
2631 textclasslist.TextClass(params.textclass);
2633 LaTeXFeatures features(params, tclass.numLayouts());
2638 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2641 ofs << "<!doctype linuxdoc system";
2643 string preamble = params.preamble;
2644 preamble += features.getIncludedFiles(fname);
2645 preamble += features.getLyXSGMLEntities();
2647 if (!preamble.empty()) {
2648 ofs << " [ " << preamble << " ]";
2652 if (params.options.empty())
2653 sgmlOpenTag(ofs, 0, top_element);
2655 string top = top_element;
2657 top += params.options;
2658 sgmlOpenTag(ofs, 0, top);
2662 ofs << "<!-- " << lyx_docversion
2663 << " created this file. For more info see http://www.lyx.org/"
2666 Paragraph::depth_type depth = 0; // paragraph depth
2667 Paragraph * par = paragraph;
2669 vector<string> environment_stack(5);
2672 LyXLayout const & style =
2673 textclasslist.Style(params.textclass,
2676 // treat <toc> as a special case for compatibility with old code
2677 if (par->isInset(0)) {
2678 Inset * inset = par->getInset(0);
2679 Inset::Code lyx_code = inset->lyxCode();
2680 if (lyx_code == Inset::TOC_CODE){
2681 string const temp = "toc";
2682 sgmlOpenTag(ofs, depth, temp);
2689 // environment tag closing
2690 for (; depth > par->params().depth(); --depth) {
2691 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2692 environment_stack[depth].erase();
2695 // write opening SGML tags
2696 switch (style.latextype) {
2697 case LATEX_PARAGRAPH:
2698 if (depth == par->params().depth()
2699 && !environment_stack[depth].empty()) {
2700 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2701 environment_stack[depth].erase();
2707 sgmlOpenTag(ofs, depth, style.latexname());
2713 _("Error : Wrong depth for"
2714 " LatexType Command.\n"));
2716 if (!environment_stack[depth].empty()){
2717 sgmlCloseTag(ofs, depth,
2718 environment_stack[depth]);
2722 environment_stack[depth].erase();
2723 sgmlOpenTag(ofs, depth, style.latexname());
2726 case LATEX_ENVIRONMENT:
2727 case LATEX_ITEM_ENVIRONMENT:
2728 if (depth == par->params().depth()
2729 && environment_stack[depth] != style.latexname()) {
2730 sgmlCloseTag(ofs, depth,
2731 environment_stack[depth]);
2732 environment_stack[depth].erase();
2734 if (depth < par->params().depth()) {
2735 depth = par->params().depth();
2736 environment_stack[depth].erase();
2738 if (environment_stack[depth] != style.latexname()) {
2740 sgmlOpenTag(ofs, depth, "p");
2742 sgmlOpenTag(ofs, depth, style.latexname());
2744 if (environment_stack.size() == depth + 1)
2745 environment_stack.push_back("!-- --");
2746 environment_stack[depth] = style.latexname();
2749 if (style.latexparam() == "CDATA")
2752 if (style.latextype == LATEX_ENVIRONMENT) break;
2754 if (style.labeltype == LABEL_MANUAL)
2759 sgmlOpenTag(ofs, depth + 1, item_name);
2762 sgmlOpenTag(ofs, depth, style.latexname());
2766 simpleLinuxDocOnePar(ofs, par, depth);
2771 // write closing SGML tags
2772 switch (style.latextype) {
2775 case LATEX_ENVIRONMENT:
2776 case LATEX_ITEM_ENVIRONMENT:
2777 if (style.latexparam() == "CDATA")
2781 sgmlCloseTag(ofs, depth, style.latexname());
2787 for (int i=depth; i >= 0; --i)
2788 sgmlCloseTag(ofs, depth, environment_stack[i]);
2792 sgmlCloseTag(ofs, 0, top_element);
2796 // How to check for successful close
2800 // checks, if newcol chars should be put into this line
2801 // writes newline, if necessary.
2804 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2805 string::size_type newcol)
2808 if (colcount > lyxrc.ascii_linelen) {
2810 colcount = newcol; // assume write after this call
2825 string tag_name(PAR_TAG const & pt) {
2827 case NONE: return "!-- --";
2828 case TT: return "tt";
2829 case SF: return "sf";
2830 case BF: return "bf";
2831 case IT: return "it";
2832 case SL: return "sl";
2833 case EM: return "em";
2840 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2842 p1 = static_cast<PAR_TAG>(p1 | p2);
2847 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2849 p1 = static_cast<PAR_TAG>( p1 & ~p2);
2855 // Handle internal paragraph parsing -- layout already processed.
2856 void Buffer::simpleLinuxDocOnePar(ostream & os,
2858 Paragraph::depth_type /*depth*/)
2860 LyXLayout const & style = textclasslist.Style(params.textclass,
2862 string::size_type char_line_count = 5; // Heuristic choice ;-)
2864 // gets paragraph main font
2867 if (style.labeltype == LABEL_MANUAL) {
2868 font_old = style.labelfont;
2871 font_old = style.font;
2875 LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2876 LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2877 LyXFont::FONT_SHAPE shape_type = LyXFont::UP_SHAPE;
2880 stack<PAR_TAG> tag_state;
2881 // parsing main loop
2882 for (pos_type i = 0; i < par->size(); ++i) {
2884 PAR_TAG tag_close = NONE;
2885 list < PAR_TAG > tag_open;
2887 LyXFont const font = par->getFont(params, i);
2889 if (font_old.family() != font.family()) {
2890 switch (family_type) {
2891 case LyXFont::SANS_FAMILY:
2894 case LyXFont::TYPEWRITER_FAMILY:
2901 family_type = font.family();
2903 switch (family_type) {
2904 case LyXFont::SANS_FAMILY:
2905 tag_open.push_back(SF);
2907 case LyXFont::TYPEWRITER_FAMILY:
2908 tag_open.push_back(TT);
2915 if (font_old.series() != font.series()) {
2916 switch (series_type) {
2917 case LyXFont::BOLD_SERIES:
2924 series_type = font.series();
2926 switch (series_type) {
2927 case LyXFont::BOLD_SERIES:
2928 tag_open.push_back(BF);
2936 if (font_old.shape() != font.shape()) {
2937 switch (shape_type) {
2938 case LyXFont::ITALIC_SHAPE:
2941 case LyXFont::SLANTED_SHAPE:
2948 shape_type = font.shape();
2950 switch (shape_type) {
2951 case LyXFont::ITALIC_SHAPE:
2952 tag_open.push_back(IT);
2954 case LyXFont::SLANTED_SHAPE:
2955 tag_open.push_back(SL);
2962 if (font_old.emph() != font.emph()) {
2963 if (font.emph() == LyXFont::ON) {
2964 tag_open.push_back(EM);
2973 list < PAR_TAG > temp;
2974 while (!tag_state.empty() && tag_close ) {
2975 PAR_TAG k = tag_state.top();
2977 os << "</" << tag_name(k) << ">";
2984 for(list< PAR_TAG >::const_iterator j = temp.begin();
2985 j != temp.end(); ++j) {
2987 os << "<" << tag_name(*j) << ">";
2990 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2991 j != tag_open.end(); ++j) {
2993 os << "<" << tag_name(*j) << ">";
2996 char c = par->getChar(i);
2998 if (c == Paragraph::META_INSET) {
2999 Inset * inset = par->getInset(i);
3000 inset->linuxdoc(this, os);
3005 if (style.latexparam() == "CDATA") {
3006 // "TeX"-Mode on == > SGML-Mode on.
3012 if (par->sgmlConvertChar(c, sgml_string)
3013 && !style.free_spacing && !par->isFreeSpacing())
3015 // in freespacing mode, spaces are
3016 // non-breaking characters
3017 if (desc_on) {// if char is ' ' then...
3020 sgmlLineBreak(os, char_line_count, 6);
3024 sgmlLineBreak(os, char_line_count, 1);
3029 char_line_count += sgml_string.length();
3035 while (!tag_state.empty()) {
3036 os << "</" << tag_name(tag_state.top()) << ">";
3040 // resets description flag correctly
3042 // <tag> not closed...
3043 sgmlLineBreak(os, char_line_count, 6);
3049 // Print an error message.
3050 void Buffer::sgmlError(Paragraph * par, int pos,
3051 string const & message) const
3053 // insert an error marker in text
3054 InsetError * new_inset = new InsetError(message);
3055 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3060 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3062 ofstream ofs(fname.c_str());
3064 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3068 Paragraph * par = paragraph;
3070 niceFile = nice; // this will be used by Insetincludes.
3072 LyXTextClass const & tclass =
3073 textclasslist.TextClass(params.textclass);
3075 LaTeXFeatures features(params, tclass.numLayouts());
3080 string top_element = textclasslist.LatexnameOfClass(params.textclass);
3083 ofs << "<!DOCTYPE " << top_element
3084 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3086 string preamble = params.preamble;
3087 preamble += features.getIncludedFiles(fname);
3088 preamble += features.getLyXSGMLEntities();
3090 if (!preamble.empty()) {
3091 ofs << "\n [ " << preamble << " ]";
3096 string top = top_element;
3098 top += params.language->code();
3101 if (!params.options.empty()) {
3103 top += params.options;
3105 sgmlOpenTag(ofs, 0, top);
3107 ofs << "<!-- DocBook file was created by " << lyx_docversion
3108 << "\n See http://www.lyx.org/ for more information -->\n";
3110 vector<string> environment_stack(10);
3111 vector<string> environment_inner(10);
3112 vector<string> command_stack(10);
3114 bool command_flag = false;
3115 Paragraph::depth_type command_depth = 0;
3116 Paragraph::depth_type command_base = 0;
3117 Paragraph::depth_type cmd_depth = 0;
3118 Paragraph::depth_type depth = 0; // paragraph depth
3121 string command_name;
3127 int desc_on = 0; // description mode
3129 LyXLayout const & style =
3130 textclasslist.Style(params.textclass,
3133 // environment tag closing
3134 for (; depth > par->params().depth(); --depth) {
3135 if (environment_inner[depth] != "!-- --") {
3136 item_name = "listitem";
3137 sgmlCloseTag(ofs, command_depth + depth,
3139 if (environment_inner[depth] == "varlistentry")
3140 sgmlCloseTag(ofs, depth+command_depth,
3141 environment_inner[depth]);
3143 sgmlCloseTag(ofs, depth + command_depth,
3144 environment_stack[depth]);
3145 environment_stack[depth].erase();
3146 environment_inner[depth].erase();
3149 if (depth == par->params().depth()
3150 && environment_stack[depth] != style.latexname()
3151 && !environment_stack[depth].empty()) {
3152 if (environment_inner[depth] != "!-- --") {
3153 item_name= "listitem";
3154 sgmlCloseTag(ofs, command_depth+depth,
3156 if (environment_inner[depth] == "varlistentry")
3158 depth + command_depth,
3159 environment_inner[depth]);
3162 sgmlCloseTag(ofs, depth + command_depth,
3163 environment_stack[depth]);
3165 environment_stack[depth].erase();
3166 environment_inner[depth].erase();
3169 // Write opening SGML tags.
3170 switch (style.latextype) {
3171 case LATEX_PARAGRAPH:
3172 sgmlOpenTag(ofs, depth + command_depth,
3179 _("Error : Wrong depth for "
3180 "LatexType Command.\n"));
3182 command_name = style.latexname();
3184 sgmlparam = style.latexparam();
3185 c_params = split(sgmlparam, c_depth,'|');
3187 cmd_depth = lyx::atoi(c_depth);
3190 if (cmd_depth < command_base) {
3191 for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3192 sgmlCloseTag(ofs, j, command_stack[j]);
3193 command_depth = command_base = cmd_depth;
3194 } else if (cmd_depth <= command_depth) {
3195 for (int j = command_depth; j >= int(cmd_depth); --j)
3196 sgmlCloseTag(ofs, j, command_stack[j]);
3197 command_depth = cmd_depth;
3199 command_depth = cmd_depth;
3201 command_depth = command_base = cmd_depth;
3202 command_flag = true;
3204 if (command_stack.size() == command_depth + 1)
3205 command_stack.push_back(string());
3206 command_stack[command_depth] = command_name;
3208 // treat label as a special case for
3209 // more WYSIWYM handling.
3210 // This is a hack while paragraphs can't have
3211 // attributes, like id in this case.
3212 if (par->isInset(0)) {
3213 Inset * inset = par->getInset(0);
3214 Inset::Code lyx_code = inset->lyxCode();
3215 if (lyx_code == Inset::LABEL_CODE){
3216 command_name += " id=\"";
3217 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3218 command_name += "\"";
3223 sgmlOpenTag(ofs, depth + command_depth, command_name);
3224 if (c_params.empty())
3225 item_name = "title";
3227 item_name = c_params;
3228 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3231 case LATEX_ENVIRONMENT:
3232 case LATEX_ITEM_ENVIRONMENT:
3233 if (depth < par->params().depth()) {
3234 depth = par->params().depth();
3235 environment_stack[depth].erase();
3238 if (environment_stack[depth] != style.latexname()) {
3239 if(environment_stack.size() == depth + 1) {
3240 environment_stack.push_back("!-- --");
3241 environment_inner.push_back("!-- --");
3243 environment_stack[depth] = style.latexname();
3244 environment_inner[depth] = "!-- --";
3245 sgmlOpenTag(ofs, depth + command_depth,
3246 environment_stack[depth]);
3248 if (environment_inner[depth] != "!-- --") {
3249 item_name= "listitem";
3251 command_depth + depth,
3253 if (environment_inner[depth] == "varlistentry")
3255 depth + command_depth,
3256 environment_inner[depth]);
3260 if (style.latextype == LATEX_ENVIRONMENT) {
3261 if (!style.latexparam().empty()) {
3262 if(style.latexparam() == "CDATA")
3265 sgmlOpenTag(ofs, depth + command_depth,
3266 style.latexparam());
3271 desc_on = (style.labeltype == LABEL_MANUAL);
3274 environment_inner[depth]= "varlistentry";
3276 environment_inner[depth]= "listitem";
3278 sgmlOpenTag(ofs, depth + 1 + command_depth,
3279 environment_inner[depth]);
3283 sgmlOpenTag(ofs, depth + 1 + command_depth,
3287 sgmlOpenTag(ofs, depth + 1 + command_depth,
3292 sgmlOpenTag(ofs, depth + command_depth,
3297 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3301 // write closing SGML tags
3302 switch (style.latextype) {
3304 if (c_params.empty())
3308 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3310 case LATEX_ENVIRONMENT:
3311 if (!style.latexparam().empty()) {
3312 if(style.latexparam() == "CDATA")
3315 sgmlCloseTag(ofs, depth + command_depth,
3316 style.latexparam());
3319 case LATEX_ITEM_ENVIRONMENT:
3320 if (desc_on == 1) break;
3322 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3324 case LATEX_PARAGRAPH:
3325 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3328 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3334 for (int d = depth; d >= 0; --d) {
3335 if (!environment_stack[depth].empty()) {
3336 if (environment_inner[depth] != "!-- --") {
3337 item_name = "listitem";
3338 sgmlCloseTag(ofs, command_depth + depth,
3340 if (environment_inner[depth] == "varlistentry")
3341 sgmlCloseTag(ofs, depth + command_depth,
3342 environment_inner[depth]);
3345 sgmlCloseTag(ofs, depth + command_depth,
3346 environment_stack[depth]);
3350 for (int j = command_depth; j >= 0 ; --j)
3351 if (!command_stack[j].empty())
3352 sgmlCloseTag(ofs, j, command_stack[j]);
3355 sgmlCloseTag(ofs, 0, top_element);
3358 // How to check for successful close
3362 void Buffer::simpleDocBookOnePar(ostream & os,
3363 Paragraph * par, int & desc_on,
3364 Paragraph::depth_type depth) const
3366 bool emph_flag = false;
3368 LyXLayout const & style = textclasslist.Style(params.textclass,
3371 LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3373 int char_line_count = depth;
3374 //if (!style.free_spacing)
3375 // os << string(depth,' ');
3377 // parsing main loop
3378 for (pos_type i = 0; i < par->size(); ++i) {
3379 LyXFont font = par->getFont(params, i);
3381 // handle <emphasis> tag
3382 if (font_old.emph() != font.emph()) {
3383 if (font.emph() == LyXFont::ON) {
3387 os << "</emphasis>";
3393 if ( par->isInset(i) ) {
3394 Inset * inset = par->getInset(i);
3395 // don't print the inset in position 0 if desc_on == 3 (label)
3396 if ( i || desc_on != 3)
3397 inset->docbook(this, os);
3399 char c = par->getChar(i);
3401 par->sgmlConvertChar(c, sgml_string);
3403 if (style.pass_thru) {
3405 } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
3407 } else if (desc_on ==1) {
3409 os << "\n</term><listitem><para>";
3419 os << "</emphasis>";
3422 // resets description flag correctly
3424 // <term> not closed...
3427 if(style.free_spacing) os << '\n';
3431 // This should be enabled when the Chktex class is implemented. (Asger)
3432 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3433 // Other flags: -wall -v0 -x
3434 int Buffer::runChktex()
3436 if (!users->text) return 0;
3438 users->owner()->prohibitInput();
3440 // get LaTeX-Filename
3441 string const name = getLatexName();
3442 string path = OnlyPath(filename);
3444 string const org_path = path;
3445 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3449 Path p(path); // path to LaTeX file
3450 users->owner()->message(_("Running chktex..."));
3452 // Remove all error insets
3453 bool const removedErrorInsets = users->removeAutoInsets();
3455 // Generate the LaTeX file if neccessary
3456 makeLaTeXFile(name, org_path, false);
3459 Chktex chktex(lyxrc.chktex_command, name, filepath);
3460 int res = chktex.run(terr); // run chktex
3463 Alert::alert(_("chktex did not work!"),
3464 _("Could not run with file:"), name);
3465 } else if (res > 0) {
3466 // Insert all errors as errors boxes
3467 users->insertErrors(terr);
3470 // if we removed error insets before we ran chktex or if we inserted
3471 // error insets after we ran chktex, this must be run:
3472 if (removedErrorInsets || res){
3476 users->owner()->allowInput();
3482 void Buffer::validate(LaTeXFeatures & features) const
3484 Paragraph * par = paragraph;
3485 LyXTextClass const & tclass =
3486 textclasslist.TextClass(params.textclass);
3488 // AMS Style is at document level
3489 if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3490 features.require("amsmath");
3493 // We don't use "lyxerr.debug" because of speed. (Asger)
3494 if (lyxerr.debugging(Debug::LATEX))
3495 lyxerr << "Paragraph: " << par << endl;
3497 // Now just follow the list of paragraphs and run
3498 // validate on each of them.
3499 par->validate(features);
3501 // and then the next paragraph
3505 // the bullet shapes are buffer level not paragraph level
3506 // so they are tested here
3507 for (int i = 0; i < 4; ++i) {
3508 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3509 int const font = params.user_defined_bullets[i].getFont();
3511 int const c = params
3512 .user_defined_bullets[i]
3519 features.require("latexsym");
3521 } else if (font == 1) {
3522 features.require("amssymb");
3523 } else if ((font >= 2 && font <= 5)) {
3524 features.require("pifont");
3529 if (lyxerr.debugging(Debug::LATEX)) {
3530 features.showStruct();
3535 // This function should be in Buffer because it's a buffer's property (ale)
3536 string const Buffer::getIncludeonlyList(char delim)
3539 for (inset_iterator it = inset_iterator_begin();
3540 it != inset_iterator_end(); ++it) {
3541 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3542 InsetInclude * insetinc =
3543 static_cast<InsetInclude *>(*it);
3544 if (insetinc->isIncludeOnly()) {
3547 lst += insetinc->getRelFileBaseName();
3551 lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3556 vector<string> const Buffer::getLabelList()
3558 /// if this is a child document and the parent is already loaded
3559 /// Use the parent's list instead [ale990407]
3560 if (!params.parentname.empty()
3561 && bufferlist.exists(params.parentname)) {
3562 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3564 return tmp->getLabelList();
3567 vector<string> label_list;
3568 for (inset_iterator it = inset_iterator_begin();
3569 it != inset_iterator_end(); ++it) {
3570 vector<string> const l = (*it)->getLabelList();
3571 label_list.insert(label_list.end(), l.begin(), l.end());
3577 Buffer::Lists const Buffer::getLists() const
3580 Paragraph * par = paragraph;
3583 std::pair<bool, textclass_type> const tmp =
3584 textclasslist.NumberOfLayout(params.textclass, "Caption");
3585 bool const found = tmp.first;
3586 textclass_type const cap = tmp.second;
3589 // This is the prefered way to to this, but boost::tie can break
3593 boost::tie(found, cap) = textclasslist
3594 .NumberOfLayout(params.textclass, "Caption");
3598 char const labeltype =
3599 textclasslist.Style(params.textclass,
3600 par->getLayout()).labeltype;
3602 if (labeltype >= LABEL_COUNTER_CHAPTER
3603 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3604 // insert this into the table of contents
3605 SingleList & item = l["TOC"];
3608 textclasslist.TextClass(params.textclass).maxcounter());
3609 item.push_back(TocItem(par, depth, par->asString(this, true)));
3611 // For each paragrph, traverse its insets and look for
3615 Paragraph::inset_iterator it =
3616 par->inset_iterator_begin();
3617 Paragraph::inset_iterator end =
3618 par->inset_iterator_end();
3620 for (; it != end; ++it) {
3621 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3623 static_cast<InsetFloat*>(*it);
3625 string const type = il->type();
3627 // Now find the caption in the float...
3628 // We now tranverse the paragraphs of
3630 Paragraph * tmp = il->inset.paragraph();
3632 if (tmp->layout == cap) {
3633 SingleList & item = l[type];
3635 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3636 item.push_back(TocItem(tmp, 0 , str));
3643 lyxerr << "caption not found" << endl;
3652 // This is also a buffer property (ale)
3653 vector<pair<string, string> > const Buffer::getBibkeyList()
3655 /// if this is a child document and the parent is already loaded
3656 /// Use the parent's list instead [ale990412]
3657 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3658 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3660 return tmp->getBibkeyList();
3663 vector<pair<string, string> > keys;
3664 Paragraph * par = paragraph;
3667 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3668 par->asString(this, false)));
3672 // Might be either using bibtex or a child has bibliography
3674 for (inset_iterator it = inset_iterator_begin();
3675 it != inset_iterator_end(); ++it) {
3676 // Search for Bibtex or Include inset
3677 if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3678 vector<pair<string,string> > tmp =
3679 static_cast<InsetBibtex*>(*it)->getKeys(this);
3680 keys.insert(keys.end(), tmp.begin(), tmp.end());
3681 } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3682 vector<pair<string,string> > const tmp =
3683 static_cast<InsetInclude*>(*it)->getKeys();
3684 keys.insert(keys.end(), tmp.begin(), tmp.end());
3693 bool Buffer::isDepClean(string const & name) const
3695 DEPCLEAN * item = dep_clean;
3696 while (item && item->master != name)
3698 if (!item) return true;
3703 void Buffer::markDepClean(string const & name)
3706 dep_clean = new DEPCLEAN;
3707 dep_clean->clean = true;
3708 dep_clean->master = name;
3709 dep_clean->next = 0;
3711 DEPCLEAN * item = dep_clean;
3712 while (item && item->master != name)
3717 item = new DEPCLEAN;
3719 item->master = name;
3726 bool Buffer::dispatch(string const & command)
3728 // Split command string into command and argument
3730 string line = frontStrip(command);
3731 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3733 return dispatch(lyxaction.LookupFunc(cmd), arg);
3737 bool Buffer::dispatch(int action, string const & argument)
3739 bool dispatched = true;
3742 Exporter::Export(this, argument, false);
3752 void Buffer::resizeInsets(BufferView * bv)
3754 /// then remove all LyXText in text-insets
3755 Paragraph * par = paragraph;
3756 for (; par; par = par->next()) {
3757 par->resizeInsetsLyXText(bv);
3762 void Buffer::redraw()
3769 void Buffer::changeLanguage(Language const * from, Language const * to)
3772 ParIterator end = par_iterator_end();
3773 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3774 (*it)->changeLanguage(params, from, to);
3778 bool Buffer::isMultiLingual()
3780 ParIterator end = par_iterator_end();
3781 for (ParIterator it = par_iterator_begin(); it != end; ++it)
3782 if ((*it)->isMultiLingual(params))
3789 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3792 it = par->InsetIterator(pos);
3793 if (it == par->inset_iterator_end()) {
3800 void Buffer::inset_iterator::setParagraph()
3803 it = par->inset_iterator_begin();
3804 if (it != par->inset_iterator_end())
3809 // We maintain an invariant that whenever par = 0 then it = 0
3813 Inset * Buffer::getInsetFromID(int id_arg) const
3815 for (inset_iterator it = inset_const_iterator_begin();
3816 it != inset_const_iterator_end(); ++it)
3818 if ((*it)->id() == id_arg)
3820 Inset * in = (*it)->getInsetFromID(id_arg);
3828 Paragraph * Buffer::getParFromID(int id) const
3830 if (id < 0) return 0;
3831 Paragraph * par = paragraph;
3833 if (par->id() == id) {
3836 Paragraph * tmp = par->getParFromID(id);
3846 ParIterator Buffer::par_iterator_begin()
3848 return ParIterator(paragraph);
3852 ParIterator Buffer::par_iterator_end()
3854 return ParIterator();