1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-2000 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
23 #include <sys/types.h>
33 #pragma implementation "buffer.h"
37 #include "bufferlist.h"
39 #include "lyx_gui_misc.h"
40 #include "LyXAction.h"
43 #include "tex-strings.h"
45 #include "bufferview_funcs.h"
46 #include "minibuffer.h"
49 #include "mathed/formulamacro.h"
50 #include "insets/lyxinset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insetlabel.h"
53 #include "insets/insetref.h"
54 #include "insets/inseturl.h"
55 #include "insets/insetinfo.h"
56 #include "insets/insetquotes.h"
57 #include "insets/insetlatexaccent.h"
58 #include "insets/insetbib.h"
59 #include "insets/insetcite.h"
60 #include "insets/insetexternal.h"
61 #include "insets/insetindex.h"
62 #include "insets/insetinclude.h"
63 #include "insets/insettoc.h"
64 #include "insets/insetparent.h"
65 #include "insets/insetspecialchar.h"
66 #include "insets/figinset.h"
67 #include "insets/insettext.h"
68 #include "insets/insetert.h"
69 #include "insets/insetgraphics.h"
70 #include "insets/insetfoot.h"
71 #include "insets/insetmarginal.h"
72 #include "insets/insetminipage.h"
73 #include "insets/insetfloat.h"
74 #include "insets/insetlist.h"
75 #include "insets/insettabular.h"
76 #include "insets/insettheorem.h"
77 #include "insets/insetcaption.h"
78 #include "support/filetools.h"
79 #include "support/path.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "support/lyxmanip.h"
92 #include "lyx_gui_misc.h" // WarnReadonly()
93 #include "frontends/Dialogs.h"
97 #include "converter.h"
111 // all these externs should eventually be removed.
112 extern BufferList bufferlist;
114 extern LyXAction lyxaction;
118 static const float LYX_FORMAT = 2.17;
120 static const int LYX_FORMAT = 218;
123 extern int tex_code_break_column;
126 Buffer::Buffer(string const & file, bool ronly)
128 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
130 filepath = OnlyPath(file);
139 if (read_only || (lyxrc.use_tempdir)) {
140 tmppath = CreateBufferTmpDir();
141 } else tmppath.erase();
147 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
148 // here the buffer should take care that it is
149 // saved properly, before it goes into the void.
151 // make sure that views using this buffer
156 if (!tmppath.empty()) {
157 DestroyBufferTmpDir(tmppath);
160 LyXParagraph * par = paragraph;
161 LyXParagraph * tmppar;
171 string const Buffer::getLatexName(bool no_path) const
174 return OnlyFilename(ChangeExtension(MakeLatexName(filename),
177 return ChangeExtension(MakeLatexName(filename),
181 string const Buffer::getLatexLogName(void) const
183 string filename, fname, bname, path;
185 filename = getLatexName(false);
187 if (filename.empty())
190 fname = OnlyFilename(ChangeExtension(filename, ".log"));
191 bname = OnlyFilename(ChangeExtension(filename,
192 formats.Extension("literate") + ".out"));
193 path = OnlyPath(filename);
195 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
196 path = tmppath + "/";
198 lyxerr[Debug::FILES] << "LaTeX Log calculated as : " << path + fname << endl;
200 // If no Latex log or Build log is newer, show Build log
201 FileInfo f_fi(path + fname), b_fi(path + bname);
203 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime()))
209 void Buffer::setReadonly(bool flag)
211 if (read_only != flag) {
214 users->owner()->getDialogs()->updateBufferDependent(false);
217 WarnReadonly(filename);
222 bool Buffer::saveParamsAsDefaults() // const
224 string const fname = AddName(AddPath(user_lyxdir, "templates/"),
226 Buffer defaults = Buffer(fname);
228 // Use the current buffer's parameters as default
229 defaults.params = params;
231 // add an empty paragraph. Is this enough?
232 defaults.paragraph = new LyXParagraph;
234 return defaults.writeFile(defaults.filename, false);
238 /// Update window titles of all users
239 // Should work on a list
240 void Buffer::updateTitles() const
242 if (users) users->owner()->updateWindowTitle();
246 /// Reset autosave timer of all users
247 // Should work on a list
248 void Buffer::resetAutosaveTimers() const
250 if (users) users->owner()->resetAutosaveTimer();
254 void Buffer::setFileName(string const & newfile)
256 filename = MakeAbsPath(newfile);
257 filepath = OnlyPath(filename);
258 setReadonly(IsFileWriteable(filename) == 0);
263 // candidate for move to BufferView
264 // (at least some parts in the beginning of the func)
267 // changed to be public and have one parameter
268 // if par = 0 normal behavior
269 // else insert behavior
270 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
271 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
274 char depth = 0; // signed or unsigned?
276 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
277 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
279 bool the_end_read = false;
281 LyXParagraph * return_par = 0;
282 LyXFont font(LyXFont::ALL_INHERIT, params.language);
284 if (format < 2.16 && params.language->lang() == "hebrew")
285 font.setLanguage(default_language);
287 if (file_format < 216 && params.language->lang() == "hebrew")
288 font.setLanguage(default_language);
290 // If we are inserting, we cheat and get a token in advance
291 bool has_token = false;
295 par = new LyXParagraph;
297 users->text->BreakParagraph(users);
298 return_par = users->text->FirstParagraph();
301 // We don't want to adopt the parameters from the
302 // document we insert, so we skip until the text begins:
305 pretoken = lex.GetString();
306 if (pretoken == "\\layout") {
318 pretoken = lex.GetString();
321 if (pretoken.empty()) continue;
324 parseSingleLyXformat2Token(lex, par, return_par,
325 pretoken, pos, depth,
337 paragraph = return_par;
343 // We'll remove this later. (Lgb)
344 static string last_inset_read;
348 Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
349 LyXParagraph *& return_par,
350 string const & token, int & pos,
351 char & depth, LyXFont & font
353 , LyXParagraph::footnote_flag & footnoteflag,
354 LyXParagraph::footnote_kind & footnotekind
358 bool the_end_read = false;
360 if (token[0] != '\\') {
361 for (string::const_iterator cit = token.begin();
362 cit != token.end(); ++cit) {
363 par->InsertChar(pos, (*cit), font);
366 } else if (token == "\\i") {
367 Inset * inset = new InsetLatexAccent;
368 inset->Read(this, lex);
369 par->InsertInset(pos, inset, font);
371 } else if (token == "\\layout") {
376 par = new LyXParagraph(par);
380 string const layoutname = lex.GetString();
381 pair<bool, LyXTextClass::LayoutList::size_type> pp
382 = textclasslist.NumberOfLayout(params.textclass,
385 par->layout = pp.second;
386 } else { // layout not found
387 // use default layout "Standard" (0)
390 // Test whether the layout is obsolete.
391 LyXLayout const & layout =
392 textclasslist.Style(params.textclass,
394 if (!layout.obsoleted_by().empty())
396 textclasslist.NumberOfLayout(params.textclass,
397 layout.obsoleted_by()).second;
399 par->footnoteflag = footnoteflag;
400 par->footnotekind = footnotekind;
403 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
405 if (format < 2.16 && params.language->lang() == "hebrew")
406 font.setLanguage(default_language);
408 if (file_format < 216 && params.language->lang() == "hebrew")
409 font.setLanguage(default_language);
412 } else if (token == "\\end_float") {
417 par = new LyXParagraph(par);
419 footnotekind = LyXParagraph::FOOTNOTE;
420 footnoteflag = LyXParagraph::NO_FOOTNOTE;
423 par->layout = LYX_DUMMY_LAYOUT;
424 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
426 if (format < 2.16 && params.language->lang() == "hebrew")
427 font.setLanguage(default_language);
429 if (file_format < 216 && params.language->lang() == "hebrew")
430 font.setLanguage(default_language);
432 } else if (token == "\\begin_float") {
433 int tmpret = lex.FindToken(string_footnotekinds);
434 if (tmpret == -1) ++tmpret;
435 if (tmpret != LYX_LAYOUT_DEFAULT)
436 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
437 if (footnotekind == LyXParagraph::FOOTNOTE
438 || footnotekind == LyXParagraph::MARGIN)
439 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
441 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
443 } else if (token == "\\begin_float") {
444 // This is the compability reader, unfinished but tested.
447 string const tmptok = lex.GetString();
448 //lyxerr << "old float: " << tmptok << endl;
453 if (tmptok == "footnote") {
454 inset = new InsetFoot;
455 } else if (tmptok == "margin") {
456 inset = new InsetMarginal;
457 } else if (tmptok == "fig") {
458 inset = new InsetFloat("figure");
459 old_float += "placement htbp\n";
460 } else if (tmptok == "tab") {
461 inset = new InsetFloat("table");
462 old_float += "placement htbp\n";
463 } else if (tmptok == "alg") {
464 inset = new InsetFloat("algorithm");
465 old_float += "placement htbp\n";
466 } else if (tmptok == "wide-fig") {
467 InsetFloat * tmp = new InsetFloat("figure");
470 old_float += "placement htbp\n";
471 } else if (tmptok == "wide-tab") {
472 InsetFloat * tmp = new InsetFloat("table");
475 old_float += "placement htbp\n";
478 if (!inset) return false; // no end read yet
480 old_float += "collapsed true\n";
482 // Here we need to check for \end_deeper and handle that
483 // before we do the footnote parsing.
484 // This _is_ a hack! (Lgb)
487 string const tmp = lex.GetString();
488 if (tmp == "\\end_deeper") {
489 lyxerr << "\\end_deeper caught!" << endl;
491 lex.printError("\\end_deeper: "
492 "depth is already null");
503 old_float += lex.getLongString("\\end_float");
504 old_float += "\n\\end_inset\n";
505 //lyxerr << "float body: " << old_float << endl;
507 istringstream istr(old_float);
510 nylex.setStream(istr);
512 inset->Read(this, nylex);
513 par->InsertInset(pos, inset, font);
516 } else if (token == "\\begin_deeper") {
518 } else if (token == "\\end_deeper") {
520 lex.printError("\\end_deeper: "
521 "depth is already null");
525 } else if (token == "\\begin_preamble") {
526 params.readPreamble(lex);
527 } else if (token == "\\textclass") {
529 pair<bool, LyXTextClassList::size_type> pp =
530 textclasslist.NumberOfClass(lex.GetString());
532 params.textclass = pp.second;
534 WriteAlert(string(_("Textclass error")),
535 string(_("The document uses an unknown textclass \"")) +
536 lex.GetString() + string("\"."),
537 string(_("LyX will not be able to produce output correctly.")));
538 params.textclass = 0;
540 if (!textclasslist.Load(params.textclass)) {
541 // if the textclass wasn't loaded properly
542 // we need to either substitute another
543 // or stop loading the file.
544 // I can substitute but I don't see how I can
545 // stop loading... ideas?? ARRae980418
546 WriteAlert(_("Textclass Loading Error!"),
547 string(_("Can't load textclass ")) +
548 textclasslist.NameOfClass(params.textclass),
549 _("-- substituting default"));
550 params.textclass = 0;
552 } else if (token == "\\options") {
554 params.options = lex.GetString();
555 } else if (token == "\\language") {
556 params.readLanguage(lex);
557 } else if (token == "\\fontencoding") {
559 } else if (token == "\\inputencoding") {
561 params.inputenc = lex.GetString();
562 } else if (token == "\\graphics") {
563 params.readGraphicsDriver(lex);
564 } else if (token == "\\fontscheme") {
566 params.fonts = lex.GetString();
567 } else if (token == "\\noindent") {
568 par->noindent = true;
569 } else if (token == "\\fill_top") {
570 par->added_space_top = VSpace(VSpace::VFILL);
571 } else if (token == "\\fill_bottom") {
572 par->added_space_bottom = VSpace(VSpace::VFILL);
573 } else if (token == "\\line_top") {
574 par->line_top = true;
575 } else if (token == "\\line_bottom") {
576 par->line_bottom = true;
577 } else if (token == "\\pagebreak_top") {
578 par->pagebreak_top = true;
579 } else if (token == "\\pagebreak_bottom") {
580 par->pagebreak_bottom = true;
581 } else if (token == "\\start_of_appendix") {
582 par->start_of_appendix = true;
583 } else if (token == "\\paragraph_separation") {
584 int tmpret = lex.FindToken(string_paragraph_separation);
585 if (tmpret == -1) ++tmpret;
586 if (tmpret != LYX_LAYOUT_DEFAULT)
587 params.paragraph_separation =
588 static_cast<BufferParams::PARSEP>(tmpret);
589 } else if (token == "\\defskip") {
591 params.defskip = VSpace(lex.GetString());
592 } else if (token == "\\epsfig") { // obsolete
593 // Indeed it is obsolete, but we HAVE to be backwards
594 // compatible until 0.14, because otherwise all figures
595 // in existing documents are irretrivably lost. (Asger)
596 params.readGraphicsDriver(lex);
597 } else if (token == "\\quotes_language") {
598 int tmpret = lex.FindToken(string_quotes_language);
599 if (tmpret == -1) ++tmpret;
600 if (tmpret != LYX_LAYOUT_DEFAULT) {
601 InsetQuotes::quote_language tmpl =
602 InsetQuotes::EnglishQ;
605 tmpl = InsetQuotes::EnglishQ;
608 tmpl = InsetQuotes::SwedishQ;
611 tmpl = InsetQuotes::GermanQ;
614 tmpl = InsetQuotes::PolishQ;
617 tmpl = InsetQuotes::FrenchQ;
620 tmpl = InsetQuotes::DanishQ;
623 params.quotes_language = tmpl;
625 } else if (token == "\\quotes_times") {
627 switch (lex.GetInteger()) {
629 params.quotes_times = InsetQuotes::SingleQ;
632 params.quotes_times = InsetQuotes::DoubleQ;
635 } else if (token == "\\papersize") {
636 int tmpret = lex.FindToken(string_papersize);
640 params.papersize2 = tmpret;
641 } else if (token == "\\paperpackage") {
642 int tmpret = lex.FindToken(string_paperpackages);
645 params.paperpackage = BufferParams::PACKAGE_NONE;
647 params.paperpackage = tmpret;
648 } else if (token == "\\use_geometry") {
650 params.use_geometry = lex.GetInteger();
651 } else if (token == "\\use_amsmath") {
653 params.use_amsmath = lex.GetInteger();
654 } else if (token == "\\paperorientation") {
655 int tmpret = lex.FindToken(string_orientation);
656 if (tmpret == -1) ++tmpret;
657 if (tmpret != LYX_LAYOUT_DEFAULT)
658 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
659 } else if (token == "\\paperwidth") {
661 params.paperwidth = lex.GetString();
662 } else if (token == "\\paperheight") {
664 params.paperheight = lex.GetString();
665 } else if (token == "\\leftmargin") {
667 params.leftmargin = lex.GetString();
668 } else if (token == "\\topmargin") {
670 params.topmargin = lex.GetString();
671 } else if (token == "\\rightmargin") {
673 params.rightmargin = lex.GetString();
674 } else if (token == "\\bottommargin") {
676 params.bottommargin = lex.GetString();
677 } else if (token == "\\headheight") {
679 params.headheight = lex.GetString();
680 } else if (token == "\\headsep") {
682 params.headsep = lex.GetString();
683 } else if (token == "\\footskip") {
685 params.footskip = lex.GetString();
686 } else if (token == "\\paperfontsize") {
688 params.fontsize = strip(lex.GetString());
689 } else if (token == "\\papercolumns") {
691 params.columns = lex.GetInteger();
692 } else if (token == "\\papersides") {
694 switch (lex.GetInteger()) {
696 case 1: params.sides = LyXTextClass::OneSide; break;
697 case 2: params.sides = LyXTextClass::TwoSides; break;
699 } else if (token == "\\paperpagestyle") {
701 params.pagestyle = strip(lex.GetString());
702 } else if (token == "\\bullet") {
704 int const index = lex.GetInteger();
706 int temp_int = lex.GetInteger();
707 params.user_defined_bullets[index].setFont(temp_int);
708 params.temp_bullets[index].setFont(temp_int);
710 temp_int = lex.GetInteger();
711 params.user_defined_bullets[index].setCharacter(temp_int);
712 params.temp_bullets[index].setCharacter(temp_int);
714 temp_int = lex.GetInteger();
715 params.user_defined_bullets[index].setSize(temp_int);
716 params.temp_bullets[index].setSize(temp_int);
718 string const temp_str = lex.GetString();
719 if (temp_str != "\\end_bullet") {
720 // this element isn't really necessary for
721 // parsing but is easier for humans
722 // to understand bullets. Put it back and
723 // set a debug message?
724 lex.printError("\\end_bullet expected, got" + temp_str);
725 //how can I put it back?
727 } else if (token == "\\bulletLaTeX") {
729 int const index = lex.GetInteger();
731 string temp_str = lex.GetString();
733 while (temp_str != "\\end_bullet") {
734 // this loop structure is needed when user
735 // enters an empty string since the first
736 // thing returned will be the \\end_bullet
738 // if the LaTeX entry has spaces. Each element
739 // therefore needs to be read in turn
742 temp_str = lex.GetString();
744 params.user_defined_bullets[index].setText(sum_str);
745 params.temp_bullets[index].setText(sum_str);
746 } else if (token == "\\secnumdepth") {
748 params.secnumdepth = lex.GetInteger();
749 } else if (token == "\\tocdepth") {
751 params.tocdepth = lex.GetInteger();
752 } else if (token == "\\spacing") {
754 string const tmp = strip(lex.GetString());
755 Spacing::Space tmp_space = Spacing::Default;
757 if (tmp == "single") {
758 tmp_space = Spacing::Single;
759 } else if (tmp == "onehalf") {
760 tmp_space = Spacing::Onehalf;
761 } else if (tmp == "double") {
762 tmp_space = Spacing::Double;
763 } else if (tmp == "other") {
765 tmp_space = Spacing::Other;
766 tmp_val = lex.GetFloat();
768 lex.printError("Unknown spacing token: '$$Token'");
770 // Small hack so that files written with klyx will be
773 par->spacing.set(tmp_space, tmp_val);
775 params.spacing.set(tmp_space, tmp_val);
777 } else if (token == "\\paragraph_spacing") {
779 string const tmp = strip(lex.GetString());
780 if (tmp == "single") {
781 par->spacing.set(Spacing::Single);
782 } else if (tmp == "onehalf") {
783 par->spacing.set(Spacing::Onehalf);
784 } else if (tmp == "double") {
785 par->spacing.set(Spacing::Double);
786 } else if (tmp == "other") {
788 par->spacing.set(Spacing::Other,
791 lex.printError("Unknown spacing token: '$$Token'");
793 } else if (token == "\\float_placement") {
795 params.float_placement = lex.GetString();
796 } else if (token == "\\family") {
798 font.setLyXFamily(lex.GetString());
799 } else if (token == "\\series") {
801 font.setLyXSeries(lex.GetString());
802 } else if (token == "\\shape") {
804 font.setLyXShape(lex.GetString());
805 } else if (token == "\\size") {
807 font.setLyXSize(lex.GetString());
808 } else if (token == "\\latex") {
810 string const tok = lex.GetString();
811 // This is dirty, but gone with LyX3. (Asger)
812 if (tok == "no_latex")
813 font.setLatex(LyXFont::OFF);
814 else if (tok == "latex")
815 font.setLatex(LyXFont::ON);
816 else if (tok == "default")
817 font.setLatex(LyXFont::INHERIT);
819 lex.printError("Unknown LaTeX font flag "
821 } else if (token == "\\lang") {
823 string const tok = lex.GetString();
824 Language const * lang = languages.getLanguage(tok);
826 font.setLanguage(lang);
828 font.setLanguage(params.language);
829 lex.printError("Unknown language `$$Token'");
831 } else if (token == "\\numeric") {
833 font.setNumber(font.setLyXMisc(lex.GetString()));
834 } else if (token == "\\emph") {
836 font.setEmph(font.setLyXMisc(lex.GetString()));
837 } else if (token == "\\bar") {
839 string const tok = lex.GetString();
840 // This is dirty, but gone with LyX3. (Asger)
842 font.setUnderbar(LyXFont::ON);
843 else if (tok == "no")
844 font.setUnderbar(LyXFont::OFF);
845 else if (tok == "default")
846 font.setUnderbar(LyXFont::INHERIT);
848 lex.printError("Unknown bar font flag "
850 } else if (token == "\\noun") {
852 font.setNoun(font.setLyXMisc(lex.GetString()));
853 } else if (token == "\\color") {
855 font.setLyXColor(lex.GetString());
856 } else if (token == "\\align") {
857 int tmpret = lex.FindToken(string_align);
858 if (tmpret == -1) ++tmpret;
859 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
862 for (; tmpret > 0; --tmpret)
863 tmpret2 = tmpret2 * 2;
865 int const tmpret2 = int(pow(2.0, tmpret));
867 //lyxerr << "Tmpret2 = " << tmpret2 << endl;
868 par->align = LyXAlignment(tmpret2);
870 } else if (token == "\\added_space_top") {
872 par->added_space_top = VSpace(lex.GetString());
873 } else if (token == "\\added_space_bottom") {
875 par->added_space_bottom = VSpace(lex.GetString());
876 } else if (token == "\\pextra_type") {
878 par->pextra_type = lex.GetInteger();
879 } else if (token == "\\pextra_width") {
881 par->pextra_width = lex.GetString();
882 } else if (token == "\\pextra_widthp") {
884 par->pextra_widthp = lex.GetString();
885 } else if (token == "\\pextra_alignment") {
887 par->pextra_alignment = lex.GetInteger();
888 } else if (token == "\\pextra_hfill") {
890 par->pextra_hfill = lex.GetInteger();
891 } else if (token == "\\pextra_start_minipage") {
893 par->pextra_start_minipage = lex.GetInteger();
894 } else if (token == "\\labelwidthstring") {
896 par->labelwidthstring = lex.GetString();
897 // do not delete this token, it is still needed!
898 } else if (token == "\\end_inset") {
899 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
900 << "Last inset read was: " << last_inset_read
902 // Simply ignore this. The insets do not have
904 // But insets should read it, it is a part of
905 // the inset isn't it? Lgb.
906 } else if (token == "\\begin_inset") {
907 readInset(lex, par, pos, font);
908 } else if (token == "\\SpecialChar") {
909 LyXLayout const & layout =
910 textclasslist.Style(params.textclass,
913 // Insets don't make sense in a free-spacing context! ---Kayvan
914 if (layout.free_spacing) {
917 string next_token = lex.GetString();
918 if (next_token == "\\-") {
919 par->InsertChar(pos, '-', font);
920 } else if (next_token == "\\protected_separator"
921 || next_token == "~") {
922 par->InsertChar(pos, ' ', font);
924 lex.printError("Token `$$Token' "
926 "paragraph layout!");
931 Inset * inset = new InsetSpecialChar;
932 inset->Read(this, lex);
933 par->InsertInset(pos, inset, font);
936 } else if (token == "\\newline") {
937 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
939 } else if (token == "\\LyXTable") {
940 Inset * inset = new InsetTabular(*this);
941 inset->Read(this, lex);
942 par->InsertInset(pos, inset, font);
944 } else if (token == "\\hfill") {
945 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
947 } else if (token == "\\protected_separator") { // obsolete
948 // This is a backward compability thingie. (Lgb)
949 // Remove it later some time...introduced with fileformat
951 LyXLayout const & layout =
952 textclasslist.Style(params.textclass,
955 if (layout.free_spacing) {
956 par->InsertChar(pos, ' ', font);
958 Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
959 par->InsertInset(pos, inset, font);
962 } else if (token == "\\bibitem") { // ale970302
964 InsetCommandParams p("bibitem", "dummy");
965 par->bibkey = new InsetBibKey(p);
967 par->bibkey->Read(this, lex);
968 } else if (token == "\\backslash") {
969 par->InsertChar(pos, '\\', font);
971 } else if (token == "\\the_end") {
974 // This should be insurance for the future: (Asger)
975 lex.printError("Unknown token `$$Token'. "
976 "Inserting as text.");
977 string::const_iterator cit = token.begin();
978 string::const_iterator end = token.end();
979 for (; cit != end; ++cit) {
980 par->InsertChar(pos, (*cit), font);
988 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
989 int & pos, LyXFont & font)
992 if (lex.GetString() != "\\begin_inset") {
993 lyxerr << "Buffer::readInset: Consistency check failed."
1000 string const tmptok = lex.GetString();
1001 last_inset_read = tmptok;
1003 // test the different insets
1004 if (tmptok == "LatexCommand") {
1005 InsetCommandParams inscmd;
1008 if (inscmd.getCmdName() == "cite") {
1009 inset = new InsetCitation(inscmd);
1010 } else if (inscmd.getCmdName() == "bibitem") {
1011 lex.printError("Wrong place for bibitem");
1012 inset = new InsetBibKey(inscmd);
1013 } else if (inscmd.getCmdName() == "BibTeX") {
1014 inset = new InsetBibtex(inscmd);
1015 } else if (inscmd.getCmdName() == "index") {
1016 inset = new InsetIndex(inscmd);
1017 } else if (inscmd.getCmdName() == "include") {
1018 inset = new InsetInclude(inscmd, *this);
1019 } else if (inscmd.getCmdName() == "label") {
1020 inset = new InsetLabel(inscmd);
1021 } else if (inscmd.getCmdName() == "url"
1022 || inscmd.getCmdName() == "htmlurl") {
1023 inset = new InsetUrl(inscmd);
1024 } else if (inscmd.getCmdName() == "ref"
1025 || inscmd.getCmdName() == "pageref"
1026 || inscmd.getCmdName() == "vref"
1027 || inscmd.getCmdName() == "vpageref"
1028 || inscmd.getCmdName() == "prettyref") {
1029 if (!inscmd.getOptions().empty()
1030 || !inscmd.getContents().empty()) {
1031 inset = new InsetRef(inscmd, *this);
1033 } else if (inscmd.getCmdName() == "tableofcontents"
1034 || inscmd.getCmdName() == "listofalgorithms"
1035 || inscmd.getCmdName() == "listoffigures"
1036 || inscmd.getCmdName() == "listoftables") {
1037 inset = new InsetTOC(inscmd);
1038 } else if (inscmd.getCmdName() == "printindex") {
1039 inset = new InsetPrintIndex(inscmd);
1040 } else if (inscmd.getCmdName() == "lyxparent") {
1041 inset = new InsetParent(inscmd, *this);
1044 if (tmptok == "Quotes") {
1045 inset = new InsetQuotes;
1046 } else if (tmptok == "External") {
1047 inset = new InsetExternal;
1048 } else if (tmptok == "FormulaMacro") {
1049 inset = new InsetFormulaMacro;
1050 } else if (tmptok == "Formula") {
1051 inset = new InsetFormula;
1052 } else if (tmptok == "Figure") {
1053 inset = new InsetFig(100, 100, *this);
1054 } else if (tmptok == "Info") {
1055 inset = new InsetInfo;
1056 } else if (tmptok == "Include") {
1057 InsetCommandParams p( "Include" );
1058 inset = new InsetInclude(p, *this);
1059 } else if (tmptok == "ERT") {
1060 inset = new InsetERT;
1061 } else if (tmptok == "Tabular") {
1062 inset = new InsetTabular(*this);
1063 } else if (tmptok == "Text") {
1064 inset = new InsetText;
1065 } else if (tmptok == "Foot") {
1066 inset = new InsetFoot;
1067 } else if (tmptok == "Marginal") {
1068 inset = new InsetMarginal;
1069 } else if (tmptok == "Minipage") {
1070 inset = new InsetMinipage;
1071 } else if (tmptok == "Float") {
1073 string tmptok = lex.GetString();
1074 inset = new InsetFloat(tmptok);
1075 } else if (tmptok == "List") {
1076 inset = new InsetList;
1077 } else if (tmptok == "Theorem") {
1078 inset = new InsetList;
1079 } else if (tmptok == "Caption") {
1080 inset = new InsetCaption;
1081 } else if (tmptok == "GRAPHICS") {
1082 inset = new InsetGraphics;
1085 if (inset) inset->Read(this, lex);
1089 par->InsertInset(pos, inset, font);
1095 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1099 string const token(lex.GetString());
1100 if (token == "\\lyxformat") { // the first token _must_ be...
1103 format = lex.GetFloat();
1105 if (LYX_FORMAT - format > 0.05) {
1106 lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
1107 LYX_FORMAT, format) << endl;
1109 if (format - LYX_FORMAT > 0.05) {
1110 lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
1111 LYX_FORMAT, format) << endl;
1113 bool the_end = readLyXformat2(lex, par);
1114 // Formats >= 2.13 support "\the_end" marker
1121 WriteAlert(_("Warning!"),
1122 _("Reading of document is not complete"),
1123 _("Maybe the document is truncated"));
1124 // We simulate a safe reading anyways to allow
1125 // users to take the chance... (Asger)
1129 WriteAlert(_("ERROR!"),
1130 _("Old LyX file format found. "
1131 "Use LyX 0.10.x to read this!"));
1136 string tmp_format = lex.GetString();
1137 //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1138 // if present remove ".," from string.
1139 string::size_type dot = tmp_format.find_first_of(".,");
1140 //lyxerr << " dot found at " << dot << endl;
1141 if (dot != string::npos)
1142 tmp_format.erase(dot, 1);
1143 file_format = strToInt(tmp_format);
1144 if (file_format == LYX_FORMAT) {
1146 } else if (file_format > LYX_FORMAT) {
1148 WriteAlert(_("Warning!"),
1149 _("LyX file format is newer that what"),
1150 _("is supported in this LyX version. Expect some problems."));
1152 } else if (file_format < LYX_FORMAT) {
1154 if (file_format < 200) {
1155 WriteAlert(_("ERROR!"),
1156 _("Old LyX file format found. "
1157 "Use LyX 0.10.x to read this!"));
1161 bool the_end = readLyXformat2(lex, par);
1163 // the_end was added in 213
1164 if (file_format < 213)
1168 WriteAlert(_("Warning!"),
1169 _("Reading of document is not complete"),
1170 _("Maybe the document is truncated"));
1173 } else { // "\\lyxformat" not found
1174 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1177 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1183 // Should probably be moved to somewhere else: BufferView? LyXView?
1184 bool Buffer::save() const
1186 // We don't need autosaves in the immediate future. (Asger)
1187 resetAutosaveTimers();
1191 if (lyxrc.make_backup) {
1192 s = fileName() + '~';
1193 if (!lyxrc.backupdir_path.empty())
1194 s = AddName(lyxrc.backupdir_path,
1195 subst(CleanupPath(s),'/','!'));
1197 // Rename is the wrong way of making a backup,
1198 // this is the correct way.
1199 /* truss cp fil fil2:
1200 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1201 stat("LyXVC.lyx", 0xEFFFF688) = 0
1202 open("LyXVC.lyx", O_RDONLY) = 3
1203 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1204 fstat(4, 0xEFFFF508) = 0
1205 fstat(3, 0xEFFFF508) = 0
1206 read(3, " # T h i s f i l e w".., 8192) = 5579
1207 write(4, " # T h i s f i l e w".., 5579) = 5579
1208 read(3, 0xEFFFD4A0, 8192) = 0
1211 chmod("LyXVC3.lyx", 0100644) = 0
1212 lseek(0, 0, SEEK_CUR) = 46440
1216 // Should proabaly have some more error checking here.
1217 // Should be cleaned up in 0.13, at least a bit.
1218 // Doing it this way, also makes the inodes stay the same.
1219 // This is still not a very good solution, in particular we
1220 // might loose the owner of the backup.
1221 FileInfo finfo(fileName());
1222 if (finfo.exist()) {
1223 mode_t fmode = finfo.getMode();
1224 struct utimbuf times = {
1225 finfo.getAccessTime(),
1226 finfo.getModificationTime() };
1228 ifstream ifs(fileName().c_str());
1229 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1234 ::chmod(s.c_str(), fmode);
1236 if (::utime(s.c_str(), ×)) {
1237 lyxerr << "utime error." << endl;
1240 lyxerr << "LyX was not able to make "
1241 "backupcopy. Beware." << endl;
1246 if (writeFile(fileName(), false)) {
1248 removeAutosaveFile(fileName());
1250 // Saving failed, so backup is not backup
1251 if (lyxrc.make_backup) {
1252 lyx::rename(s, fileName());
1260 // Returns false if unsuccesful
1261 bool Buffer::writeFile(string const & fname, bool flag) const
1263 // if flag is false writeFile will not create any GUI
1264 // warnings, only cerr.
1265 // Needed for autosave in background or panic save (Matthias 120496)
1267 if (read_only && (fname == filename)) {
1268 // Here we should come with a question if we should
1269 // perform the write anyway.
1271 lyxerr << _("Error! Document is read-only: ")
1274 WriteAlert(_("Error! Document is read-only: "),
1279 FileInfo finfo(fname);
1280 if (finfo.exist() && !finfo.writable()) {
1281 // Here we should come with a question if we should
1282 // try to do the save anyway. (i.e. do a chmod first)
1284 lyxerr << _("Error! Cannot write file: ")
1287 WriteFSAlert(_("Error! Cannot write file: "),
1292 ofstream ofs(fname.c_str());
1295 lyxerr << _("Error! Cannot open file: ")
1298 WriteFSAlert(_("Error! Cannot open file: "),
1304 // Use the standard "C" locale for file output.
1305 ofs.imbue(std::locale::classic());
1308 // The top of the file should not be written by params.
1310 // write out a comment in the top of the file
1311 ofs << '#' << LYX_DOCVERSION
1312 << " created this file. For more info see http://www.lyx.org/\n";
1314 ofs.setf(ios::showpoint|ios::fixed);
1317 char dummy_format[512];
1318 sprintf(dummy_format, "%.2f", LYX_FORMAT);
1319 ofs << "\\lyxformat " << dummy_format << "\n";
1321 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1324 ofs << "\\lyxformat " << LYX_FORMAT << "\n";
1326 // now write out the buffer paramters.
1327 params.writeFile(ofs);
1329 char footnoteflag = 0;
1332 // this will write out all the paragraphs
1333 // using recursive descent.
1334 paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1336 // Write marker that shows file is complete
1337 ofs << "\n\\the_end" << endl;
1341 // how to check if close went ok?
1342 // Following is an attempt... (BE 20001011)
1344 // good() returns false if any error occured, including some
1345 // formatting error.
1346 // bad() returns true if something bad happened in the buffer,
1347 // which should include file system full errors.
1354 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1356 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1366 string const Buffer::asciiParagraph(LyXParagraph const * par,
1367 unsigned int linelen) const
1369 ostringstream buffer;
1372 Inset const * inset;
1375 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
1379 int ltype_depth = 0;
1380 unsigned int currlinelen = 0;
1381 bool ref_printed = false;
1387 par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1391 || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1395 /* begins a footnote environment ? */
1396 if (footnoteflag != par->footnoteflag) {
1397 footnoteflag = par->footnoteflag;
1399 size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
1400 if ((linelen > 0) &&
1401 ((currlinelen + j) > linelen)) {
1406 << string_footnotekinds[par->footnotekind]
1412 /* begins or ends a deeper area ?*/
1413 if (depth != par->depth) {
1414 if (par->depth > depth) {
1415 while (par->depth > depth) {
1420 while (par->depth < depth) {
1426 /* First write the layout */
1427 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1428 if (tmp == "Itemize") {
1430 ltype_depth = depth+1;
1431 } else if (tmp == "Enumerate") {
1433 ltype_depth = depth+1;
1434 } else if (strstr(tmp.c_str(), "ection")) {
1436 ltype_depth = depth+1;
1437 } else if (strstr(tmp.c_str(), "aragraph")) {
1439 ltype_depth = depth+1;
1440 } else if (tmp == "Description") {
1442 ltype_depth = depth+1;
1443 } else if (tmp == "Abstract") {
1446 } else if (tmp == "Bibliography") {
1454 /* maybe some vertical spaces */
1456 /* the labelwidthstring used in lists */
1460 /* some pagebreaks? */
1464 /* what about the alignment */
1467 /* dummy layout, that means a footnote ended */
1468 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1472 lyxerr << "Should this ever happen?" << endl;
1476 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1477 for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
1485 for (char j = 0; j < depth; ++j)
1487 currlinelen = depth * 2;
1489 case 0: /* Standard */
1490 case 4: /* (Sub)Paragraph */
1491 case 5: /* Description */
1493 case 6: /* Abstract */
1495 buffer << "Abstract\n\n";
1497 buffer << "Abstract: ";
1499 case 7: /* Bibliography */
1502 buffer << "References\n\n";
1504 buffer << "References: ";
1509 buffer << par->labelstring << " ";
1512 if (ltype_depth > depth) {
1513 for (char j = ltype_depth - 1; j > depth; --j)
1515 currlinelen += (ltype_depth-depth)*2;
1518 font2 = par->GetFontSettings(params, i);
1519 if (font1.latex() != font2.latex()) {
1520 if (font2.latex() == LyXFont::OFF)
1527 c = par->GetChar(i);
1531 case LyXParagraph::META_INSET:
1532 if ((inset = par->GetInset(i))) {
1533 if (!inset->Ascii(this, buffer)) {
1535 string s = rsplit(buffer.str().c_str(),
1537 currlinelen += s.length();
1539 // to be sure it breaks paragraph
1540 currlinelen += linelen;
1544 case LyXParagraph::META_NEWLINE:
1547 for (char j = 0; j < depth; ++j)
1550 currlinelen = depth * 2;
1551 if (ltype_depth > depth) {
1552 for (char j = ltype_depth;
1555 currlinelen += (ltype_depth - depth) * 2;
1558 case LyXParagraph::META_HFILL:
1565 if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1566 (c == ' ') && ((i + 2) < par->size()))
1569 for (char j = 0; j < depth; ++j)
1571 currlinelen = depth * 2;
1572 if (ltype_depth > depth) {
1573 for (char j = ltype_depth;
1576 currlinelen += (ltype_depth-depth)*2;
1578 } else if (c != '\0')
1581 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1586 return buffer.str().c_str();
1590 void Buffer::writeFileAscii(string const & fname, int linelen)
1592 ofstream ofs(fname.c_str());
1594 WriteFSAlert(_("Error: Cannot write file:"), fname);
1597 writeFileAscii(ofs, linelen);
1601 void Buffer::writeFileAscii(ostream & ofs, int linelen)
1603 LyXParagraph * par = paragraph;
1605 ofs << asciiParagraph(par, linelen);
1612 void Buffer::makeLaTeXFile(string const & fname,
1613 string const & original_path,
1614 bool nice, bool only_body)
1616 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1618 niceFile = nice; // this will be used by Insetincludes.
1620 tex_code_break_column = lyxrc.ascii_linelen;
1622 LyXTextClass const & tclass =
1623 textclasslist.TextClass(params.textclass);
1625 ofstream ofs(fname.c_str());
1627 WriteFSAlert(_("Error: Cannot open file: "), fname);
1631 // validate the buffer.
1632 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1633 LaTeXFeatures features(params, tclass.numLayouts());
1635 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1638 // The starting paragraph of the coming rows is the
1639 // first paragraph of the document. (Asger)
1640 texrow.start(paragraph, 0);
1642 if (!only_body && nice) {
1643 ofs << "%% " LYX_DOCVERSION " created this file. "
1644 "For more info, see http://www.lyx.org/.\n"
1645 "%% Do not edit unless you really know what "
1650 lyxerr.debug() << "lyx header finished" << endl;
1651 // There are a few differences between nice LaTeX and usual files:
1652 // usual is \batchmode and has a
1653 // special input@path to allow the including of figures
1654 // with either \input or \includegraphics (what figinsets do).
1655 // batchmode is not set if there is a tex_code_break_column.
1656 // In this case somebody is interested in the generated LaTeX,
1657 // so this is OK. input@path is set when the actual parameter
1658 // original_path is set. This is done for usual tex-file, but not
1659 // for nice-latex-file. (Matthias 250696)
1662 // code for usual, NOT nice-latex-file
1663 ofs << "\\batchmode\n"; // changed
1664 // from \nonstopmode
1667 if (!original_path.empty()) {
1668 ofs << "\\makeatletter\n"
1669 << "\\def\\input@path{{"
1670 << original_path << "/}}\n"
1671 << "\\makeatother\n";
1677 ofs << "\\documentclass";
1679 string options; // the document class options.
1681 if (tokenPos(tclass.opt_fontsize(),
1682 '|', params.fontsize) >= 0) {
1683 // only write if existing in list (and not default)
1684 options += params.fontsize;
1689 if (!params.use_geometry &&
1690 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1691 switch (params.papersize) {
1692 case BufferParams::PAPER_A4PAPER:
1693 options += "a4paper,";
1695 case BufferParams::PAPER_USLETTER:
1696 options += "letterpaper,";
1698 case BufferParams::PAPER_A5PAPER:
1699 options += "a5paper,";
1701 case BufferParams::PAPER_B5PAPER:
1702 options += "b5paper,";
1704 case BufferParams::PAPER_EXECUTIVEPAPER:
1705 options += "executivepaper,";
1707 case BufferParams::PAPER_LEGALPAPER:
1708 options += "legalpaper,";
1714 if (params.sides != tclass.sides()) {
1715 switch (params.sides) {
1716 case LyXTextClass::OneSide:
1717 options += "oneside,";
1719 case LyXTextClass::TwoSides:
1720 options += "twoside,";
1727 if (params.columns != tclass.columns()) {
1728 if (params.columns == 2)
1729 options += "twocolumn,";
1731 options += "onecolumn,";
1734 if (!params.use_geometry
1735 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1736 options += "landscape,";
1738 // language should be a parameter to \documentclass
1739 bool use_babel = false;
1740 if (params.language->babel() == "hebrew"
1741 && default_language->babel() != "hebrew")
1742 // This seems necessary
1743 features.UsedLanguages.insert(default_language);
1744 #ifdef DO_USE_DEFAULT_LANGUAGE
1745 if (params.language->lang() != "default" ||
1746 !features.UsedLanguages.empty()) {
1749 for (LaTeXFeatures::LanguageList::const_iterator cit =
1750 features.UsedLanguages.begin();
1751 cit != features.UsedLanguages.end(); ++cit)
1752 options += (*cit)->babel() + ",";
1753 options += params.language->babel() + ',';
1754 #ifdef DO_USE_DEFAULT_LANGUAGE
1758 // the user-defined options
1759 if (!params.options.empty()) {
1760 options += params.options + ',';
1763 if (!options.empty()){
1764 options = strip(options, ',');
1765 ofs << '[' << options << ']';
1769 << textclasslist.LatexnameOfClass(params.textclass)
1772 // end of \documentclass defs
1774 // font selection must be done before loading fontenc.sty
1775 // The ae package is not needed when using OT1 font encoding.
1776 if (params.fonts != "default" &&
1777 (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1778 ofs << "\\usepackage{" << params.fonts << "}\n";
1780 if (params.fonts == "ae") {
1781 ofs << "\\usepackage{aecompl}\n";
1785 // this one is not per buffer
1786 if (lyxrc.fontenc != "default") {
1787 ofs << "\\usepackage[" << lyxrc.fontenc
1792 if (params.inputenc == "auto") {
1793 string const doc_encoding =
1794 params.language->encoding()->LatexName();
1796 // Create a list with all the input encodings used
1798 set<string> encodings;
1799 for (LaTeXFeatures::LanguageList::const_iterator it =
1800 features.UsedLanguages.begin();
1801 it != features.UsedLanguages.end(); ++it)
1802 if ((*it)->encoding()->LatexName() != doc_encoding)
1803 encodings.insert((*it)->encoding()->LatexName());
1805 ofs << "\\usepackage[";
1806 std::copy(encodings.begin(), encodings.end(),
1807 std::ostream_iterator<string>(ofs, ","));
1808 ofs << doc_encoding << "]{inputenc}\n";
1810 } else if (params.inputenc != "default") {
1811 ofs << "\\usepackage[" << params.inputenc
1816 // At the very beginning the text parameters.
1817 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1818 switch (params.paperpackage) {
1819 case BufferParams::PACKAGE_A4:
1820 ofs << "\\usepackage{a4}\n";
1823 case BufferParams::PACKAGE_A4WIDE:
1824 ofs << "\\usepackage{a4wide}\n";
1827 case BufferParams::PACKAGE_WIDEMARGINSA4:
1828 ofs << "\\usepackage[widemargins]{a4}\n";
1833 if (params.use_geometry) {
1834 ofs << "\\usepackage{geometry}\n";
1836 ofs << "\\geometry{verbose";
1837 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1838 ofs << ",landscape";
1839 switch (params.papersize2) {
1840 case BufferParams::VM_PAPER_CUSTOM:
1841 if (!params.paperwidth.empty())
1842 ofs << ",paperwidth="
1843 << params.paperwidth;
1844 if (!params.paperheight.empty())
1845 ofs << ",paperheight="
1846 << params.paperheight;
1848 case BufferParams::VM_PAPER_USLETTER:
1849 ofs << ",letterpaper";
1851 case BufferParams::VM_PAPER_USLEGAL:
1852 ofs << ",legalpaper";
1854 case BufferParams::VM_PAPER_USEXECUTIVE:
1855 ofs << ",executivepaper";
1857 case BufferParams::VM_PAPER_A3:
1860 case BufferParams::VM_PAPER_A4:
1863 case BufferParams::VM_PAPER_A5:
1866 case BufferParams::VM_PAPER_B3:
1869 case BufferParams::VM_PAPER_B4:
1872 case BufferParams::VM_PAPER_B5:
1876 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1877 switch (lyxrc.default_papersize) {
1878 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1879 case BufferParams::PAPER_USLETTER:
1880 ofs << ",letterpaper";
1882 case BufferParams::PAPER_LEGALPAPER:
1883 ofs << ",legalpaper";
1885 case BufferParams::PAPER_EXECUTIVEPAPER:
1886 ofs << ",executivepaper";
1888 case BufferParams::PAPER_A3PAPER:
1891 case BufferParams::PAPER_A4PAPER:
1894 case BufferParams::PAPER_A5PAPER:
1897 case BufferParams::PAPER_B5PAPER:
1902 if (!params.topmargin.empty())
1903 ofs << ",tmargin=" << params.topmargin;
1904 if (!params.bottommargin.empty())
1905 ofs << ",bmargin=" << params.bottommargin;
1906 if (!params.leftmargin.empty())
1907 ofs << ",lmargin=" << params.leftmargin;
1908 if (!params.rightmargin.empty())
1909 ofs << ",rmargin=" << params.rightmargin;
1910 if (!params.headheight.empty())
1911 ofs << ",headheight=" << params.headheight;
1912 if (!params.headsep.empty())
1913 ofs << ",headsep=" << params.headsep;
1914 if (!params.footskip.empty())
1915 ofs << ",footskip=" << params.footskip;
1919 if (features.amsstyle
1920 && !tclass.provides(LyXTextClass::amsmath)) {
1921 ofs << "\\usepackage{amsmath}\n";
1925 if (tokenPos(tclass.opt_pagestyle(),
1926 '|', params.pagestyle) >= 0) {
1927 if (params.pagestyle == "fancy") {
1928 ofs << "\\usepackage{fancyhdr}\n";
1931 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1935 // We try to load babel late, in case it interferes
1936 // with other packages.
1938 ofs << lyxrc.language_package << endl;
1942 if (params.secnumdepth != tclass.secnumdepth()) {
1943 ofs << "\\setcounter{secnumdepth}{"
1944 << params.secnumdepth
1948 if (params.tocdepth != tclass.tocdepth()) {
1949 ofs << "\\setcounter{tocdepth}{"
1955 if (params.paragraph_separation) {
1956 switch (params.defskip.kind()) {
1957 case VSpace::SMALLSKIP:
1958 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1960 case VSpace::MEDSKIP:
1961 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1963 case VSpace::BIGSKIP:
1964 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1966 case VSpace::LENGTH:
1967 ofs << "\\setlength\\parskip{"
1968 << params.defskip.length().asLatexString()
1971 default: // should never happen // Then delete it.
1972 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1977 ofs << "\\setlength\\parindent{0pt}\n";
1981 // Now insert the LyX specific LaTeX commands...
1983 // The optional packages;
1984 string preamble(features.getPackages());
1986 // this might be useful...
1987 preamble += "\n\\makeatletter\n";
1989 // Some macros LyX will need
1990 string tmppreamble(features.getMacros());
1992 if (!tmppreamble.empty()) {
1993 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1994 "LyX specific LaTeX commands.\n"
1995 + tmppreamble + '\n';
1998 // the text class specific preamble
1999 tmppreamble = features.getTClassPreamble();
2000 if (!tmppreamble.empty()) {
2001 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2002 "Textclass specific LaTeX commands.\n"
2003 + tmppreamble + '\n';
2006 /* the user-defined preamble */
2007 if (!params.preamble.empty()) {
2008 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2009 "User specified LaTeX commands.\n"
2010 + params.preamble + '\n';
2013 preamble += "\\makeatother\n";
2015 // Itemize bullet settings need to be last in case the user
2016 // defines their own bullets that use a package included
2017 // in the user-defined preamble -- ARRae
2018 // Actually it has to be done much later than that
2019 // since some packages like frenchb make modifications
2020 // at \begin{document} time -- JMarc
2022 for (int i = 0; i < 4; ++i) {
2023 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2024 if (bullets_def.empty())
2025 bullets_def="\\AtBeginDocument{\n";
2026 bullets_def += " \\renewcommand{\\labelitemi";
2028 // `i' is one less than the item to modify
2035 bullets_def += "ii";
2041 bullets_def += "}{" +
2042 params.user_defined_bullets[i].getText()
2047 if (!bullets_def.empty())
2048 preamble += bullets_def + "}\n\n";
2050 for (int j = countChar(preamble, '\n'); j-- ;) {
2057 ofs << "\\begin{document}\n";
2060 lyxerr.debug() << "preamble finished, now the body." << endl;
2061 #ifdef DO_USE_DEFAULT_LANGUAGE
2062 if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
2064 if (!lyxrc.language_auto_begin) {
2066 ofs << subst(lyxrc.language_command_begin, "$$lang",
2067 params.language->babel())
2072 latexParagraphs(ofs, paragraph, 0, texrow);
2074 // add this just in case after all the paragraphs
2078 #ifdef DO_USE_DEFAULT_LANGUAGE
2079 if (!lyxrc.language_auto_end && params.language->lang() != "default") {
2081 if (!lyxrc.language_auto_end) {
2083 ofs << subst(lyxrc.language_command_end, "$$lang",
2084 params.language->babel())
2090 ofs << "\\end{document}\n";
2093 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2095 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2099 // Just to be sure. (Asger)
2102 // tex_code_break_column's value is used to decide
2103 // if we are in batchmode or not (within mathed_write()
2104 // in math_write.C) so we must set it to a non-zero
2105 // value when we leave otherwise we save incorrect .lyx files.
2106 tex_code_break_column = lyxrc.ascii_linelen;
2110 lyxerr << "File was not closed properly." << endl;
2113 lyxerr.debug() << "Finished making latex file." << endl;
2118 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2120 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2121 LyXParagraph * endpar, TexRow & texrow) const
2123 bool was_title = false;
2124 bool already_title = false;
2125 std::ostringstream ftnote;
2130 while (par != endpar) {
2133 lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2136 LyXLayout const & layout =
2137 textclasslist.Style(params.textclass,
2140 if (layout.intitle) {
2141 if (already_title) {
2142 lyxerr <<"Error in latexParagraphs: You"
2143 " should not mix title layouts"
2144 " with normal ones." << endl;
2147 } else if (was_title && !already_title) {
2148 ofs << "\\maketitle\n";
2150 already_title = true;
2153 // We are at depth 0 so we can just use
2154 // ordinary \footnote{} generation
2155 // flag this with ftcount
2157 if (layout.isEnvironment()
2158 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2159 par = par->TeXEnvironment(this, params, ofs, texrow
2161 ,ftnote, ft_texrow, ftcount
2165 par = par->TeXOnePar(this, params, ofs, texrow, false
2168 ftnote, ft_texrow, ftcount
2173 // Write out what we've generated...
2176 ofs << "\\addtocounter{footnote}{-"
2180 ofs << ftnote.str();
2181 texrow += ft_texrow;
2183 // The extra .c_str() is needed when we use
2184 // lyxstring instead of the STL string class.
2185 ftnote.str(string().c_str());
2190 // It might be that we only have a title in this document
2191 if (was_title && !already_title) {
2192 ofs << "\\maketitle\n";
2198 bool Buffer::isLatex() const
2200 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2204 bool Buffer::isLinuxDoc() const
2206 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2210 bool Buffer::isLiterate() const
2212 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2216 bool Buffer::isDocBook() const
2218 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2222 bool Buffer::isSGML() const
2224 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2225 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2229 void Buffer::sgmlOpenTag(ostream & os, int depth,
2230 string const & latexname) const
2232 if (latexname != "!-- --")
2233 os << string(depth, ' ') << "<" << latexname << ">\n";
2237 void Buffer::sgmlCloseTag(ostream & os, int depth,
2238 string const & latexname) const
2240 if (latexname != "!-- --")
2241 os << string(depth, ' ') << "</" << latexname << ">\n";
2245 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2247 LyXParagraph * par = paragraph;
2249 niceFile = nice; // this will be used by Insetincludes.
2251 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2252 string environment_stack[10];
2255 int depth = 0; // paragraph depth
2257 ofstream ofs(fname.c_str());
2260 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2264 LyXTextClass const & tclass =
2265 textclasslist.TextClass(params.textclass);
2267 LaTeXFeatures features(params, tclass.numLayouts());
2271 tex_code_break_column = lyxrc.ascii_linelen;
2273 //tex_code_break_column = 0;
2278 string sgml_includedfiles=features.getIncludedFiles(fname);
2280 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2281 ofs << "<!doctype linuxdoc system>\n\n";
2283 ofs << "<!doctype linuxdoc system [ "
2284 << params.preamble << sgml_includedfiles << " \n]>\n\n";
2287 if (params.options.empty())
2288 sgmlOpenTag(ofs, 0, top_element);
2290 string top = top_element;
2292 top += params.options;
2293 sgmlOpenTag(ofs, 0, top);
2297 ofs << "<!-- " << LYX_DOCVERSION
2298 << " created this file. For more info see http://www.lyx.org/"
2302 int desc_on = 0; // description mode
2303 LyXLayout const & style =
2304 textclasslist.Style(params.textclass,
2307 // treat <toc> as a special case for compatibility with old code
2308 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2309 Inset * inset = par->GetInset(0);
2310 Inset::Code lyx_code = inset->LyxCode();
2311 if (lyx_code == Inset::TOC_CODE){
2312 string const temp = "toc";
2313 sgmlOpenTag(ofs, depth, temp);
2317 linuxDocHandleFootnote(ofs, par, depth);
2323 // environment tag closing
2324 for (; depth > par->depth; --depth) {
2325 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2326 environment_stack[depth].erase();
2329 // write opening SGML tags
2330 switch (style.latextype) {
2331 case LATEX_PARAGRAPH:
2332 if (depth == par->depth
2333 && !environment_stack[depth].empty()) {
2334 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2335 environment_stack[depth].erase();
2341 sgmlOpenTag(ofs, depth, style.latexname());
2346 LinuxDocError(par, 0,
2347 _("Error : Wrong depth for"
2348 " LatexType Command.\n"));
2350 if (!environment_stack[depth].empty()){
2351 sgmlCloseTag(ofs, depth,
2352 environment_stack[depth]);
2356 environment_stack[depth].erase();
2357 sgmlOpenTag(ofs, depth, style.latexname());
2360 case LATEX_ENVIRONMENT:
2361 case LATEX_ITEM_ENVIRONMENT:
2362 if (depth == par->depth
2363 && environment_stack[depth] != style.latexname()
2364 && !environment_stack[depth].empty()) {
2366 sgmlCloseTag(ofs, depth,
2367 environment_stack[depth]);
2368 environment_stack[depth].erase();
2370 if (depth < par->depth) {
2372 environment_stack[depth].erase();
2374 if (environment_stack[depth] != style.latexname()) {
2376 string const temp = "p";
2377 sgmlOpenTag(ofs, depth, temp);
2379 environment_stack[depth] = style.latexname();
2380 sgmlOpenTag(ofs, depth,
2381 environment_stack[depth]);
2383 if (style.latextype == LATEX_ENVIRONMENT) break;
2385 desc_on = (style.labeltype == LABEL_MANUAL);
2392 sgmlOpenTag(ofs, depth + 1, item_name);
2395 sgmlOpenTag(ofs, depth, style.latexname());
2402 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2406 linuxDocHandleFootnote(ofs, par, depth);
2408 while(par && par->IsDummy());
2412 // write closing SGML tags
2413 switch (style.latextype) {
2415 case LATEX_ENVIRONMENT:
2416 case LATEX_ITEM_ENVIRONMENT:
2419 sgmlCloseTag(ofs, depth, style.latexname());
2425 for (; depth > 0; --depth)
2426 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2428 if (!environment_stack[depth].empty())
2429 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2433 sgmlCloseTag(ofs, 0, top_element);
2437 // How to check for successful close
2442 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2445 string const tag = "footnote";
2447 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2448 sgmlOpenTag(os, depth + 1, tag);
2449 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2450 sgmlCloseTag(os, depth + 1, tag);
2457 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2458 int depth, int desc_on,
2459 LyXParagraph * & par)
2461 LyXParagraph * tpar = par;
2464 && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2466 && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2470 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2471 "Caption").second) {
2472 sgmlOpenTag(os, depth + 1, inner_tag);
2474 SimpleDocBookOnePar(os, extra_par, tpar,
2475 desc_on, depth + 2);
2476 sgmlCloseTag(os, depth+1, inner_tag);
2477 if (!extra_par.empty())
2484 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2487 string tag, inner_tag;
2488 string tmp_par, extra_par;
2489 bool inner_span = false;
2492 // Someone should give this enum a proper name (Lgb)
2500 SOME_ENUM last = NO_ONE;
2501 SOME_ENUM present = FOOTNOTE_LIKE;
2503 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2504 if (last == present) {
2506 if (!tmp_par.empty()) {
2509 sgmlCloseTag(os, depth + 1, inner_tag);
2510 sgmlOpenTag(os, depth + 1, inner_tag);
2517 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2519 if (!extra_par.empty()) os << extra_par;
2520 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2523 switch (par->footnotekind) {
2524 case LyXParagraph::FOOTNOTE:
2525 case LyXParagraph::ALGORITHM:
2528 present = FOOTNOTE_LIKE;
2531 case LyXParagraph::MARGIN:
2534 present = MARGIN_LIKE;
2537 case LyXParagraph::FIG:
2538 case LyXParagraph::WIDE_FIG:
2540 inner_tag = "title";
2544 case LyXParagraph::TAB:
2545 case LyXParagraph::WIDE_TAB:
2547 inner_tag = "title";
2552 sgmlOpenTag(os, depth, tag);
2553 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2554 DocBookHandleCaption(os, inner_tag, depth,
2558 sgmlOpenTag(os, depth + 1, inner_tag);
2561 // ignore all caption here, we processed them above!!!
2562 if (par->layout != textclasslist
2563 .NumberOfLayout(params.textclass,
2564 "Caption").second) {
2565 std::ostringstream ost;
2566 SimpleDocBookOnePar(ost, extra_par, par,
2567 desc_on, depth + 2);
2568 tmp_par += ost.str().c_str();
2570 tmp_par = frontStrip(strip(tmp_par));
2576 if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2577 if (!extra_par.empty()) os << extra_par;
2578 if (!tag.empty()) sgmlCloseTag(os, depth, tag);
2583 // push a tag in a style stack
2584 void Buffer::push_tag(ostream & os, string const & tag,
2585 int & pos, char stack[5][3])
2587 #ifdef WITH_WARNINGS
2588 #warning Use a real stack! (Lgb)
2590 // pop all previous tags
2591 for (int j = pos; j >= 0; --j)
2592 os << "</" << stack[j] << ">";
2595 sprintf(stack[++pos], "%s", tag.c_str());
2598 for (int i = 0; i <= pos; ++i)
2599 os << "<" << stack[i] << ">";
2603 void Buffer::pop_tag(ostream & os, string const & tag,
2604 int & pos, char stack[5][3])
2606 #ifdef WITH_WARNINGS
2607 #warning Use a real stack! (Lgb)
2609 // Please, Lars, do not remove the global variable. I already
2610 // had to reintroduce it twice! (JMarc)
2611 // but...but... I'll remove it anyway. (well not quite) (Lgb)
2615 // pop all tags till specified one
2616 for (j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2617 os << "</" << stack[j] << ">";
2620 os << "</" << tag << ">";
2622 // push all tags, but the specified one
2623 for (j = j + 1; j <= pos; ++j) {
2624 os << "<" << stack[j] << ">";
2625 strcpy(stack[j - 1], stack[j]);
2629 // pop all tags till specified one
2631 for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
2632 os << "</" << stack[j] << ">";
2635 os << "</" << tag << ">";
2637 // push all tags, but the specified one
2638 for (int i = j + 1; i <= pos; ++i) {
2639 os << "<" << stack[i] << ">";
2640 strcpy(stack[i - 1], stack[i]);
2647 // Handle internal paragraph parsing -- layout already processed.
2649 // checks, if newcol chars should be put into this line
2650 // writes newline, if necessary.
2652 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2653 string::size_type newcol)
2656 if (colcount > lyxrc.ascii_linelen) {
2658 colcount = newcol; // assume write after this call
2663 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2664 int desc_on, int /*depth*/)
2669 LyXParagraph::size_type main_body;
2671 LyXLayout const & style = textclasslist.Style(params.textclass,
2674 char family_type = 0; // family font flag
2675 bool is_bold = false; // series font flag
2676 char shape_type = 0; // shape font flag
2677 bool is_em = false; // emphasis (italic) font flag
2679 int stack_num = -1; // style stack position
2680 // Can this be rewritten to use a std::stack, please. (Lgb)
2681 char stack[5][3]; // style stack
2682 string::size_type char_line_count = 5; // Heuristic choice ;-)
2684 if (style.labeltype != LABEL_MANUAL)
2687 main_body = par->BeginningOfMainBody();
2689 // gets paragraph main font
2691 font1 = style.labelfont;
2696 // parsing main loop
2697 for (LyXParagraph::size_type i = 0;
2698 i < par->size(); ++i) {
2710 LyXFont const font2 = par->getFont(params, i);
2712 if (font1.family() != font2.family()) {
2713 switch (family_type) {
2715 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2716 push_tag(os, "tt", stack_num, stack);
2719 else if (font2.family() == LyXFont::SANS_FAMILY) {
2720 push_tag(os, "sf", stack_num, stack);
2725 pop_tag(os, "tt", stack_num, stack);
2726 if (font2.family() == LyXFont::SANS_FAMILY) {
2727 push_tag(os, "sf", stack_num, stack);
2734 pop_tag(os, "sf", stack_num, stack);
2735 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2736 push_tag(os, "tt", stack_num, stack);
2745 if (font1.series() != font2.series()) {
2746 if (font2.series() == LyXFont::BOLD_SERIES) {
2747 push_tag(os, "bf", stack_num, stack);
2749 } else if (is_bold) {
2750 pop_tag(os, "bf", stack_num, stack);
2755 // handle italic and slanted fonts
2756 if (font1.shape() != font2.shape()) {
2757 switch (shape_type) {
2759 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2760 push_tag(os, "it", stack_num, stack);
2762 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2763 push_tag(os, "sl", stack_num, stack);
2768 pop_tag(os, "it", stack_num, stack);
2769 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2770 push_tag(os, "sl", stack_num, stack);
2777 pop_tag(os, "sl", stack_num, stack);
2778 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2779 push_tag(os, "it", stack_num, stack);
2787 if (font1.emph() != font2.emph()) {
2788 if (font2.emph() == LyXFont::ON) {
2789 push_tag(os, "em", stack_num, stack);
2792 pop_tag(os, "em", stack_num, stack);
2797 c = par->GetChar(i);
2799 if (c == LyXParagraph::META_INSET) {
2800 inset = par->GetInset(i);
2801 inset->Linuxdoc(this, os);
2804 if (font2.latex() == LyXFont::ON) {
2805 // "TeX"-Mode on == > SGML-Mode on.
2807 os << c; // see LaTeX-Generation...
2811 if (par->linuxDocConvertChar(c, sgml_string)
2812 && !style.free_spacing) { // in freespacing
2814 // non-breaking characters
2818 linux_doc_line_break(os, char_line_count, 6);
2822 linux_doc_line_break(os, char_line_count, 1);
2827 char_line_count += sgml_string.length();
2833 // needed if there is an optional argument but no contents
2834 if (main_body > 0 && main_body == par->size()) {
2838 // pop all defined Styles
2839 for (j = stack_num; j >= 0; --j) {
2840 linux_doc_line_break(os,
2842 3 + strlen(stack[j]));
2843 os << "</" << stack[j] << ">";
2846 // resets description flag correctly
2849 // <tag> not closed...
2850 linux_doc_line_break(os, char_line_count, 6);
2854 // fprintf(file, "</p>");
2860 // Print an error message.
2861 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2862 string const & message)
2864 // insert an error marker in text
2865 InsetError * new_inset = new InsetError(message);
2866 par->InsertInset(pos, new_inset);
2869 // This constant defines the maximum number of
2870 // environment layouts that can be nesteded.
2871 // The same applies for command layouts.
2872 // These values should be more than enough.
2873 // José Matos (1999/07/22)
2875 enum { MAX_NEST_LEVEL = 25};
2877 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2879 LyXParagraph * par = paragraph;
2881 niceFile = nice; // this will be used by Insetincludes.
2883 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2884 // Please use a real stack.
2885 string environment_stack[MAX_NEST_LEVEL];
2886 string environment_inner[MAX_NEST_LEVEL];
2887 // Please use a real stack.
2888 string command_stack[MAX_NEST_LEVEL];
2889 bool command_flag= false;
2890 int command_depth= 0, command_base= 0, cmd_depth= 0;
2892 string item_name, command_name;
2893 string c_depth, c_params, tmps;
2895 int depth = 0; // paragraph depth
2896 LyXTextClass const & tclass =
2897 textclasslist.TextClass(params.textclass);
2899 LaTeXFeatures features(params, tclass.numLayouts());
2903 tex_code_break_column = lyxrc.ascii_linelen;
2905 //tex_code_break_column = 0;
2907 ofstream ofs(fname.c_str());
2909 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2916 string sgml_includedfiles=features.getIncludedFiles(fname);
2918 ofs << "<!doctype " << top_element
2919 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2921 if (params.preamble.empty() && sgml_includedfiles.empty())
2924 ofs << "\n [ " << params.preamble
2925 << sgml_includedfiles << " \n]>\n\n";
2928 string top = top_element;
2930 top += params.language->code();
2933 if (!params.options.empty()) {
2935 top += params.options;
2937 sgmlOpenTag(ofs, 0, top);
2939 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2940 << "\n See http://www.lyx.org/ for more information -->\n";
2943 int desc_on = 0; // description mode
2944 LyXLayout const & style =
2945 textclasslist.Style(params.textclass,
2948 // environment tag closing
2949 for (; depth > par->depth; --depth) {
2950 if (environment_inner[depth] != "!-- --") {
2951 item_name= "listitem";
2952 sgmlCloseTag(ofs, command_depth + depth,
2954 if (environment_inner[depth] == "varlistentry")
2955 sgmlCloseTag(ofs, depth+command_depth,
2956 environment_inner[depth]);
2958 sgmlCloseTag(ofs, depth + command_depth,
2959 environment_stack[depth]);
2960 environment_stack[depth].erase();
2961 environment_inner[depth].erase();
2964 if (depth == par->depth
2965 && environment_stack[depth] != style.latexname()
2966 && !environment_stack[depth].empty()) {
2967 if (environment_inner[depth] != "!-- --") {
2968 item_name= "listitem";
2969 sgmlCloseTag(ofs, command_depth+depth,
2971 if (environment_inner[depth] == "varlistentry")
2973 depth + command_depth,
2974 environment_inner[depth]);
2977 sgmlCloseTag(ofs, depth + command_depth,
2978 environment_stack[depth]);
2980 environment_stack[depth].erase();
2981 environment_inner[depth].erase();
2984 // Write opening SGML tags.
2985 switch (style.latextype) {
2986 case LATEX_PARAGRAPH:
2987 sgmlOpenTag(ofs, depth+command_depth, style.latexname());
2992 LinuxDocError(par, 0,
2993 _("Error : Wrong depth for "
2994 "LatexType Command.\n"));
2996 command_name = style.latexname();
2998 tmps = style.latexparam();
2999 c_params = split(tmps, c_depth,'|');
3001 cmd_depth= lyx::atoi(c_depth);
3004 if (cmd_depth<command_base) {
3005 for (int j = command_depth;
3006 j >= command_base; --j)
3007 if (!command_stack[j].empty())
3008 sgmlCloseTag(ofs, j, command_stack[j]);
3009 command_depth= command_base= cmd_depth;
3010 } else if (cmd_depth <= command_depth) {
3011 for (int j = command_depth;
3012 j >= cmd_depth; --j)
3014 if (!command_stack[j].empty())
3015 sgmlCloseTag(ofs, j, command_stack[j]);
3016 command_depth= cmd_depth;
3018 command_depth= cmd_depth;
3020 command_depth = command_base = cmd_depth;
3021 command_flag = true;
3023 command_stack[command_depth]= command_name;
3025 // treat label as a special case for
3026 // more WYSIWYM handling.
3027 if (par->GetChar(0) == LyXParagraph::META_INSET) {
3028 Inset * inset = par->GetInset(0);
3029 Inset::Code lyx_code = inset->LyxCode();
3030 if (lyx_code == Inset::LABEL_CODE){
3031 command_name += " id=\"";
3032 command_name += (static_cast<InsetCommand *>(inset))->getContents();
3033 command_name += "\"";
3038 sgmlOpenTag(ofs, depth + command_depth, command_name);
3039 item_name = "title";
3040 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3043 case LATEX_ENVIRONMENT:
3044 case LATEX_ITEM_ENVIRONMENT:
3045 if (depth < par->depth) {
3047 environment_stack[depth].erase();
3050 if (environment_stack[depth] != style.latexname()) {
3051 environment_stack[depth] = style.latexname();
3052 environment_inner[depth] = "!-- --";
3053 sgmlOpenTag(ofs, depth + command_depth,
3054 environment_stack[depth]);
3056 if (environment_inner[depth] != "!-- --") {
3057 item_name= "listitem";
3059 command_depth + depth,
3061 if (environment_inner[depth] == "varlistentry")
3063 depth + command_depth,
3064 environment_inner[depth]);
3068 if (style.latextype == LATEX_ENVIRONMENT) {
3069 if (!style.latexparam().empty()) {
3070 if(style.latexparam() == "CDATA")
3071 ofs << "<![ CDATA [";
3073 sgmlOpenTag(ofs, depth + command_depth,
3074 style.latexparam());
3079 desc_on = (style.labeltype == LABEL_MANUAL);
3082 environment_inner[depth]= "varlistentry";
3084 environment_inner[depth]= "listitem";
3086 sgmlOpenTag(ofs, depth + 1 + command_depth,
3087 environment_inner[depth]);
3091 sgmlOpenTag(ofs, depth + 1 + command_depth,
3095 sgmlOpenTag(ofs, depth + 1 + command_depth,
3100 sgmlOpenTag(ofs, depth + command_depth,
3109 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3110 depth + 1 + command_depth);
3113 DocBookHandleFootnote(ofs, par,
3114 depth + 1 + command_depth);
3116 while(par && par->IsDummy());
3119 // write closing SGML tags
3120 switch (style.latextype) {
3123 sgmlCloseTag(ofs, depth + command_depth, end_tag);
3125 case LATEX_ENVIRONMENT:
3126 if (!style.latexparam().empty()) {
3127 if(style.latexparam() == "CDATA")
3130 sgmlCloseTag(ofs, depth + command_depth,
3131 style.latexparam());
3134 case LATEX_ITEM_ENVIRONMENT:
3135 if (desc_on == 1) break;
3137 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3139 case LATEX_PARAGRAPH:
3140 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3143 sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3149 for (; depth >= 0; --depth) {
3150 if (!environment_stack[depth].empty()) {
3151 if (environment_inner[depth] != "!-- --") {
3152 item_name= "listitem";
3153 sgmlCloseTag(ofs, command_depth + depth,
3155 if (environment_inner[depth] == "varlistentry")
3156 sgmlCloseTag(ofs, depth + command_depth,
3157 environment_inner[depth]);
3160 sgmlCloseTag(ofs, depth + command_depth,
3161 environment_stack[depth]);
3165 for (int j = command_depth; j >= command_base; --j)
3166 if (!command_stack[j].empty())
3167 sgmlCloseTag(ofs, j, command_stack[j]);
3170 sgmlCloseTag(ofs, 0, top_element);
3173 // How to check for successful close
3177 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3178 LyXParagraph * par, int & desc_on,
3181 bool emph_flag = false;
3183 LyXLayout const & style = textclasslist.Style(params.textclass,
3186 LyXParagraph::size_type main_body;
3187 if (style.labeltype != LABEL_MANUAL)
3190 main_body = par->BeginningOfMainBody();
3192 // gets paragraph main font
3193 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3195 int char_line_count = depth;
3196 if (!style.free_spacing)
3197 for (int j = 0; j < depth; ++j)
3200 // parsing main loop
3201 for (LyXParagraph::size_type i = 0;
3202 i < par->size(); ++i) {
3203 LyXFont font2 = par->getFont(params, i);
3205 // handle <emphasis> tag
3206 if (font1.emph() != font2.emph() && i) {
3207 if (font2.emph() == LyXFont::ON) {
3211 os << "</emphasis>";
3216 char c = par->GetChar(i);
3218 if (c == LyXParagraph::META_INSET) {
3219 Inset * inset = par->GetInset(i);
3220 std::ostringstream ost;
3221 inset->DocBook(this, ost);
3222 string tmp_out = ost.str().c_str();
3225 // This code needs some explanation:
3226 // Two insets are treated specially
3227 // label if it is the first element in a command paragraph
3229 // graphics inside tables or figure floats can't go on
3230 // title (the equivalente in latex for this case is caption
3231 // and title should come first
3234 if (desc_on!= 3 || i!= 0) {
3235 if (!tmp_out.empty() && tmp_out[0] == '@') {
3237 extra += frontStrip(tmp_out, '@');
3239 os << frontStrip(tmp_out, '@');
3244 } else if (font2.latex() == LyXFont::ON) {
3245 // "TeX"-Mode on ==> SGML-Mode on.
3251 if (par->linuxDocConvertChar(c, sgml_string)
3252 && !style.free_spacing) { // in freespacing
3254 // non-breaking characters
3258 os << "\n</term><listitem><para>";
3270 // needed if there is an optional argument but no contents
3271 if (main_body > 0 && main_body == par->size()) {
3275 os << "</emphasis>";
3278 // resets description flag correctly
3281 // <term> not closed...
3289 // This should be enabled when the Chktex class is implemented. (Asger)
3290 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3291 // Other flags: -wall -v0 -x
3292 int Buffer::runChktex()
3294 if (!users->text) return 0;
3296 ProhibitInput(users);
3298 // get LaTeX-Filename
3299 string const name = getLatexName();
3300 string path = OnlyPath(filename);
3302 string const org_path = path;
3303 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3307 Path p(path); // path to LaTeX file
3308 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3310 // Remove all error insets
3311 bool const removedErrorInsets = users->removeAutoInsets();
3313 // Generate the LaTeX file if neccessary
3314 makeLaTeXFile(name, org_path, false);
3317 Chktex chktex(lyxrc.chktex_command, name, filepath);
3318 int res = chktex.run(terr); // run chktex
3321 WriteAlert(_("chktex did not work!"),
3322 _("Could not run with file:"), name);
3323 } else if (res > 0) {
3324 // Insert all errors as errors boxes
3325 users->insertErrors(terr);
3328 // if we removed error insets before we ran chktex or if we inserted
3329 // error insets after we ran chktex, this must be run:
3330 if (removedErrorInsets || res){
3332 users->fitCursor(users->text);
3340 void Buffer::validate(LaTeXFeatures & features) const
3342 LyXParagraph * par = paragraph;
3343 LyXTextClass const & tclass =
3344 textclasslist.TextClass(params.textclass);
3346 // AMS Style is at document level
3348 features.amsstyle = (params.use_amsmath ||
3349 tclass.provides(LyXTextClass::amsmath));
3352 // We don't use "lyxerr.debug" because of speed. (Asger)
3353 if (lyxerr.debugging(Debug::LATEX))
3354 lyxerr << "Paragraph: " << par << endl;
3356 // Now just follow the list of paragraphs and run
3357 // validate on each of them.
3358 par->validate(features);
3360 // and then the next paragraph
3364 // the bullet shapes are buffer level not paragraph level
3365 // so they are tested here
3366 for (int i = 0; i < 4; ++i) {
3367 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3368 int const font = params.user_defined_bullets[i].getFont();
3370 int const c = params
3371 .user_defined_bullets[i]
3378 features.latexsym = true;
3380 } else if (font == 1) {
3381 features.amssymb = true;
3382 } else if ((font >= 2 && font <= 5)) {
3383 features.pifont = true;
3388 if (lyxerr.debugging(Debug::LATEX)) {
3389 features.showStruct();
3394 void Buffer::setPaperStuff()
3396 params.papersize = BufferParams::PAPER_DEFAULT;
3397 char const c1 = params.paperpackage;
3398 if (c1 == BufferParams::PACKAGE_NONE) {
3399 char const c2 = params.papersize2;
3400 if (c2 == BufferParams::VM_PAPER_USLETTER)
3401 params.papersize = BufferParams::PAPER_USLETTER;
3402 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3403 params.papersize = BufferParams::PAPER_LEGALPAPER;
3404 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3405 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3406 else if (c2 == BufferParams::VM_PAPER_A3)
3407 params.papersize = BufferParams::PAPER_A3PAPER;
3408 else if (c2 == BufferParams::VM_PAPER_A4)
3409 params.papersize = BufferParams::PAPER_A4PAPER;
3410 else if (c2 == BufferParams::VM_PAPER_A5)
3411 params.papersize = BufferParams::PAPER_A5PAPER;
3412 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3413 (c2 == BufferParams::VM_PAPER_B5))
3414 params.papersize = BufferParams::PAPER_B5PAPER;
3415 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3416 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3417 params.papersize = BufferParams::PAPER_A4PAPER;
3421 // This function should be in Buffer because it's a buffer's property (ale)
3422 string const Buffer::getIncludeonlyList(char delim)
3425 for (inset_iterator it = inset_iterator_begin();
3426 it != inset_iterator_end(); ++it) {
3427 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3428 InsetInclude * insetinc =
3429 static_cast<InsetInclude *>(*it);
3430 if (insetinc->isInclude()
3431 && insetinc->isNoLoad()) {
3434 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3438 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3443 vector<string> const Buffer::getLabelList()
3445 /// if this is a child document and the parent is already loaded
3446 /// Use the parent's list instead [ale990407]
3447 if (!params.parentname.empty()
3448 && bufferlist.exists(params.parentname)) {
3449 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3451 return tmp->getLabelList();
3454 vector<string> label_list;
3455 for (inset_iterator it = inset_iterator_begin();
3456 it != inset_iterator_end(); ++it) {
3457 vector<string> const l = (*it)->getLabelList();
3458 label_list.insert(label_list.end(), l.begin(), l.end());
3464 vector<vector<Buffer::TocItem> > const Buffer::getTocList() const
3469 vector<vector<TocItem> > l(4);
3470 LyXParagraph * par = paragraph;
3473 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3474 if (textclasslist.Style(params.textclass,
3475 par->GetLayout()).labeltype
3476 == LABEL_SENSITIVE) {
3480 tmp.str = par->String(this, false);
3481 switch (par->footnotekind) {
3482 case LyXParagraph::FIG:
3483 case LyXParagraph::WIDE_FIG:
3484 tmp.str = tostr(++figs) + ". "
3486 l[TOC_LOF].push_back(tmp);
3488 case LyXParagraph::TAB:
3489 case LyXParagraph::WIDE_TAB:
3490 tmp.str = tostr(++tables) + ". "
3492 l[TOC_LOT].push_back(tmp);
3494 case LyXParagraph::ALGORITHM:
3495 tmp.str = tostr(++algs) + ". "
3497 l[TOC_LOA].push_back(tmp);
3499 case LyXParagraph::FOOTNOTE:
3500 case LyXParagraph::MARGIN:
3504 } else if (!par->IsDummy()) {
3506 char const labeltype =
3507 textclasslist.Style(params.textclass,
3508 par->GetLayout()).labeltype;
3510 if (labeltype >= LABEL_COUNTER_CHAPTER
3511 && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3512 // insert this into the table of contents
3517 textclasslist.TextClass(params.textclass).maxcounter());
3518 tmp.str = par->String(this, true);
3519 l[TOC_TOC].push_back(tmp);
3530 // This is also a buffer property (ale)
3531 vector<pair<string,string> > const Buffer::getBibkeyList()
3533 /// if this is a child document and the parent is already loaded
3534 /// Use the parent's list instead [ale990412]
3535 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3536 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3538 return tmp->getBibkeyList();
3541 vector<pair<string, string> > keys;
3542 LyXParagraph * par = paragraph;
3545 keys.push_back(pair<string, string>(par->bibkey->getContents(),
3546 par->String(this, false)));
3550 // Might be either using bibtex or a child has bibliography
3552 for (inset_iterator it = inset_iterator_begin();
3553 it != inset_iterator_end(); ++it) {
3554 // Search for Bibtex or Include inset
3555 if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3556 vector<pair<string,string> > tmp =
3557 static_cast<InsetBibtex*>(*it)->getKeys(this);
3558 keys.insert(keys.end(), tmp.begin(), tmp.end());
3559 } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3560 vector<pair<string,string> > const tmp =
3561 static_cast<InsetInclude*>(*it)->getKeys();
3562 keys.insert(keys.end(), tmp.begin(), tmp.end());
3571 bool Buffer::isDepClean(string const & name) const
3573 DEPCLEAN * item = dep_clean;
3574 while (item && item->master != name)
3576 if (!item) return true;
3581 void Buffer::markDepClean(string const & name)
3584 dep_clean = new DEPCLEAN;
3585 dep_clean->clean = true;
3586 dep_clean->master = name;
3587 dep_clean->next = 0;
3589 DEPCLEAN * item = dep_clean;
3590 while (item && item->master != name)
3595 item = new DEPCLEAN;
3597 item->master = name;
3604 bool Buffer::Dispatch(string const & command)
3606 // Split command string into command and argument
3608 string line = frontStrip(command);
3609 string const arg = strip(frontStrip(split(line, cmd, ' ')));
3611 return Dispatch(lyxaction.LookupFunc(cmd), arg);
3615 bool Buffer::Dispatch(int action, string const & argument)
3617 bool dispatched = true;
3620 Exporter::Export(this, argument, false);
3630 void Buffer::resize()
3632 /// resize the BufferViews!
3638 void Buffer::resizeInsets(BufferView * bv)
3640 /// then remove all LyXText in text-insets
3641 LyXParagraph * par = paragraph;
3642 for (; par; par = par->next) {
3643 par->resizeInsetsLyXText(bv);
3647 void Buffer::ChangeLanguage(Language const * from, Language const * to)
3650 LyXParagraph * par = paragraph;
3652 par->ChangeLanguage(params, from, to);
3658 bool Buffer::isMultiLingual()
3660 LyXParagraph * par = paragraph;
3662 if (par->isMultiLingual(params))
3670 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
3671 LyXParagraph::size_type pos)
3674 it = par->InsetIterator(pos);
3675 if (it == par->inset_iterator_end()) {
3682 void Buffer::inset_iterator::SetParagraph()
3685 it = par->inset_iterator_begin();
3686 if (it != par->inset_iterator_end())
3691 // We maintain an invariant that whenever par = 0 then it = 0