1 /* This file is part of
2 * ======================================================
4 * LyX, The Document Processor
6 * Copyright 1995 Matthias Ettrich
7 * Copyright 1995-1999 The LyX Team.
9 * This file is Copyright 1996-1999
12 * ======================================================
17 // 23/03/98 Heinrich Bauer (heinrich.bauer@t-mobil.de)
18 // Spots marked "changed Heinrich Bauer, 23/03/98" modified due to the
19 // following bug: dvi file export did not work after printing (or previewing)
20 // and vice versa as long as the same file was concerned. This happened
21 // every time the LyX-file was left unchanged between the two actions mentioned
37 #include <sys/types.h>
41 #pragma implementation "buffer.h"
45 #include "bufferlist.h"
47 #include "lyx_gui_misc.h"
48 #include "LyXAction.h"
51 #include "tex-strings.h"
54 #include "minibuffer.h"
57 #include "mathed/formulamacro.h"
58 #include "insets/lyxinset.h"
59 #include "insets/inseterror.h"
60 #include "insets/insetlabel.h"
61 #include "insets/insetref.h"
62 #include "insets/inseturl.h"
63 #include "insets/insetinfo.h"
64 #include "insets/insetquotes.h"
65 #include "insets/insetlatexaccent.h"
66 #include "insets/insetbib.h"
67 #include "insets/insetindex.h"
68 #include "insets/insetinclude.h"
69 #include "insets/insettoc.h"
70 #include "insets/insetlof.h"
71 #include "insets/insetlot.h"
72 #include "insets/insetloa.h"
73 #include "insets/insetparent.h"
74 #include "insets/insetspecialchar.h"
75 #include "insets/figinset.h"
76 #include "insets/insettext.h"
77 #include "insets/insetert.h"
78 #include "insets/insetgraphics.h"
79 #include "insets/insetfoot.h"
80 #include "support/filetools.h"
81 #include "support/path.h"
87 #include "LaTeXFeatures.h"
88 #include "support/syscall.h"
89 #include "support/lyxlib.h"
90 #include "support/FileInfo.h"
94 // Uncomment this line to enable a workaround for the weird behaviour
95 // of the cursor between a displayed inset and last character
96 // at the upper line. (Alejandro 20.9.96)
97 // #define BREAK_BEFORE_INSET
99 /* Lars, when changing this file sometime in the future to a list,
100 * please check out the figinsets-sideeffects described at the
101 * beginning of figinset.C Matthias (04.07.1996)
105 // all these externs should eventually be removed.
106 extern BufferList bufferlist;
108 extern void MenuExport(Buffer *, string const &);
109 extern LyXAction lyxaction;
112 static const float LYX_FORMAT = 2.15;
114 extern int tex_code_break_column;
116 extern void FreeUpdateTimer();
119 Buffer::Buffer(string const & file, bool ronly)
121 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
123 filepath = OnlyPath(file);
127 dvi_clean_orgd = false; // Heinrich Bauer, 23/03/98
128 dvi_clean_tmpd = false; // Heinrich Bauer, 23/03/98
133 if (read_only || (lyxrc.use_tempdir)) {
134 tmppath = CreateBufferTmpDir();
135 } else tmppath.clear();
141 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142 // here the buffer should take care that it is
143 // saved properly, before it goes into the void.
145 // make sure that views using this buffer
150 if (!tmppath.empty()) {
151 DestroyBufferTmpDir(tmppath);
154 LyXParagraph * par = paragraph;
155 LyXParagraph * tmppar;
165 bool Buffer::saveParamsAsDefaults()
167 string fname = AddName(AddPath(user_lyxdir, "templates/"),
169 Buffer defaults = Buffer(fname);
171 // Use the current buffer's parameters as default
172 defaults.params = params;
174 // add an empty paragraph. Is this enough?
175 defaults.paragraph = new LyXParagraph;
177 return defaults.writeFile(defaults.filename, false);
181 /// Update window titles of all users
182 // Should work on a list
183 void Buffer::updateTitles() const
185 if (users) users->owner()->updateWindowTitle();
189 /// Reset autosave timer of all users
190 // Should work on a list
191 void Buffer::resetAutosaveTimers() const
193 if (users) users->owner()->resetAutosaveTimer();
197 void Buffer::fileName(string const & newfile)
199 filename = MakeAbsPath(newfile);
200 filepath = OnlyPath(filename);
201 setReadonly(IsFileWriteable(filename) == 0);
206 // candidate for move to BufferView
207 // (at least some parts in the beginning of the func)
210 // changed to be public and have one parameter
211 // if par = 0 normal behavior
212 // else insert behavior
213 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
214 #define USE_PARSE_FUNCTION 1
215 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
219 char depth = 0; // signed or unsigned?
220 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
221 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
222 bool the_end_read = false;
224 LyXParagraph * return_par = 0;
225 LyXFont font(LyXFont::ALL_INHERIT);
227 // If we are inserting, we cheat and get a token in advance
228 bool has_token = false;
232 par = new LyXParagraph;
234 users->text->BreakParagraph();
235 return_par = users->text->FirstParagraph();
238 // We don't want to adopt the parameters from the
239 // document we insert, so we skip until the text begins:
242 pretoken = lex.GetString();
243 if (pretoken == "\\layout") {
255 pretoken = lex.GetString();
258 // Profiling show this should give a lot: (Asger)
259 string const token = pretoken;
263 the_end_read = parseSingleLyXformat2Token(lex, par, return_par,
272 paragraph = return_par;
278 bool Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
279 LyXParagraph *& return_par,
280 const string & token, int & pos,
281 char & depth, LyXFont & font,
282 LyXParagraph::footnote_flag & footnoteflag,
283 LyXParagraph::footnote_kind & footnotekind)
288 bool the_end_read = false;
290 if (token[0] != '\\') {
291 int n = token.length();
292 for (int i = 0; i < n; ++i) {
293 par->InsertChar(pos, token[i]);
294 par->SetFont(pos, font);
297 } else if (token == "\\i") {
298 inset = new InsetLatexAccent;
300 par->InsertChar(pos, LyXParagraph::META_INSET);
302 par->InsertInset(pos, inset);
303 par->SetFont(pos, font);
305 } else if (token == "\\layout") {
309 par->text.resize(par->text.size());
310 par = new LyXParagraph(par);
314 string layoutname = lex.GetString();
315 pair<bool, LyXTextClass::LayoutList::size_type> pp
316 = textclasslist.NumberOfLayout(params.textclass,
319 par->layout = pp.second;
320 } else { // layout not found
321 // use default layout "Standard" (0)
324 // Test whether the layout is obsolete.
325 LyXLayout const & layout =
326 textclasslist.Style(params.textclass,
328 if (!layout.obsoleted_by().empty())
330 textclasslist.NumberOfLayout(params.textclass,
331 layout.obsoleted_by()).second;
332 par->footnoteflag = footnoteflag;
333 par->footnotekind = footnotekind;
335 font = LyXFont(LyXFont::ALL_INHERIT);
336 } else if (token == "\\end_float") {
340 par->text.resize(par->text.size());
341 par = new LyXParagraph(par);
343 footnotekind = LyXParagraph::FOOTNOTE;
344 footnoteflag = LyXParagraph::NO_FOOTNOTE;
347 par->layout = LYX_DUMMY_LAYOUT;
348 font = LyXFont(LyXFont::ALL_INHERIT);
349 } else if (token == "\\begin_float") {
350 tmpret = lex.FindToken(string_footnotekinds);
351 if (tmpret == -1) ++tmpret;
352 if (tmpret != LYX_LAYOUT_DEFAULT)
353 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
354 if (footnotekind == LyXParagraph::FOOTNOTE
355 || footnotekind == LyXParagraph::MARGIN)
356 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
358 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
359 } else if (token == "\\begin_deeper") {
361 } else if (token == "\\end_deeper") {
363 lex.printError("\\end_deeper: "
364 "depth is already null");
368 } else if (token == "\\begin_preamble") {
369 params.readPreamble(lex);
370 } else if (token == "\\textclass") {
372 pair<bool, LyXTextClassList::size_type> pp =
373 textclasslist.NumberOfClass(lex.GetString());
375 params.textclass = pp.second;
377 lex.printError("Unknown textclass `$$Token'");
378 params.textclass = 0;
380 if (!textclasslist.Load(params.textclass)) {
381 // if the textclass wasn't loaded properly
382 // we need to either substitute another
383 // or stop loading the file.
384 // I can substitute but I don't see how I can
385 // stop loading... ideas?? ARRae980418
386 WriteAlert(_("Textclass Loading Error!"),
387 string(_("Can't load textclass ")) +
388 textclasslist.NameOfClass(params.textclass),
389 _("-- substituting default"));
390 params.textclass = 0;
392 } else if (token == "\\options") {
394 params.options = lex.GetString();
395 } else if (token == "\\language") {
396 params.readLanguage(lex);
397 } else if (token == "\\fontencoding") {
399 } else if (token == "\\inputencoding") {
401 params.inputenc = lex.GetString();
402 } else if (token == "\\graphics") {
403 params.readGraphicsDriver(lex);
404 } else if (token == "\\fontscheme") {
406 params.fonts = lex.GetString();
407 } else if (token == "\\noindent") {
408 par->noindent = true;
409 } else if (token == "\\fill_top") {
410 par->added_space_top = VSpace(VSpace::VFILL);
411 } else if (token == "\\fill_bottom") {
412 par->added_space_bottom = VSpace(VSpace::VFILL);
413 } else if (token == "\\line_top") {
414 par->line_top = true;
415 } else if (token == "\\line_bottom") {
416 par->line_bottom = true;
417 } else if (token == "\\pagebreak_top") {
418 par->pagebreak_top = true;
419 } else if (token == "\\pagebreak_bottom") {
420 par->pagebreak_bottom = true;
421 } else if (token == "\\start_of_appendix") {
422 par->start_of_appendix = true;
423 } else if (token == "\\paragraph_separation") {
424 tmpret = lex.FindToken(string_paragraph_separation);
425 if (tmpret == -1) ++tmpret;
426 if (tmpret != LYX_LAYOUT_DEFAULT)
427 params.paragraph_separation =
428 static_cast<BufferParams::PARSEP>(tmpret);
429 } else if (token == "\\defskip") {
431 params.defskip = VSpace(lex.GetString());
433 } else if (token == "\\no_isolatin1") { // obsolete
435 } else if (token == "\\no_babel") { // obsolete
437 } else if (token == "\\no_epsfig") { // obsolete
440 } else if (token == "\\epsfig") { // obsolete
441 // Indeed it is obsolete, but we HAVE to be backwards
442 // compatible until 0.14, because otherwise all figures
443 // in existing documents are irretrivably lost. (Asger)
444 params.readGraphicsDriver(lex);
445 } else if (token == "\\quotes_language") {
446 tmpret = lex.FindToken(string_quotes_language);
447 if (tmpret == -1) ++tmpret;
448 if (tmpret != LYX_LAYOUT_DEFAULT) {
449 InsetQuotes::quote_language tmpl =
450 InsetQuotes::EnglishQ;
453 tmpl = InsetQuotes::EnglishQ;
456 tmpl = InsetQuotes::SwedishQ;
459 tmpl = InsetQuotes::GermanQ;
462 tmpl = InsetQuotes::PolishQ;
465 tmpl = InsetQuotes::FrenchQ;
468 tmpl = InsetQuotes::DanishQ;
471 params.quotes_language = tmpl;
473 } else if (token == "\\quotes_times") {
475 switch(lex.GetInteger()) {
477 params.quotes_times = InsetQuotes::SingleQ;
480 params.quotes_times = InsetQuotes::DoubleQ;
483 } else if (token == "\\papersize") {
484 tmpret = lex.FindToken(string_papersize);
488 params.papersize2 = tmpret;
489 } else if (token == "\\paperpackage") {
490 tmpret = lex.FindToken(string_paperpackages);
493 params.paperpackage = BufferParams::PACKAGE_NONE;
495 params.paperpackage = tmpret;
496 } else if (token == "\\use_geometry") {
498 params.use_geometry = lex.GetInteger();
499 } else if (token == "\\use_amsmath") {
501 params.use_amsmath = lex.GetInteger();
502 } else if (token == "\\paperorientation") {
503 tmpret = lex.FindToken(string_orientation);
504 if (tmpret == -1) ++tmpret;
505 if (tmpret != LYX_LAYOUT_DEFAULT)
506 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
507 } else if (token == "\\paperwidth") {
509 params.paperwidth = lex.GetString();
510 } else if (token == "\\paperheight") {
512 params.paperheight = lex.GetString();
513 } else if (token == "\\leftmargin") {
515 params.leftmargin = lex.GetString();
516 } else if (token == "\\topmargin") {
518 params.topmargin = lex.GetString();
519 } else if (token == "\\rightmargin") {
521 params.rightmargin = lex.GetString();
522 } else if (token == "\\bottommargin") {
524 params.bottommargin = lex.GetString();
525 } else if (token == "\\headheight") {
527 params.headheight = lex.GetString();
528 } else if (token == "\\headsep") {
530 params.headsep = lex.GetString();
531 } else if (token == "\\footskip") {
533 params.footskip = lex.GetString();
534 } else if (token == "\\paperfontsize") {
536 params.fontsize = strip(lex.GetString());
537 } else if (token == "\\papercolumns") {
539 params.columns = lex.GetInteger();
540 } else if (token == "\\papersides") {
542 switch(lex.GetInteger()) {
544 case 1: params.sides = LyXTextClass::OneSide; break;
545 case 2: params.sides = LyXTextClass::TwoSides; break;
547 } else if (token == "\\paperpagestyle") {
549 params.pagestyle = strip(lex.GetString());
550 } else if (token == "\\bullet") {
552 int index = lex.GetInteger();
554 int temp_int = lex.GetInteger();
555 params.user_defined_bullets[index].setFont(temp_int);
556 params.temp_bullets[index].setFont(temp_int);
558 temp_int = lex.GetInteger();
559 params.user_defined_bullets[index].setCharacter(temp_int);
560 params.temp_bullets[index].setCharacter(temp_int);
562 temp_int = lex.GetInteger();
563 params.user_defined_bullets[index].setSize(temp_int);
564 params.temp_bullets[index].setSize(temp_int);
566 string temp_str = lex.GetString();
567 if (temp_str != "\\end_bullet") {
568 // this element isn't really necessary for
569 // parsing but is easier for humans
570 // to understand bullets. Put it back and
571 // set a debug message?
572 lex.printError("\\end_bullet expected, got" + temp_str);
573 //how can I put it back?
575 } else if (token == "\\bulletLaTeX") {
577 int index = lex.GetInteger();
579 string temp_str = lex.GetString(), sum_str;
580 while (temp_str != "\\end_bullet") {
581 // this loop structure is needed when user
582 // enters an empty string since the first
583 // thing returned will be the \\end_bullet
585 // if the LaTeX entry has spaces. Each element
586 // therefore needs to be read in turn
589 temp_str = lex.GetString();
591 params.user_defined_bullets[index].setText(sum_str);
592 params.temp_bullets[index].setText(sum_str);
593 } else if (token == "\\secnumdepth") {
595 params.secnumdepth = lex.GetInteger();
596 } else if (token == "\\tocdepth") {
598 params.tocdepth = lex.GetInteger();
599 } else if (token == "\\baselinestretch") { // obsolete
600 lex.nextToken(); // should not be used directly
602 // Will probably keep a kind of support just for
604 params.spacing.set(Spacing::Other, lex.GetFloat());
605 } else if (token == "\\spacing") {
607 string tmp = strip(lex.GetString());
608 if (tmp == "single") {
609 params.spacing.set(Spacing::Single);
610 } else if (tmp == "onehalf") {
611 params.spacing.set(Spacing::Onehalf);
612 } else if (tmp == "double") {
613 params.spacing.set(Spacing::Double);
614 } else if (tmp == "other") {
616 params.spacing.set(Spacing::Other,
619 lex.printError("Unknown spacing token: '$$Token'");
621 } else if (token == "\\float_placement") {
623 params.float_placement = lex.GetString();
624 } else if (token == "\\cursor") { // obsolete
625 // this is obsolete, so we just skip it.
627 } else if (token == "\\family") {
629 font.setLyXFamily(lex.GetString());
630 } else if (token == "\\series") {
632 font.setLyXSeries(lex.GetString());
633 } else if (token == "\\shape") {
635 font.setLyXShape(lex.GetString());
636 } else if (token == "\\size") {
638 font.setLyXSize(lex.GetString());
639 } else if (token == "\\latex") {
641 string tok = lex.GetString();
642 // This is dirty, but gone with LyX3. (Asger)
643 if (tok == "no_latex")
644 font.setLatex(LyXFont::OFF);
645 else if (tok == "latex")
646 font.setLatex(LyXFont::ON);
647 else if (tok == "default")
648 font.setLatex(LyXFont::INHERIT);
650 lex.printError("Unknown LaTeX font flag "
652 } else if (token == "\\direction") {
654 string tok = lex.GetString();
656 font.setDirection(LyXFont::LTR_DIR);
657 else if (tok == "rtl")
658 font.setDirection(LyXFont::RTL_DIR);
659 else if (tok == "default")
660 font.setDirection(LyXFont::INHERIT_DIR);
662 lex.printError("Unknown font flag "
664 } else if (token == "\\emph") {
666 font.setEmph(font.setLyXMisc(lex.GetString()));
667 } else if (token == "\\bar") {
669 string tok = lex.GetString();
670 // This is dirty, but gone with LyX3. (Asger)
672 font.setUnderbar(LyXFont::ON);
673 else if (tok == "no")
674 font.setUnderbar(LyXFont::OFF);
675 else if (tok == "default")
676 font.setUnderbar(LyXFont::INHERIT);
678 lex.printError("Unknown bar font flag "
680 } else if (token == "\\noun") {
682 font.setNoun(font.setLyXMisc(lex.GetString()));
683 } else if (token == "\\color") {
685 font.setLyXColor(lex.GetString());
686 } else if (token == "\\align") {
687 tmpret = lex.FindToken(string_align);
688 if (tmpret == -1) ++tmpret;
689 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
691 for (; tmpret > 0; --tmpret)
692 tmpret2 = tmpret2 * 2;
693 par->align = LyXAlignment(tmpret2);
695 } else if (token == "\\added_space_top") {
697 par->added_space_top = lex.GetString();
698 } else if (token == "\\added_space_bottom") {
700 par->added_space_bottom = lex.GetString();
701 } else if (token == "\\pextra_type") {
703 par->pextra_type = lex.GetInteger();
704 } else if (token == "\\pextra_width") {
706 par->pextra_width = lex.GetString();
707 } else if (token == "\\pextra_widthp") {
709 par->pextra_widthp = lex.GetString();
710 } else if (token == "\\pextra_alignment") {
712 par->pextra_alignment = lex.GetInteger();
713 } else if (token == "\\pextra_hfill") {
715 par->pextra_hfill = lex.GetInteger();
716 } else if (token == "\\pextra_start_minipage") {
718 par->pextra_start_minipage = lex.GetInteger();
719 } else if (token == "\\labelwidthstring") {
721 par->labelwidthstring = lex.GetString();
722 /* do not delete this token, it is still needed! */
723 } else if (token == "\\end_inset") {
724 /* simple ignore this. The insets do not have
726 // but insets should read it, it is a part of
727 //the inset isn't it? Lgb.
728 } else if (token == "\\begin_inset") {
730 tmptok = lex.GetString();
731 /* test the different insets */
732 if (tmptok == "Quotes") {
733 inset = new InsetQuotes;
735 par->InsertChar(pos, LyXParagraph::META_INSET);
736 par->InsertInset(pos, inset);
737 par->SetFont(pos, font);
739 } else if (tmptok == "\\i") {
740 inset = new InsetLatexAccent;
742 par->InsertChar(pos, LyXParagraph::META_INSET);
743 par->InsertInset(pos, inset);
744 par->SetFont(pos, font);
746 } else if (tmptok == "FormulaMacro") {
747 inset = new InsetFormulaMacro;
749 par->InsertChar(pos, LyXParagraph::META_INSET);
750 par->InsertInset(pos, inset);
751 par->SetFont(pos, font);
753 } else if (tmptok == "Formula") {
754 inset = new InsetFormula;
756 par->InsertChar(pos, LyXParagraph::META_INSET);
757 par->InsertInset(pos, inset);
758 par->SetFont(pos, font);
760 } else if (tmptok == "Figure") {
761 inset = new InsetFig(100, 100, this);
763 par->InsertChar(pos, LyXParagraph::META_INSET);
764 par->InsertInset(pos, inset);
765 par->SetFont(pos, font);
767 } else if (tmptok == "Info") {
768 inset = new InsetInfo;
770 par->InsertChar(pos, LyXParagraph::META_INSET);
771 par->InsertInset(pos, inset);
772 par->SetFont(pos, font);
774 } else if (tmptok == "Include") {
775 inset = new InsetInclude(string(), this);
777 par->InsertChar(pos, LyXParagraph::META_INSET);
778 par->InsertInset(pos, inset);
779 par->SetFont(pos, font);
781 } else if (tmptok == "ERT") {
782 inset = new InsetERT(this);
784 par->InsertChar(pos, LyXParagraph::META_INSET);
785 par->InsertInset(pos, inset);
786 par->SetFont(pos, font);
788 } else if (tmptok == "Text") {
789 inset = new InsetText(this);
791 par->InsertChar(pos, LyXParagraph::META_INSET);
792 par->InsertInset(pos, inset);
793 par->SetFont(pos, font);
795 } else if (tmptok == "Foot") {
796 inset = new InsetFoot(this);
798 par->InsertChar(pos, LyXParagraph::META_INSET);
799 par->InsertInset(pos, inset);
800 par->SetFont(pos, font);
802 } else if (tmptok == "GRAPHICS") {
803 inset = new InsetGraphics;
805 par->InsertChar(pos, LyXParagraph::META_INSET);
806 par->InsertInset(pos, inset);
807 par->SetFont(pos, font);
808 } else if (tmptok == "LatexCommand") {
811 if (inscmd.getCmdName() == "cite") {
812 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
813 } else if (inscmd.getCmdName() == "bibitem") {
814 lex.printError("Wrong place for bibitem");
815 inset = inscmd.Clone();
816 } else if (inscmd.getCmdName() == "BibTeX") {
817 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
818 } else if (inscmd.getCmdName() == "index") {
819 inset = new InsetIndex(inscmd.getContents());
820 } else if (inscmd.getCmdName() == "include") {
821 inset = new InsetInclude(inscmd.getContents(), this);
822 } else if (inscmd.getCmdName() == "label") {
823 inset = new InsetLabel(inscmd.getCommand());
824 } else if (inscmd.getCmdName() == "url"
825 || inscmd.getCmdName() == "htmlurl") {
826 inset = new InsetUrl(inscmd.getCommand());
827 } else if (inscmd.getCmdName() == "ref"
828 || inscmd.getCmdName() == "pageref") {
829 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
830 inset = new InsetRef(inscmd, this);
832 #warning Verify that this else clause is still needed. (Lgb)
834 // This condition comes from a
835 // temporary solution to the latexdel
836 // ref inset that was transformed to
837 // an empty ref inset plus the body
838 // surronded by latexdel insets
840 string cont, opt, tmptmptok, cmdname;
842 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
847 tmptmptok = lex.GetString();
848 if(tmptmptok[0] == '\\') {
849 if( tmptmptok == "\\backslash")
859 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
864 tmptmptok = lex.GetString();
865 if(tmptmptok[0] == '\\') {
866 if( tmptmptok == "\\backslash")
876 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
882 cmdname = "\\" + inscmd.getCmdName();
883 cmdname += "[" + cont + "]";
884 cmdname += "{" + opt + "}";
885 inset = new InsetRef(cmdname, this);
888 } else if (inscmd.getCmdName() == "tableofcontents") {
889 inset = new InsetTOC(this);
890 } else if (inscmd.getCmdName() == "listoffigures") {
891 inset = new InsetLOF(this);
892 } else if (inscmd.getCmdName() == "listofalgorithms") {
893 inset = new InsetLOA(this);
894 } else if (inscmd.getCmdName() == "listoftables") {
895 inset = new InsetLOT(this);
896 } else if (inscmd.getCmdName() == "printindex") {
897 inset = new InsetPrintIndex(this);
898 } else if (inscmd.getCmdName() == "lyxparent") {
899 inset = new InsetParent(inscmd.getContents(), this);
903 par->InsertChar(pos, LyXParagraph::META_INSET);
904 par->InsertInset(pos, inset);
905 par->SetFont(pos, font);
909 } else if (token == "\\InsetQuotes") {
910 inset = new InsetQuotes;
912 par->InsertChar(pos, LyXParagraph::META_INSET);
913 par->InsertInset(pos, inset);
914 par->SetFont(pos, font);
916 } else if (token == "\\InsetFormula") {
917 inset = new InsetFormula;
919 par->InsertChar(pos, LyXParagraph::META_INSET);
920 par->InsertInset(pos, inset);
921 par->SetFont(pos, font);
923 } else if (token == "\\SpecialChar") {
924 LyXLayout const & layout =
925 textclasslist.Style(params.textclass,
928 // Insets don't make sense in a free-spacing context! ---Kayvan
929 if (layout.free_spacing)
934 next_token = lex.GetString();
935 if (next_token == "\\-") {
936 par->InsertChar(pos, '-');
937 par->SetFont(pos, font);
938 } else if (next_token == "\\protected_separator") {
939 par->InsertChar(pos, ' ');
940 par->SetFont(pos, font);
942 lex.printError("Token `$$Token' "
944 "paragraph layout!");
951 inset = new InsetSpecialChar;
953 par->InsertChar(pos, LyXParagraph::META_INSET);
954 par->InsertInset(pos, inset);
955 par->SetFont(pos, font);
958 } else if (token == "\\Figure") {
959 inset = new InsetFig(100, 100, this);
961 par->InsertChar(pos, LyXParagraph::META_INSET);
962 par->InsertInset(pos, inset);
963 par->SetFont(pos, font);
965 } else if (token == "\\newline") { // soon obsolete
967 par->InsertChar(pos, LyXParagraph::META_NEWLINE);
968 par->SetFont(pos, font);
970 inset = new InsetSpecialChar(InsetSpecialChar::NEWLINE);
971 par->InsertChar(pos, LyXParagraph::META_INSET);
972 par->InsertInset(pos, inset);
973 par->SetFont(pos, font);
976 } else if (token == "\\LyXTable") {
977 par->table = new LyXTable(lex);
978 } else if (token == "\\hfill") {
979 par->InsertChar(pos, LyXParagraph::META_HFILL);
980 par->SetFont(pos, font);
982 } else if (token == "\\protected_separator") { // obsolete
984 LyXLayout const & layout =
985 textclasslist.Style(params.textclass,
988 if (layout.free_spacing) {
989 par->InsertChar(pos, ' ');
990 par->SetFont(pos, font);
992 inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
993 par->InsertChar(pos, LyXParagraph::META_INSET);
994 par->InsertInset(pos, inset);
995 par->SetFont(pos, font);
998 par->InsertChar(pos, LyXParagraph::META_PROTECTED_SEPARATOR);
999 par->SetFont(pos, font);
1002 } else if (token == "\\bibitem") { // ale970302
1004 par->bibkey = new InsetBibKey;
1005 par->bibkey->Read(lex);
1006 }else if (token == "\\backslash") {
1007 par->InsertChar(pos, '\\');
1008 par->SetFont(pos, font);
1010 }else if (token == "\\the_end") {
1011 the_end_read = true;
1013 // This should be insurance for the future: (Asger)
1014 lex.printError("Unknown token `$$Token'. "
1015 "Inserting as text.");
1016 int n = token.length();
1017 for (int i = 0; i < n; ++i) {
1018 par->InsertChar(pos, token[i]);
1019 par->SetFont(pos, font);
1023 return the_end_read;
1026 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1032 token = lex.GetString();
1033 if (token == "\\lyxformat") { // the first token _must_ be...
1035 format = lex.GetFloat();
1037 if (LYX_FORMAT - format > 0.05) {
1038 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1039 LYX_FORMAT, format);
1041 if (format - LYX_FORMAT > 0.05) {
1042 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1043 LYX_FORMAT, format);
1045 bool the_end = readLyXformat2(lex, par);
1046 // Formats >= 2.13 support "\the_end" marker
1053 WriteAlert(_("Warning!"),
1054 _("Reading of document is not complete"),
1055 _("Maybe the document is truncated"));
1056 // We simulate a safe reading anyways to allow
1057 // users to take the chance... (Asger)
1061 WriteAlert(_("ERROR!"),
1062 _("Old LyX file format found. "
1063 "Use LyX 0.10.x to read this!"));
1067 } else { // "\\lyxformat" not found
1068 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1071 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1077 // Should probably be moved to somewhere else: BufferView? LyXView?
1078 bool Buffer::save(bool makeBackup) const
1080 // We don't need autosaves in the immediate future. (Asger)
1081 resetAutosaveTimers();
1085 string s = fileName() + '~';
1086 // Rename is the wrong way of making a backup,
1087 // this is the correct way.
1088 /* truss cp fil fil2:
1089 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1090 stat("LyXVC.lyx", 0xEFFFF688) = 0
1091 open("LyXVC.lyx", O_RDONLY) = 3
1092 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1093 fstat(4, 0xEFFFF508) = 0
1094 fstat(3, 0xEFFFF508) = 0
1095 read(3, " # T h i s f i l e w".., 8192) = 5579
1096 write(4, " # T h i s f i l e w".., 5579) = 5579
1097 read(3, 0xEFFFD4A0, 8192) = 0
1100 chmod("LyXVC3.lyx", 0100644) = 0
1101 lseek(0, 0, SEEK_CUR) = 46440
1105 // Should proabaly have some more error checking here.
1106 // Should be cleaned up in 0.13, at least a bit.
1107 // Doing it this way, also makes the inodes stay the same.
1108 // This is still not a very good solution, in particular we
1109 // might loose the owner of the backup.
1110 FileInfo finfo(fileName());
1111 if (finfo.exist()) {
1112 mode_t fmode = finfo.getMode();
1113 struct utimbuf * times = new struct utimbuf;
1115 times->actime = finfo.getAccessTime();
1116 times->modtime = finfo.getModificationTime();
1117 ifstream ifs(fileName().c_str());
1118 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1123 ::chmod(s.c_str(), fmode);
1125 if (::utime(s.c_str(), times)) {
1126 lyxerr << "utime error." << endl;
1129 lyxerr << "LyX was not able to make "
1130 "backupcopy. Beware." << endl;
1136 if (writeFile(fileName(), false)) {
1139 // now delete the autosavefile
1140 string a = OnlyPath(fileName());
1142 a += OnlyFilename(fileName());
1144 FileInfo fileinfo(a);
1145 if (fileinfo.exist()) {
1146 if (::remove(a.c_str()) != 0) {
1147 WriteFSAlert(_("Could not delete "
1148 "auto-save file!"), a);
1152 // Saving failed, so backup is not backup
1154 string s = fileName() + '~';
1155 ::rename(s.c_str(), fileName().c_str());
1163 // Returns false if unsuccesful
1164 bool Buffer::writeFile(string const & fname, bool flag) const
1166 // if flag is false writeFile will not create any GUI
1167 // warnings, only cerr.
1168 // Needed for autosave in background or panic save (Matthias 120496)
1170 if (read_only && (fname == filename)) {
1171 // Here we should come with a question if we should
1172 // perform the write anyway.
1174 lyxerr << _("Error! Document is read-only: ")
1177 WriteAlert(_("Error! Document is read-only: "),
1182 FileInfo finfo(fname);
1183 if (finfo.exist() && !finfo.writable()) {
1184 // Here we should come with a question if we should
1185 // try to do the save anyway. (i.e. do a chmod first)
1187 lyxerr << _("Error! Cannot write file: ")
1190 WriteFSAlert(_("Error! Cannot write file: "),
1195 ofstream ofs(fname.c_str());
1198 lyxerr << _("Error! Cannot open file: ")
1201 WriteFSAlert(_("Error! Cannot open file: "),
1205 // The top of the file should not be written by params.
1207 // write out a comment in the top of the file
1208 ofs << '#' << LYX_DOCVERSION
1209 << " created this file. For more info see http://www.lyx.org/\n";
1210 ofs.setf(ios::showpoint|ios::fixed);
1212 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1214 // now write out the buffer paramters.
1215 params.writeFile(ofs);
1217 char footnoteflag = 0;
1220 // this will write out all the paragraphs
1221 // using recursive descent.
1222 paragraph->writeFile(ofs, params, footnoteflag, depth);
1224 // Write marker that shows file is complete
1225 ofs << "\n\\the_end" << endl;
1227 // how to check if close went ok?
1232 void Buffer::writeFileAscii(string const & fname, int linelen)
1234 LyXFont font1, font2;
1236 char c, footnoteflag = 0, depth = 0;
1238 LyXParagraph::size_type i;
1239 int j, h, ltype = 0, ltype_depth = 0,
1240 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1243 bool ref_printed = false;
1245 ofstream ofs(fname.c_str());
1247 WriteFSAlert(_("Error: Cannot write file:"), fname);
1251 string fname1 = TmpFileName();
1252 LyXParagraph * par = paragraph;
1256 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1258 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1260 /* begins a footnote environment ? */
1261 if (footnoteflag != par->footnoteflag) {
1262 footnoteflag = par->footnoteflag;
1264 j = strlen(string_footnotekinds[par->footnotekind])+4;
1265 if (currlinelen + j > linelen)
1268 << string_footnotekinds[par->footnotekind] << "] ";
1273 /* begins or ends a deeper area ?*/
1274 if (depth != par->depth) {
1275 if (par->depth > depth) {
1276 while (par->depth > depth) {
1281 while (par->depth < depth) {
1287 /* First write the layout */
1288 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1289 if (tmp == "Itemize") {
1291 ltype_depth = depth+1;
1292 } else if (tmp == "Enumerate") {
1294 ltype_depth = depth+1;
1295 } else if (strstr(tmp.c_str(), "ection")) {
1297 ltype_depth = depth+1;
1298 } else if (strstr(tmp.c_str(), "aragraph")) {
1300 ltype_depth = depth+1;
1301 } else if (tmp == "Description") {
1303 ltype_depth = depth+1;
1304 } else if (tmp == "Abstract") {
1307 } else if (tmp == "Bibliography") {
1315 /* maybe some vertical spaces */
1317 /* the labelwidthstring used in lists */
1321 /* some pagebreaks? */
1325 /* what about the alignment */
1328 /* dummy layout, that means a footnote ended */
1329 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1334 LyXLayout const & layout =
1335 textclasslist.Style(params.textclass,
1337 bool free_spc = layout.free_spacing;
1339 /* It might be a table */
1342 if (!lyxrc.ascii_roff_command.empty() &&
1343 lyxrc.ascii_roff_command != "none") {
1344 RoffAsciiTable(ofs, par);
1351 cells = par->table->columns;
1352 clen = new int [cells];
1353 memset(clen, 0, sizeof(int) * cells);
1355 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1356 c = par->GetChar(i);
1357 if (c == LyXParagraph::META_INSET) {
1358 if ((inset = par->GetInset(i))) {
1362 inset->Latex(ost, -1, free_spc);
1363 h += ost.str().length();
1366 inset->Latex(ost, -1, free_spc);
1368 char * tmp = ost.str();
1374 ofstream fs(fname1.c_str());
1376 WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1379 inset->Latex(fs, -1, free_spc);
1380 h += fs.tellp() - 1;
1381 ::remove(fname1.c_str());
1384 } else if (c == LyXParagraph::META_NEWLINE) {
1388 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1396 font1 = LyXFont(LyXFont::ALL_INHERIT);
1398 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1399 if (!i && !footnoteflag && !noparbreak){
1401 for(j = 0; j < depth; ++j)
1403 currlinelen = depth * 2;
1405 case 0: /* Standard */
1406 case 4: /* (Sub)Paragraph */
1407 case 5: /* Description */
1409 case 6: /* Abstract */
1410 ofs << "Abstract\n\n";
1412 case 7: /* Bibliography */
1414 ofs << "References\n\n";
1419 ofs << par->labelstring << " ";
1422 if (ltype_depth > depth) {
1423 for(j = ltype_depth - 1; j > depth; --j)
1425 currlinelen += (ltype_depth-depth)*2;
1428 for(j = 0; j < cells; ++j) {
1430 for(h = 0; h < (clen[j] + 1);
1435 for(j = 0; j < depth; ++j)
1437 currlinelen = depth * 2;
1438 if (ltype_depth > depth) {
1439 for(j = ltype_depth;
1442 currlinelen += (ltype_depth-depth)*2;
1447 font2 = par->GetFontSettings(i);
1448 if (font1.latex() != font2.latex()) {
1449 if (font2.latex() == LyXFont::OFF)
1457 c = par->GetChar(i);
1461 case LyXParagraph::META_INSET:
1462 if ((inset = par->GetInset(i))) {
1464 inset->Latex(ofs, -1, free_spc);
1465 currlinelen += (ofs.tellp() - fpos);
1466 actpos += (ofs.tellp() - fpos) - 1;
1469 case LyXParagraph::META_NEWLINE:
1471 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1472 for(j = actpos; j < clen[cell - 1]; ++j)
1475 for(j = 0; j < depth; ++j)
1477 currlinelen = depth*2;
1478 if (ltype_depth > depth) {
1479 for(j = ltype_depth; j > depth; --j)
1481 currlinelen += (ltype_depth-depth) * 2;
1483 for(j = 0; j < cells; ++j) {
1485 for(h = 0; h < (clen[j] + 1); ++h)
1489 for(j = 0; j < depth; ++j)
1491 currlinelen = depth * 2;
1492 if (ltype_depth > depth) {
1493 for(j = ltype_depth;
1496 currlinelen += (ltype_depth-depth)*2;
1502 j < clen[cell - 1]; ++j)
1508 currlinelen = actpos = 0;
1511 for(j = 0; j < depth; ++j)
1513 currlinelen = depth * 2;
1514 if (ltype_depth > depth) {
1515 for(j = ltype_depth;
1518 currlinelen += (ltype_depth - depth) * 2;
1522 case LyXParagraph::META_HFILL:
1526 case LyXParagraph::META_PROTECTED_SEPARATOR:
1534 if (currlinelen > linelen - 10
1535 && c == ' ' && i + 2 < par->size()) {
1537 for(j = 0; j < depth; ++j)
1539 currlinelen = depth * 2;
1540 if (ltype_depth > depth) {
1541 for(j = ltype_depth;
1544 currlinelen += (ltype_depth-depth)*2;
1546 } else if (c != '\0')
1549 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1555 for(j = actpos; j < clen[cell - 1]; ++j)
1558 for(j = 0; j < depth; ++j)
1560 currlinelen = depth * 2;
1561 if (ltype_depth > depth) {
1562 for(j = ltype_depth; j > depth; --j)
1564 currlinelen += (ltype_depth - depth) * 2;
1566 for(j = 0; j < cells; ++j) {
1568 for(h = 0; h < (clen[j] + 1); ++h)
1581 void Buffer::makeLaTeXFile(string const & fname,
1582 string const & original_path,
1583 bool nice, bool only_body)
1585 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1587 niceFile = nice; // this will be used by Insetincludes.
1589 tex_code_break_column = lyxrc.ascii_linelen;
1591 LyXTextClass const & tclass =
1592 textclasslist.TextClass(params.textclass);
1594 ofstream ofs(fname.c_str());
1596 WriteFSAlert(_("Error: Cannot open file: "), fname);
1600 // validate the buffer.
1601 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1602 LaTeXFeatures features(tclass.numLayouts());
1604 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1607 // The starting paragraph of the coming rows is the
1608 // first paragraph of the document. (Asger)
1609 texrow.start(paragraph, 0);
1611 if (!only_body && nice) {
1612 ofs << "%% " LYX_DOCVERSION " created this file. "
1613 "For more info, see http://www.lyx.org/.\n"
1614 "%% Do not edit unless you really know what "
1619 lyxerr.debug() << "lyx header finished" << endl;
1620 // There are a few differences between nice LaTeX and usual files:
1621 // usual is \batchmode and has a
1622 // special input@path to allow the including of figures
1623 // with either \input or \includegraphics (what figinsets do).
1624 // batchmode is not set if there is a tex_code_break_column.
1625 // In this case somebody is interested in the generated LaTeX,
1626 // so this is OK. input@path is set when the actual parameter
1627 // original_path is set. This is done for usual tex-file, but not
1628 // for nice-latex-file. (Matthias 250696)
1631 // code for usual, NOT nice-latex-file
1632 ofs << "\\batchmode\n"; // changed
1633 // from \nonstopmode
1636 if (!original_path.empty()) {
1637 ofs << "\\makeatletter\n"
1638 << "\\def\\input@path{{"
1639 << original_path << "/}}\n"
1640 << "\\makeatother\n";
1646 ofs << "\\documentclass";
1648 string options; // the document class options.
1650 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1651 // only write if existing in list (and not default)
1652 options += params.fontsize;
1657 if (!params.use_geometry &&
1658 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1659 switch (params.papersize) {
1660 case BufferParams::PAPER_A4PAPER:
1661 options += "a4paper,";
1663 case BufferParams::PAPER_USLETTER:
1664 options += "letterpaper,";
1666 case BufferParams::PAPER_A5PAPER:
1667 options += "a5paper,";
1669 case BufferParams::PAPER_B5PAPER:
1670 options += "b5paper,";
1672 case BufferParams::PAPER_EXECUTIVEPAPER:
1673 options += "executivepaper,";
1675 case BufferParams::PAPER_LEGALPAPER:
1676 options += "legalpaper,";
1682 if (params.sides != tclass.sides()) {
1683 switch (params.sides) {
1684 case LyXTextClass::OneSide:
1685 options += "oneside,";
1687 case LyXTextClass::TwoSides:
1688 options += "twoside,";
1695 if (params.columns != tclass.columns()) {
1696 if (params.columns == 2)
1697 options += "twocolumn,";
1699 options += "onecolumn,";
1702 if (!params.use_geometry
1703 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1704 options += "landscape,";
1706 // language should be a parameter to \documentclass
1707 if (params.language != "default") {
1708 if (params.language == "hebrew")
1709 options += "english,";
1710 else if (lyxrc.rtl_support)
1711 options += "hebrew,";
1712 options += params.language + ',';
1715 // the user-defined options
1716 if (!params.options.empty()) {
1717 options += params.options + ',';
1720 if (!options.empty()){
1721 options = strip(options, ',');
1722 ofs << '[' << options << ']';
1726 << textclasslist.LatexnameOfClass(params.textclass)
1729 // end of \documentclass defs
1731 // font selection must be done before loading fontenc.sty
1732 if (params.fonts != "default") {
1733 ofs << "\\usepackage{" << params.fonts << "}\n";
1736 // this one is not per buffer
1737 if (lyxrc.fontenc != "default") {
1738 ofs << "\\usepackage[" << lyxrc.fontenc
1742 if (params.inputenc != "default") {
1743 ofs << "\\usepackage[" << params.inputenc
1748 /* at the very beginning the text parameters */
1749 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1750 switch (params.paperpackage) {
1751 case BufferParams::PACKAGE_A4:
1752 ofs << "\\usepackage{a4}\n";
1755 case BufferParams::PACKAGE_A4WIDE:
1756 ofs << "\\usepackage{a4wide}\n";
1759 case BufferParams::PACKAGE_WIDEMARGINSA4:
1760 ofs << "\\usepackage[widemargins]{a4}\n";
1765 if (params.use_geometry) {
1766 ofs << "\\usepackage{geometry}\n";
1768 ofs << "\\geometry{verbose";
1769 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1770 ofs << ",landscape";
1771 switch (params.papersize2) {
1772 case BufferParams::VM_PAPER_CUSTOM:
1773 if (!params.paperwidth.empty())
1774 ofs << ",paperwidth="
1775 << params.paperwidth;
1776 if (!params.paperheight.empty())
1777 ofs << ",paperheight="
1778 << params.paperheight;
1780 case BufferParams::VM_PAPER_USLETTER:
1781 ofs << ",letterpaper";
1783 case BufferParams::VM_PAPER_USLEGAL:
1784 ofs << ",legalpaper";
1786 case BufferParams::VM_PAPER_USEXECUTIVE:
1787 ofs << ",executivepaper";
1789 case BufferParams::VM_PAPER_A3:
1792 case BufferParams::VM_PAPER_A4:
1795 case BufferParams::VM_PAPER_A5:
1798 case BufferParams::VM_PAPER_B3:
1801 case BufferParams::VM_PAPER_B4:
1804 case BufferParams::VM_PAPER_B5:
1808 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1809 switch (lyxrc.default_papersize) {
1810 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1811 case BufferParams::PAPER_USLETTER:
1812 ofs << ",letterpaper";
1814 case BufferParams::PAPER_LEGALPAPER:
1815 ofs << ",legalpaper";
1817 case BufferParams::PAPER_EXECUTIVEPAPER:
1818 ofs << ",executivepaper";
1820 case BufferParams::PAPER_A3PAPER:
1823 case BufferParams::PAPER_A4PAPER:
1826 case BufferParams::PAPER_A5PAPER:
1829 case BufferParams::PAPER_B5PAPER:
1834 if (!params.topmargin.empty())
1835 ofs << ",tmargin=" << params.topmargin;
1836 if (!params.bottommargin.empty())
1837 ofs << ",bmargin=" << params.bottommargin;
1838 if (!params.leftmargin.empty())
1839 ofs << ",lmargin=" << params.leftmargin;
1840 if (!params.rightmargin.empty())
1841 ofs << ",rmargin=" << params.rightmargin;
1842 if (!params.headheight.empty())
1843 ofs << ",headheight=" << params.headheight;
1844 if (!params.headsep.empty())
1845 ofs << ",headsep=" << params.headsep;
1846 if (!params.footskip.empty())
1847 ofs << ",footskip=" << params.footskip;
1851 if (params.use_amsmath
1852 && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1853 ofs << "\\usepackage{amsmath}\n";
1857 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1858 if (params.pagestyle == "fancy") {
1859 ofs << "\\usepackage{fancyhdr}\n";
1862 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1866 // We try to load babel late, in case it interferes
1867 // with other packages.
1868 if (params.language != "default") {
1869 ofs << lyxrc.language_package;
1873 if (params.secnumdepth != tclass.secnumdepth()) {
1874 ofs << "\\setcounter{secnumdepth}{"
1875 << params.secnumdepth
1879 if (params.tocdepth != tclass.tocdepth()) {
1880 ofs << "\\setcounter{tocdepth}{"
1886 if (params.paragraph_separation) {
1887 switch (params.defskip.kind()) {
1888 case VSpace::SMALLSKIP:
1889 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1891 case VSpace::MEDSKIP:
1892 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1894 case VSpace::BIGSKIP:
1895 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1897 case VSpace::LENGTH:
1898 ofs << "\\setlength\\parskip{"
1899 << params.defskip.length().asLatexString()
1902 default: // should never happen // Then delete it.
1903 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1908 ofs << "\\setlength\\parindent{0pt}\n";
1912 // Now insert the LyX specific LaTeX commands...
1913 string preamble, tmppreamble;
1915 // The optional packages;
1916 preamble = features.getPackages(params);
1918 // this might be useful...
1919 preamble += "\n\\makeatletter\n\n";
1921 // Some macros LyX will need
1922 tmppreamble = features.getMacros(params);
1924 if (!tmppreamble.empty()) {
1925 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1926 "LyX specific LaTeX commands.\n"
1927 + tmppreamble + '\n';
1930 // the text class specific preamble
1931 tmppreamble = features.getTClassPreamble(params);
1932 if (!tmppreamble.empty()) {
1933 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1934 "Textclass specific LaTeX commands.\n"
1935 + tmppreamble + '\n';
1938 /* the user-defined preamble */
1939 if (!params.preamble.empty()) {
1940 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1941 "User specified LaTeX commands.\n"
1942 + params.preamble + '\n';
1945 preamble += "\\makeatother\n\n";
1947 // Itemize bullet settings need to be last in case the user
1948 // defines their own bullets that use a package included
1949 // in the user-defined preamble -- ARRae
1950 // Actually it has to be done much later than that
1951 // since some packages like frenchb make modifications
1952 // at \begin{document} time -- JMarc
1954 for (int i = 0; i < 4; ++i) {
1955 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1956 if (bullets_def.empty())
1957 bullets_def="\\AtBeginDocument{\n";
1958 bullets_def += " \\renewcommand{\\labelitemi";
1960 // `i' is one less than the item to modify
1967 bullets_def += "ii";
1973 bullets_def += "}{" +
1974 params.user_defined_bullets[i].getText()
1979 if (!bullets_def.empty())
1980 preamble += bullets_def + "}\n\n";
1982 for (int j = countChar(preamble, '\n'); j-- ;) {
1989 ofs << "\\begin{document}\n\n";
1993 lyxerr.debug() << "preamble finished, now the body." << endl;
1994 if (lyxrc.language_command_begin &&
1995 params.getDocumentDirection() == LYX_DIR_RIGHT_TO_LEFT)
1996 ofs << lyxrc.language_command_rtl;
1998 bool was_title = false;
1999 bool already_title = false;
2001 ostringstream ftnote;
2003 char * tmpholder = 0;
2008 LyXParagraph * par = paragraph;
2012 #ifndef HAVE_SSTREAM
2015 ftnote << tmpholder;
2016 delete [] tmpholder;
2021 lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
2023 LyXLayout const & layout =
2024 textclasslist.Style(params.textclass,
2027 if (layout.intitle) {
2028 if (already_title) {
2029 lyxerr <<"Error in MakeLatexFile: You"
2030 " should not mix title layouts"
2031 " with normal ones." << endl;
2034 } else if (was_title && !already_title) {
2035 ofs << "\\maketitle\n";
2037 already_title = true;
2040 // We are at depth 0 so we can just use
2041 // ordinary \footnote{} generation
2042 // flag this with ftcount
2044 if (layout.isEnvironment()
2045 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2046 par = par->TeXEnvironment(ofs, texrow,
2047 ftnote, ft_texrow, ftcount);
2049 par = par->TeXOnePar(ofs, texrow,
2050 ftnote, ft_texrow, ftcount);
2053 // Write out what we've generated...
2056 ofs << "\\addtocounter{footnote}{-"
2060 ofs << ftnote.str();
2061 texrow += ft_texrow;
2063 // The extra .c_str() is needed when we use
2064 // lyxstring instead of the STL string class.
2065 ftnote.str(string().c_str());
2067 delete [] ftnote.str();
2072 #ifndef HAVE_SSTREAM
2074 // I hate strstreams
2075 tmpholder = ftnote.str();
2079 #ifndef HAVE_SSTREAM
2080 delete [] tmpholder;
2082 // It might be that we only have a title in this document
2083 if (was_title && !already_title) {
2084 ofs << "\\maketitle\n";
2088 if (lyxrc.language_command_end &&
2089 params.getDocumentDirection() == LYX_DIR_RIGHT_TO_LEFT)
2090 ofs << lyxrc.language_command_ltr;
2093 ofs << "\\end{document}\n";
2096 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2098 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2102 // Just to be sure. (Asger)
2105 // tex_code_break_column's value is used to decide
2106 // if we are in batchmode or not (within mathed_write()
2107 // in math_write.C) so we must set it to a non-zero
2108 // value when we leave otherwise we save incorrect .lyx files.
2109 tex_code_break_column = lyxrc.ascii_linelen;
2113 lyxerr << "File was not closed properly." << endl;
2116 lyxerr.debug() << "Finished making latex file." << endl;
2120 bool Buffer::isLatex() const
2122 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2126 bool Buffer::isLinuxDoc() const
2128 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2132 bool Buffer::isLiterate() const
2134 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2138 bool Buffer::isDocBook() const
2140 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2144 bool Buffer::isSGML() const
2146 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2147 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2151 void Buffer::sgmlOpenTag(ostream & os, int depth,
2152 string const & latexname) const
2154 os << string(depth, ' ') << "<" << latexname << ">\n";
2158 void Buffer::sgmlCloseTag(ostream & os, int depth,
2159 string const & latexname) const
2161 os << string(depth, ' ') << "</" << latexname << ">\n";
2165 void Buffer::makeLinuxDocFile(string const & fname, int column)
2167 LyXParagraph * par = paragraph;
2169 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2170 string environment_stack[10];
2173 int depth = 0; /* paragraph depth */
2175 ofstream ofs(fname.c_str());
2178 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2182 tex_code_break_column = column;
2185 if (params.preamble.empty()) {
2186 ofs << "<!doctype linuxdoc system>\n\n";
2189 ofs << "<!doctype linuxdoc system \n [ "
2190 << params.preamble << " \n]>\n\n";
2193 ofs << "<!-- " << LYX_DOCVERSION
2194 << " created this file. For more info see http://www.lyx.org/"
2197 if(params.options.empty())
2198 sgmlOpenTag(ofs, 0, top_element);
2200 string top = top_element;
2202 top += params.options;
2203 sgmlOpenTag(ofs, 0, top);
2207 int desc_on = 0; /* description mode*/
2208 LyXLayout const & style =
2209 textclasslist.Style(users->buffer()->params.textclass,
2211 par->AutoDeleteInsets();
2213 /* treat <toc> as a special case for compatibility with old code */
2214 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2215 Inset * inset = par->GetInset(0);
2216 char lyx_code = inset->LyxCode();
2217 if (lyx_code == Inset::TOC_CODE){
2218 string temp = "toc";
2219 sgmlOpenTag(ofs, depth, temp);
2222 linuxDocHandleFootnote(ofs, par, depth);
2227 // environment tag closing
2228 for( ; depth > par->depth; --depth) {
2229 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2230 environment_stack[depth].clear();
2233 // write opening SGML tags
2234 switch(style.latextype) {
2235 case LATEX_PARAGRAPH:
2236 if(depth == par->depth
2237 && !environment_stack[depth].empty()) {
2238 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2239 environment_stack[depth].clear();
2245 sgmlOpenTag(ofs, depth, style.latexname());
2250 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2252 if (!environment_stack[depth].empty()){
2253 sgmlCloseTag(ofs, depth,
2254 environment_stack[depth]);
2258 environment_stack[depth].clear();
2259 sgmlOpenTag(ofs, depth, style.latexname());
2262 case LATEX_ENVIRONMENT:
2263 case LATEX_ITEM_ENVIRONMENT:
2264 if(depth == par->depth
2265 && environment_stack[depth] != style.latexname()
2266 && !environment_stack[depth].empty()) {
2268 sgmlCloseTag(ofs, depth,
2269 environment_stack[depth]);
2270 environment_stack[depth].clear();
2272 if (depth < par->depth) {
2274 environment_stack[depth].clear();
2276 if (environment_stack[depth] != style.latexname()) {
2279 sgmlOpenTag(ofs, depth, temp);
2281 environment_stack[depth] = style.latexname();
2282 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2284 if(style.latextype == LATEX_ENVIRONMENT) break;
2286 desc_on = (style.labeltype == LABEL_MANUAL);
2293 sgmlOpenTag(ofs, depth + 1, item_name);
2296 sgmlOpenTag(ofs, depth, style.latexname());
2301 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2304 linuxDocHandleFootnote(ofs, par, depth);
2306 while(par && par->IsDummy());
2309 /* write closing SGML tags */
2310 switch(style.latextype) {
2312 case LATEX_ENVIRONMENT:
2313 case LATEX_ITEM_ENVIRONMENT:
2316 sgmlCloseTag(ofs, depth, style.latexname());
2321 /* Close open tags */
2322 for(; depth > 0; --depth)
2323 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2325 if(!environment_stack[depth].empty())
2326 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2329 sgmlCloseTag(ofs, 0, top_element);
2332 // How to check for successful close
2336 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2339 string tag = "footnote";
2341 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2342 sgmlOpenTag(os, depth + 1, tag);
2343 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2344 sgmlCloseTag(os, depth + 1, tag);
2350 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2351 int const depth, int desc_on,
2352 LyXParagraph * & par)
2354 LyXParagraph * tpar = par;
2355 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2356 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2360 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2361 "Caption").second) {
2362 sgmlOpenTag(os, depth + 1, inner_tag);
2364 SimpleDocBookOnePar(os, extra_par, tpar,
2365 desc_on, depth + 2);
2366 sgmlCloseTag(os, depth+1, inner_tag);
2367 if(!extra_par.empty())
2373 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2376 string tag, inner_tag;
2377 string tmp_par, extra_par;
2378 bool inner_span = false;
2381 // Someone should give this enum a proper name (Lgb)
2389 SOME_ENUM last = NO_ONE;
2390 SOME_ENUM present = FOOTNOTE_LIKE;
2392 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2393 if(last == present) {
2395 if(!tmp_par.empty()) {
2398 sgmlCloseTag(os, depth + 1, inner_tag);
2399 sgmlOpenTag(os, depth + 1, inner_tag);
2406 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2408 if(!extra_par.empty()) os << extra_par;
2409 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2412 switch (par->footnotekind) {
2413 case LyXParagraph::FOOTNOTE:
2414 case LyXParagraph::ALGORITHM:
2417 present = FOOTNOTE_LIKE;
2420 case LyXParagraph::MARGIN:
2423 present = MARGIN_LIKE;
2426 case LyXParagraph::FIG:
2427 case LyXParagraph::WIDE_FIG:
2429 inner_tag = "title";
2433 case LyXParagraph::TAB:
2434 case LyXParagraph::WIDE_TAB:
2436 inner_tag = "title";
2441 sgmlOpenTag(os, depth, tag);
2442 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2443 DocBookHandleCaption(os, inner_tag, depth,
2447 sgmlOpenTag(os, depth + 1, inner_tag);
2450 // ignore all caption here, we processed them above!!!
2451 if (par->layout != textclasslist
2452 .NumberOfLayout(params.textclass,
2453 "Caption").second) {
2459 SimpleDocBookOnePar(ost, extra_par, par,
2460 desc_on, depth + 2);
2462 tmp_par += ost.str().c_str();
2465 char * ctmp = ost.str();
2470 tmp_par = frontStrip(strip(tmp_par));
2476 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2477 if(!extra_par.empty()) os << extra_par;
2478 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2482 /* push a tag in a style stack */
2483 void Buffer::push_tag(ostream & os, char const * tag,
2484 int & pos, char stack[5][3])
2486 /* pop all previous tags */
2487 for (int j = pos; j >= 0; --j)
2488 os << "</" << stack[j] << ">";
2491 sprintf(stack[++pos], "%s", tag);
2494 for (int i = 0; i <= pos; ++i)
2495 os << "<" << stack[i] << ">";
2498 void Buffer::pop_tag(ostream & os, char const * tag,
2499 int & pos, char stack[5][3])
2503 // pop all tags till specified one
2504 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2505 os << "</" << stack[j] << ">";
2508 os << "</" << tag << ">";
2510 // push all tags, but the specified one
2511 for (j = j + 1; j <= pos; ++j) {
2512 os << "<" << stack[j] << ">";
2513 strcpy(stack[j-1], stack[j]);
2519 /* handle internal paragraph parsing -- layout already processed */
2521 // checks, if newcol chars should be put into this line
2522 // writes newline, if necessary.
2524 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2525 const unsigned int newcol)
2528 if (colcount > lyxrc.ascii_linelen) {
2530 colcount = newcol; // assume write after this call
2535 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2536 int desc_on, int const /*depth*/)
2538 LyXFont font1, font2;
2541 LyXParagraph::size_type main_body;
2543 LyXLayout const & style = textclasslist.Style(params.textclass,
2546 char family_type = 0; // family font flag
2547 bool is_bold = false; // series font flag
2548 char shape_type = 0; // shape font flag
2549 bool is_em = false; // emphasis (italic) font flag
2551 int stack_num = -1; // style stack position
2552 char stack[5][3]; // style stack
2553 unsigned int char_line_count = 5; // Heuristic choice ;-)
2555 if (style.labeltype != LABEL_MANUAL)
2558 main_body = par->BeginningOfMainBody();
2560 /* gets paragraph main font */
2562 font1 = style.labelfont;
2567 /* parsing main loop */
2568 for (LyXParagraph::size_type i = 0;
2569 i < par->size(); ++i) {
2571 /* handle quote tag */
2572 if (i == main_body && !par->IsDummy()) {
2577 font2 = par->getFont(i);
2579 if (font1.family() != font2.family()) {
2580 switch(family_type) {
2582 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2583 push_tag(os, "tt", stack_num, stack);
2586 else if (font2.family() == LyXFont::SANS_FAMILY) {
2587 push_tag(os, "sf", stack_num, stack);
2592 pop_tag(os, "tt", stack_num, stack);
2593 if (font2.family() == LyXFont::SANS_FAMILY) {
2594 push_tag(os, "sf", stack_num, stack);
2602 pop_tag(os, "sf", stack_num, stack);
2603 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2604 push_tag(os, "tt", stack_num, stack);
2613 /* handle bold face */
2614 if (font1.series() != font2.series()) {
2615 if (font2.series() == LyXFont::BOLD_SERIES) {
2616 push_tag(os, "bf", stack_num, stack);
2620 pop_tag(os, "bf", stack_num, stack);
2625 /* handle italic and slanted fonts */
2626 if (font1.shape() != font2.shape()) {
2627 switch(shape_type) {
2629 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2630 push_tag(os, "it", stack_num, stack);
2633 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2634 push_tag(os, "sl", stack_num, stack);
2639 pop_tag(os, "it", stack_num, stack);
2640 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2641 push_tag(os, "sl", stack_num, stack);
2649 pop_tag(os, "sl", stack_num, stack);
2650 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2651 push_tag(os, "it", stack_num, stack);
2659 /* handle <em> tag */
2660 if (font1.emph() != font2.emph()) {
2661 if (font2.emph() == LyXFont::ON) {
2662 push_tag(os, "em", stack_num, stack);
2665 pop_tag(os, "em", stack_num, stack);
2670 c = par->GetChar(i);
2672 if (font2.latex() == LyXFont::ON) {
2673 // "TeX"-Mode on == > SGML-Mode on.
2675 os << c; // see LaTeX-Generation...
2677 } else if (c == LyXParagraph::META_INSET) {
2678 inset = par->GetInset(i);
2679 inset->Linuxdoc(os);
2682 if (par->linuxDocConvertChar(c, sgml_string)
2683 && !style.free_spacing) { // in freespacing
2685 // non-breaking characters
2689 linux_doc_line_break(os, char_line_count, 6);
2694 linux_doc_line_break(os, char_line_count, 1);
2700 char_line_count += sgml_string.length();
2706 if (lyxrc.language_command_end &&
2707 params.getDocumentDirection() == LYX_DIR_RIGHT_TO_LEFT)
2708 os << lyxrc.language_command_ltr;
2710 /* needed if there is an optional argument but no contents */
2711 if (main_body > 0 && main_body == par->size()) {
2715 /* pop all defined Styles */
2716 for (j = stack_num; j >= 0; --j) {
2717 linux_doc_line_break(os,
2719 3 + strlen(stack[j]));
2720 os << "</" << stack[j] << ">";
2723 /* resets description flag correctly */
2726 /* <tag> not closed... */
2727 linux_doc_line_break(os, char_line_count, 6);
2731 /* fprintf(file, "</p>");*/
2737 /* print an error message */
2738 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2739 char const * message)
2741 InsetError * new_inset;
2743 /* insert an error marker in text */
2744 new_inset = new InsetError(message);
2745 par->InsertChar(pos, LyXParagraph::META_INSET);
2746 par->InsertInset(pos, new_inset);
2749 // This constant defines the maximum number of
2750 // environment layouts that can be nesteded.
2751 // The same applies for command layouts.
2752 // These values should be more than enough.
2753 // José Matos (1999/07/22)
2755 enum { MAX_NEST_LEVEL = 25};
2757 void Buffer::makeDocBookFile(string const & fname, int column)
2759 LyXParagraph * par = paragraph;
2761 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2762 string environment_stack[MAX_NEST_LEVEL];
2763 string environment_inner[MAX_NEST_LEVEL];
2764 string command_stack[MAX_NEST_LEVEL];
2765 bool command_flag= false;
2766 int command_depth= 0, command_base= 0, cmd_depth= 0;
2768 string item_name, command_name;
2769 string c_depth, c_params, tmps;
2771 int depth= 0; /* paragraph depth */
2773 tex_code_break_column = column;
2775 ofstream ofs(fname.c_str());
2777 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2783 ofs << "<!doctype " << top_element
2784 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2786 if (params.preamble.empty())
2789 ofs << "\n [ " << params.preamble << " \n]>\n\n";
2791 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2792 << "\n See http://www.lyx.org/ for more information -->\n";
2794 if(params.options.empty())
2795 sgmlOpenTag(ofs, 0, top_element);
2797 string top = top_element;
2799 top += params.options;
2800 sgmlOpenTag(ofs, 0, top);
2804 int desc_on = 0; /* description mode*/
2805 LyXLayout const & style =
2806 textclasslist.Style(users->buffer()->params.textclass,
2808 par->AutoDeleteInsets();
2810 /* environment tag closing */
2811 for( ; depth > par->depth; --depth) {
2812 if(environment_inner[depth] != "!-- --") {
2813 item_name= "listitem";
2814 sgmlCloseTag(ofs, command_depth + depth,
2816 if( environment_inner[depth] == "varlistentry")
2817 sgmlCloseTag(ofs, depth+command_depth,
2818 environment_inner[depth]);
2820 sgmlCloseTag(ofs, depth + command_depth,
2821 environment_stack[depth]);
2822 environment_stack[depth].clear();
2823 environment_inner[depth].clear();
2826 if(depth == par->depth
2827 && environment_stack[depth] != style.latexname()
2828 && !environment_stack[depth].empty()) {
2829 if(environment_inner[depth] != "!-- --") {
2830 item_name= "listitem";
2831 sgmlCloseTag(ofs, command_depth+depth,
2833 if( environment_inner[depth] == "varlistentry")
2835 depth + command_depth,
2836 environment_inner[depth]);
2839 sgmlCloseTag(ofs, depth + command_depth,
2840 environment_stack[depth]);
2842 environment_stack[depth].clear();
2843 environment_inner[depth].clear();
2846 // Write opening SGML tags.
2847 switch(style.latextype) {
2848 case LATEX_PARAGRAPH:
2849 if(style.latexname() != "dummy")
2850 sgmlOpenTag(ofs, depth+command_depth,
2856 LinuxDocError(par, 0,
2857 _("Error : Wrong depth for "
2858 "LatexType Command.\n"));
2860 command_name = style.latexname();
2862 tmps = style.latexparam();
2863 c_params = split(tmps, c_depth,'|');
2865 cmd_depth= atoi(c_depth.c_str());
2868 if(cmd_depth<command_base) {
2869 for(int j = command_depth;
2870 j >= command_base; --j)
2871 if(!command_stack[j].empty())
2872 sgmlCloseTag(ofs, j, command_stack[j]);
2873 command_depth= command_base= cmd_depth;
2875 else if(cmd_depth <= command_depth) {
2876 for(int j = command_depth;
2877 j >= cmd_depth; --j)
2879 if(!command_stack[j].empty())
2880 sgmlCloseTag(ofs, j, command_stack[j]);
2881 command_depth= cmd_depth;
2884 command_depth= cmd_depth;
2887 command_depth = command_base = cmd_depth;
2888 command_flag = true;
2890 command_stack[command_depth]= command_name;
2892 // treat label as a special case for
2893 // more WYSIWYM handling.
2894 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2895 Inset * inset = par->GetInset(0);
2896 char lyx_code = inset->LyxCode();
2897 if (lyx_code == Inset::LABEL_CODE){
2898 command_name += " id=\"";
2899 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2900 command_name += "\"";
2905 sgmlOpenTag(ofs, depth+command_depth, command_name);
2906 item_name = "title";
2907 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2910 case LATEX_ENVIRONMENT:
2911 case LATEX_ITEM_ENVIRONMENT:
2912 if (depth < par->depth) {
2914 environment_stack[depth].clear();
2917 if (environment_stack[depth] != style.latexname()) {
2918 environment_stack[depth] = style.latexname();
2919 environment_inner[depth] = "!-- --";
2920 sgmlOpenTag(ofs, depth + command_depth,
2921 environment_stack[depth]);
2923 if(environment_inner[depth] != "!-- --") {
2924 item_name= "listitem";
2926 command_depth + depth,
2928 if (environment_inner[depth] == "varlistentry")
2930 depth + command_depth,
2931 environment_inner[depth]);
2935 if(style.latextype == LATEX_ENVIRONMENT) {
2936 if(!style.latexparam().empty())
2937 sgmlOpenTag(ofs, depth + command_depth,
2938 style.latexparam());
2942 desc_on = (style.labeltype == LABEL_MANUAL);
2945 environment_inner[depth]= "varlistentry";
2947 environment_inner[depth]= "listitem";
2949 sgmlOpenTag(ofs, depth + 1 + command_depth,
2950 environment_inner[depth]);
2954 sgmlOpenTag(ofs, depth + 1 + command_depth,
2959 sgmlOpenTag(ofs, depth + 1 + command_depth,
2964 sgmlOpenTag(ofs, depth + command_depth,
2971 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
2972 depth + 1 + command_depth);
2974 DocBookHandleFootnote(ofs, par,
2975 depth + 1 + command_depth);
2977 while(par && par->IsDummy());
2980 /* write closing SGML tags */
2981 switch(style.latextype) {
2984 sgmlCloseTag(ofs, depth + command_depth, end_tag);
2986 case LATEX_ENVIRONMENT:
2987 if(!style.latexparam().empty())
2988 sgmlCloseTag(ofs, depth + command_depth,
2989 style.latexparam());
2991 case LATEX_ITEM_ENVIRONMENT:
2992 if(desc_on == 1) break;
2994 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2996 case LATEX_PARAGRAPH:
2997 if(style.latexname() != "dummy")
2998 sgmlCloseTag(ofs, depth + command_depth,
3002 sgmlCloseTag(ofs, depth + command_depth,
3009 for(; depth >= 0; --depth) {
3010 if(!environment_stack[depth].empty()) {
3011 if(environment_inner[depth] != "!-- --") {
3012 item_name= "listitem";
3013 sgmlCloseTag(ofs, command_depth + depth,
3015 if( environment_inner[depth] == "varlistentry")
3016 sgmlCloseTag(ofs, depth + command_depth,
3017 environment_inner[depth]);
3020 sgmlCloseTag(ofs, depth + command_depth,
3021 environment_stack[depth]);
3025 for(int j = command_depth; j >= command_base; --j)
3026 if(!command_stack[j].empty())
3027 sgmlCloseTag(ofs, j, command_stack[j]);
3030 sgmlCloseTag(ofs, 0, top_element);
3033 // How to check for successful close
3037 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3038 LyXParagraph * par, int & desc_on,
3042 par->SimpleDocBookOneTablePar(os, extra, desc_on, depth);
3046 bool emph_flag = false;
3048 LyXLayout const & style = textclasslist.Style(params.textclass,
3051 LyXParagraph::size_type main_body;
3052 if (style.labeltype != LABEL_MANUAL)
3055 main_body = par->BeginningOfMainBody();
3057 // gets paragraph main font
3058 //if (main_body > 0)
3059 // font1 = style.labelfont;
3061 // font1 = style.font;
3062 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3064 int char_line_count = depth;
3065 if(!style.free_spacing)
3066 for (int j = 0; j < depth; ++j)
3069 // parsing main loop
3070 for (LyXParagraph::size_type i = 0;
3071 i < par->size(); ++i) {
3072 LyXFont font2 = par->getFont(i);
3074 // handle <emphasis> tag
3075 if (font1.emph() != font2.emph() && i) {
3076 if (font2.emph() == LyXFont::ON) {
3080 os << "</emphasis>";
3085 char c = par->GetChar(i);
3087 if (c == LyXParagraph::META_INSET) {
3088 Inset * inset = par->GetInset(i);
3091 inset->DocBook(ost);
3092 string tmp_out = ost.str().c_str();
3095 inset->DocBook(ost);
3097 char * ctmp = ost.str();
3098 string tmp_out(ctmp);
3102 // This code needs some explanation:
3103 // Two insets are treated specially
3104 // label if it is the first element in a command paragraph
3106 // graphics inside tables or figure floats can't go on
3107 // title (the equivalente in latex for this case is caption
3108 // and title should come first
3111 if(desc_on!= 3 || i!= 0) {
3112 if(!tmp_out.empty() && tmp_out[0] == '@') {
3114 extra += frontStrip(tmp_out, '@');
3116 os << frontStrip(tmp_out, '@');
3121 } else if (font2.latex() == LyXFont::ON) {
3122 // "TeX"-Mode on ==> SGML-Mode on.
3129 if (par->linuxDocConvertChar(c, sgml_string)
3130 && !style.free_spacing) { // in freespacing
3132 // non-breaking characters
3136 os << "\n</term><listitem><para>";
3150 /* needed if there is an optional argument but no contents */
3151 if (main_body > 0 && main_body == par->size()) {
3155 os << "</emphasis>";
3158 /* resets description flag correctly */
3161 /* <term> not closed... */
3169 int Buffer::runLaTeX()
3171 if (!users->text) return 0;
3175 // get LaTeX-Filename
3176 string name = getLatexName();
3178 string path = OnlyPath(filename);
3180 string org_path = path;
3181 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3185 Path p(path); // path to LaTeX file
3186 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3188 // Remove all error insets
3189 bool a = users->removeAutoInsets();
3191 // Always generate the LaTeX file
3192 makeLaTeXFile(name, org_path, false);
3195 // do the LaTex run(s)
3197 string latex_command = lyxrc.pdf_mode ?
3198 lyxrc.pdflatex_command : lyxrc.latex_command;
3199 LaTeX latex(latex_command, name, filepath);
3200 int res = latex.run(terr,
3201 users->owner()->getMiniBuffer()); // running latex
3203 // check return value from latex.run().
3204 if ((res & LaTeX::NO_LOGFILE)) {
3205 WriteAlert(_("LaTeX did not work!"),
3206 _("Missing log file:"), name);
3207 } else if ((res & LaTeX::ERRORS)) {
3208 users->owner()->getMiniBuffer()->Set(_("Done"));
3209 // Insert all errors as errors boxes
3210 users->insertErrors(terr);
3212 // Dvi should also be kept dirty if the latex run
3213 // ends up with errors. However it should be possible
3214 // to view a dirty dvi too.
3216 //no errors or any other things to think about so:
3217 users->owner()->getMiniBuffer()->Set(_("Done"));
3221 // if we removed error insets before we ran LaTeX or if we inserted
3222 // error insets after we ran LaTeX this must be run:
3223 if (a || (res & LaTeX::ERRORS)){
3226 users->updateScrollbar();
3230 return latex.getNumErrors();
3234 int Buffer::runLiterate()
3236 if (!users->text) return 0;
3240 // get LaTeX-Filename
3241 string name = getLatexName();
3242 // get Literate-Filename
3243 string lit_name = ChangeExtension (getLatexName(),
3244 lyxrc.literate_extension, true);
3246 string path = OnlyPath(filename);
3248 string org_path = path;
3249 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3253 Path p(path); // path to Literate file
3254 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3256 // Remove all error insets
3257 bool a = users->removeAutoInsets();
3259 // generate the Literate file if necessary
3260 if (!isDviClean() || a) {
3261 makeLaTeXFile(lit_name, org_path, false);
3265 string latex_command = lyxrc.pdf_mode ?
3266 lyxrc.pdflatex_command : lyxrc.latex_command;
3267 Literate literate(latex_command, name, filepath,
3269 lyxrc.literate_command, lyxrc.literate_error_filter,
3270 lyxrc.build_command, lyxrc.build_error_filter);
3272 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3274 // check return value from literate.weave().
3275 if ((res & Literate::NO_LOGFILE)) {
3276 WriteAlert(_("Literate command did not work!"),
3277 _("Missing log file:"), name);
3278 } else if ((res & Literate::ERRORS)) {
3279 users->owner()->getMiniBuffer()->Set(_("Done"));
3280 // Insert all errors as errors boxes
3281 users->insertErrors(terr);
3283 // Dvi should also be kept dirty if the latex run
3284 // ends up with errors. However it should be possible
3285 // to view a dirty dvi too.
3287 //no errors or any other things to think about so:
3288 users->owner()->getMiniBuffer()->Set(_("Done"));
3292 // if we removed error insets before we ran LaTeX or if we inserted
3293 // error insets after we ran LaTeX this must be run:
3294 if (a || (res & Literate::ERRORS)){
3297 users->updateScrollbar();
3301 return literate.getNumErrors();
3305 int Buffer::buildProgram()
3307 if (!users->text) return 0;
3311 // get LaTeX-Filename
3312 string name = getLatexName();
3313 // get Literate-Filename
3314 string lit_name = ChangeExtension(getLatexName(),
3315 lyxrc.literate_extension, true);
3317 string path = OnlyPath(filename);
3319 string org_path = path;
3320 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3324 Path p(path); // path to Literate file
3325 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3327 // Remove all error insets
3328 bool a = users->removeAutoInsets();
3330 // generate the LaTeX file if necessary
3331 if (!isNwClean() || a) {
3332 makeLaTeXFile(lit_name, org_path, false);
3336 string latex_command = lyxrc.pdf_mode ?
3337 lyxrc.pdflatex_command : lyxrc.latex_command;
3338 Literate literate(latex_command, name, filepath,
3340 lyxrc.literate_command, lyxrc.literate_error_filter,
3341 lyxrc.build_command, lyxrc.build_error_filter);
3343 int res = literate.build(terr, users->owner()->getMiniBuffer());
3345 // check return value from literate.build().
3346 if ((res & Literate::NO_LOGFILE)) {
3347 WriteAlert(_("Build did not work!"),
3348 _("Missing log file:"), name);
3349 } else if ((res & Literate::ERRORS)) {
3350 users->owner()->getMiniBuffer()->Set(_("Done"));
3351 // Insert all errors as errors boxes
3352 users->insertErrors(terr);
3354 // Literate files should also be kept dirty if the literate
3355 // command run ends up with errors.
3357 //no errors or any other things to think about so:
3358 users->owner()->getMiniBuffer()->Set(_("Done"));
3362 // if we removed error insets before we ran Literate/Build or if we inserted
3363 // error insets after we ran Literate/Build this must be run:
3364 if (a || (res & Literate::ERRORS)){
3367 users->updateScrollbar();
3371 return literate.getNumErrors();
3375 // This should be enabled when the Chktex class is implemented. (Asger)
3376 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3377 // Other flags: -wall -v0 -x
3378 int Buffer::runChktex()
3380 if (!users->text) return 0;
3384 // get LaTeX-Filename
3385 string name = getLatexName();
3386 string path = OnlyPath(filename);
3388 string org_path = path;
3389 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3393 Path p(path); // path to LaTeX file
3394 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3396 // Remove all error insets
3397 bool a = users->removeAutoInsets();
3399 // Generate the LaTeX file if neccessary
3400 if (!isDviClean() || a) {
3401 makeLaTeXFile(name, org_path, false);
3406 Chktex chktex(lyxrc.chktex_command, name, filepath);
3407 int res = chktex.run(terr); // run chktex
3410 WriteAlert(_("chktex did not work!"),
3411 _("Could not run with file:"), name);
3412 } else if (res > 0) {
3413 // Insert all errors as errors boxes
3414 users->insertErrors(terr);
3417 // if we removed error insets before we ran chktex or if we inserted
3418 // error insets after we ran chktex, this must be run:
3422 users->updateScrollbar();
3431 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
3433 LyXFont font1(LyXFont::ALL_INHERIT);
3436 LyXParagraph::size_type i;
3440 string fname1 = TmpFileName(string(), "RAT1");
3441 string fname2 = TmpFileName(string(), "RAT2");
3443 ofstream ofs(fname1.c_str());
3445 WriteAlert(_("LYX_ERROR:"),
3446 _("Cannot open temporary file:"), fname1);
3449 par->table->RoffEndOfCell(ofs, -1);
3450 for (i = 0; i < par->size(); ++i) {
3451 c = par->GetChar(i);
3452 if (par->table->IsContRow(cell)) {
3453 if (c == LyXParagraph::META_NEWLINE)
3457 font2 = par->GetFontSettings(i);
3458 if (font1.latex() != font2.latex()) {
3459 if (font2.latex() != LyXFont::OFF)
3463 case LyXParagraph::META_INSET:
3464 if ((inset = par->GetInset(i))) {
3467 stringstresm ss(ios::in | ios::out);
3468 inset->Latex(ss, -1);
3480 inset->Latex(ss, -1);
3493 fstream fs(fname2.c_str(), ios::in|ios::out);
3495 WriteAlert(_("LYX_ERROR:"),
3496 _("Cannot open temporary file:"), fname2);
3498 remove(fname1.c_str());
3501 inset->Latex(fs, -1);
3515 case LyXParagraph::META_NEWLINE:
3516 if (par->table->CellHasContRow(cell)>= 0)
3517 par->RoffContTableRows(ofs, i+1, cell);
3518 par->table->RoffEndOfCell(ofs, cell);
3521 case LyXParagraph::META_HFILL:
3524 case LyXParagraph::META_PROTECTED_SEPARATOR:
3535 << "RoffAsciiTable:"
3536 " NULL char in structure." << endl;
3540 par->table->RoffEndOfCell(ofs, cell);
3542 string cmd = lyxrc.ascii_roff_command + " >" + fname2;
3543 cmd = subst(cmd, "$$FName", fname1);
3544 Systemcalls one(Systemcalls::System, cmd);
3545 if (!(lyxerr.debugging(Debug::ROFF))) {
3546 remove(fname1.c_str());
3548 ifstream ifs(fname2.c_str());
3550 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3553 // now output the produced file
3557 WriteAlert(_("Error!"),
3558 _("Error executing *roff command on table"));
3559 // overread leading blank lines
3560 while(!ifs && (c == '\n'))
3563 for(j = 0; j < par->depth; ++j)
3565 while(!ifs && (c != '\n')) {
3570 // overread trailing blank lines
3571 while(!ifs && (c == '\n'))
3575 remove(fname2.c_str());
3580 /// changed Heinrich Bauer, 23/03/98
3581 bool Buffer::isDviClean() const
3583 if (lyxrc.use_tempdir)
3584 return dvi_clean_tmpd;
3586 return dvi_clean_orgd;
3590 /// changed Heinrich Bauer, 23/03/98
3591 void Buffer::markDviClean()
3593 if (lyxrc.use_tempdir)
3594 dvi_clean_tmpd = true;
3596 dvi_clean_orgd = true;
3600 /// changed Heinrich Bauer, 23/03/98
3601 void Buffer::markDviDirty()
3603 if (lyxrc.use_tempdir)
3604 dvi_clean_tmpd = false;
3606 dvi_clean_orgd = false;
3610 void Buffer::validate(LaTeXFeatures & features) const
3612 LyXParagraph * par = paragraph;
3613 LyXTextClass const & tclass =
3614 textclasslist.TextClass(params.textclass);
3616 // AMS Style is at document level
3618 features.amsstyle = (params.use_amsmath ||
3619 tclass.provides(LyXTextClass::amsmath));
3622 // We don't use "lyxerr.debug" because of speed. (Asger)
3623 if (lyxerr.debugging(Debug::LATEX))
3624 lyxerr << "Paragraph: " << par << endl;
3626 // Now just follow the list of paragraphs and run
3627 // validate on each of them.
3628 par->validate(features);
3630 // and then the next paragraph
3634 // the bullet shapes are buffer level not paragraph level
3635 // so they are tested here
3636 for (int i = 0; i < 4; ++i) {
3637 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3638 int font = params.user_defined_bullets[i].getFont();
3641 .user_defined_bullets[i]
3648 features.latexsym = true;
3652 features.amssymb = true;
3654 else if ((font >= 2 && font <= 5)) {
3655 features.pifont = true;
3660 if (lyxerr.debugging(Debug::LATEX)) {
3661 features.showStruct(params);
3666 void Buffer::setPaperStuff()
3668 params.papersize = BufferParams::PAPER_DEFAULT;
3669 char c1 = params.paperpackage;
3670 if (c1 == BufferParams::PACKAGE_NONE) {
3671 char c2 = params.papersize2;
3672 if (c2 == BufferParams::VM_PAPER_USLETTER)
3673 params.papersize = BufferParams::PAPER_USLETTER;
3674 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3675 params.papersize = BufferParams::PAPER_LEGALPAPER;
3676 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3677 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3678 else if (c2 == BufferParams::VM_PAPER_A3)
3679 params.papersize = BufferParams::PAPER_A3PAPER;
3680 else if (c2 == BufferParams::VM_PAPER_A4)
3681 params.papersize = BufferParams::PAPER_A4PAPER;
3682 else if (c2 == BufferParams::VM_PAPER_A5)
3683 params.papersize = BufferParams::PAPER_A5PAPER;
3684 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3685 (c2 == BufferParams::VM_PAPER_B5))
3686 params.papersize = BufferParams::PAPER_B5PAPER;
3687 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3688 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3689 params.papersize = BufferParams::PAPER_A4PAPER;
3693 // This function should be in Buffer because it's a buffer's property (ale)
3694 string Buffer::getIncludeonlyList(char delim)
3697 LyXParagraph * par = paragraph;
3698 LyXParagraph::size_type pos;
3702 while ((inset = par->ReturnNextInsetPointer(pos))){
3703 if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3704 InsetInclude * insetinc =
3705 static_cast<InsetInclude*>(inset);
3706 if (insetinc->isInclude()
3707 && insetinc->isNoLoad()) {
3710 lst += ChangeExtension(insetinc->getContents(), string(), true);
3717 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3722 // This is also a buffer property (ale)
3723 string Buffer::getReferenceList(char delim)
3725 /// if this is a child document and the parent is already loaded
3726 /// Use the parent's list instead [ale990407]
3727 if (!params.parentname.empty()
3728 && bufferlist.exists(params.parentname)) {
3729 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3731 return tmp->getReferenceList(delim);
3734 LyXParagraph * par = paragraph;
3735 LyXParagraph::size_type pos;
3740 while ((inset = par->ReturnNextInsetPointer(pos))){
3741 for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
3744 lst += inset->getLabel(i);
3750 lyxerr.debug() << "References(" << lst << ")" << endl;
3755 // This is also a buffer property (ale)
3756 string Buffer::getBibkeyList(char delim)
3758 /// if this is a child document and the parent is already loaded
3759 /// Use the parent's list instead [ale990412]
3760 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3761 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3763 return tmp->getBibkeyList(delim);
3767 LyXParagraph * par = paragraph;
3770 if (!bibkeys.empty())
3772 bibkeys += par->bibkey->getContents();
3777 // Might be either using bibtex or a child has bibliography
3778 if (bibkeys.empty()) {
3782 LyXParagraph::size_type pos = -1;
3784 // Search for Bibtex or Include inset
3785 while ((inset = par->ReturnNextInsetPointer(pos))) {
3786 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3787 if (!bibkeys.empty())
3789 bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
3790 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3791 string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
3793 if (!bibkeys.empty())
3804 lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3809 bool Buffer::isDepClean(string const & name) const
3811 DEPCLEAN * item = dep_clean;
3812 while (item && item->master != name)
3814 if (!item) return true;
3819 void Buffer::markDepClean(string const & name)
3822 dep_clean = new DEPCLEAN;
3823 dep_clean->clean = true;
3824 dep_clean->master = name;
3825 dep_clean->next = 0;
3827 DEPCLEAN* item = dep_clean;
3828 while (item && item->master != name)
3833 item = new DEPCLEAN;
3835 item->master = name;
3842 void Buffer::Dispatch(string const & command)
3844 // Split command string into command and argument
3845 string cmd, line = frontStrip(command);
3846 string arg = strip(frontStrip(split(line, cmd, ' ')));
3848 Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3852 void Buffer::Dispatch(int action, string const & argument)
3856 MenuExport(this, argument);
3860 lyxerr << "A truly unknown func!" << endl;