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);
301 par->InsertInset(pos, inset);
302 par->SetFont(pos, font);
304 } else if (token == "\\layout") {
308 par->text.resize(par->text.size());
309 par = new LyXParagraph(par);
313 string layoutname = lex.GetString();
314 pair<bool, LyXTextClass::LayoutList::size_type> pp
315 = textclasslist.NumberOfLayout(params.textclass,
318 par->layout = pp.second;
319 } else { // layout not found
320 // use default layout "Standard" (0)
323 // Test whether the layout is obsolete.
324 LyXLayout const & layout =
325 textclasslist.Style(params.textclass,
327 if (!layout.obsoleted_by().empty())
329 textclasslist.NumberOfLayout(params.textclass,
330 layout.obsoleted_by()).second;
331 par->footnoteflag = footnoteflag;
332 par->footnotekind = footnotekind;
334 font = LyXFont(LyXFont::ALL_INHERIT);
335 } else if (token == "\\end_float") {
339 par->text.resize(par->text.size());
340 par = new LyXParagraph(par);
342 footnotekind = LyXParagraph::FOOTNOTE;
343 footnoteflag = LyXParagraph::NO_FOOTNOTE;
346 par->layout = LYX_DUMMY_LAYOUT;
347 font = LyXFont(LyXFont::ALL_INHERIT);
348 } else if (token == "\\begin_float") {
349 tmpret = lex.FindToken(string_footnotekinds);
350 if (tmpret == -1) ++tmpret;
351 if (tmpret != LYX_LAYOUT_DEFAULT)
352 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
353 if (footnotekind == LyXParagraph::FOOTNOTE
354 || footnotekind == LyXParagraph::MARGIN)
355 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
357 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
358 } else if (token == "\\begin_deeper") {
360 } else if (token == "\\end_deeper") {
362 lex.printError("\\end_deeper: "
363 "depth is already null");
367 } else if (token == "\\begin_preamble") {
368 params.readPreamble(lex);
369 } else if (token == "\\textclass") {
371 pair<bool, LyXTextClassList::size_type> pp =
372 textclasslist.NumberOfClass(lex.GetString());
374 params.textclass = pp.second;
376 lex.printError("Unknown textclass `$$Token'");
377 params.textclass = 0;
379 if (!textclasslist.Load(params.textclass)) {
380 // if the textclass wasn't loaded properly
381 // we need to either substitute another
382 // or stop loading the file.
383 // I can substitute but I don't see how I can
384 // stop loading... ideas?? ARRae980418
385 WriteAlert(_("Textclass Loading Error!"),
386 string(_("Can't load textclass ")) +
387 textclasslist.NameOfClass(params.textclass),
388 _("-- substituting default"));
389 params.textclass = 0;
391 } else if (token == "\\options") {
393 params.options = lex.GetString();
394 } else if (token == "\\language") {
395 params.readLanguage(lex);
396 } else if (token == "\\fontencoding") {
398 } else if (token == "\\inputencoding") {
400 params.inputenc = lex.GetString();
401 } else if (token == "\\graphics") {
402 params.readGraphicsDriver(lex);
403 } else if (token == "\\fontscheme") {
405 params.fonts = lex.GetString();
406 } else if (token == "\\noindent") {
407 par->noindent = true;
408 } else if (token == "\\fill_top") {
409 par->added_space_top = VSpace(VSpace::VFILL);
410 } else if (token == "\\fill_bottom") {
411 par->added_space_bottom = VSpace(VSpace::VFILL);
412 } else if (token == "\\line_top") {
413 par->line_top = true;
414 } else if (token == "\\line_bottom") {
415 par->line_bottom = true;
416 } else if (token == "\\pagebreak_top") {
417 par->pagebreak_top = true;
418 } else if (token == "\\pagebreak_bottom") {
419 par->pagebreak_bottom = true;
420 } else if (token == "\\start_of_appendix") {
421 par->start_of_appendix = true;
422 } else if (token == "\\paragraph_separation") {
423 tmpret = lex.FindToken(string_paragraph_separation);
424 if (tmpret == -1) ++tmpret;
425 if (tmpret != LYX_LAYOUT_DEFAULT)
426 params.paragraph_separation =
427 static_cast<BufferParams::PARSEP>(tmpret);
428 } else if (token == "\\defskip") {
430 params.defskip = VSpace(lex.GetString());
432 } else if (token == "\\no_isolatin1") { // obsolete
434 } else if (token == "\\no_babel") { // obsolete
436 } else if (token == "\\no_epsfig") { // obsolete
439 } else if (token == "\\epsfig") { // obsolete
440 // Indeed it is obsolete, but we HAVE to be backwards
441 // compatible until 0.14, because otherwise all figures
442 // in existing documents are irretrivably lost. (Asger)
443 params.readGraphicsDriver(lex);
444 } else if (token == "\\quotes_language") {
445 tmpret = lex.FindToken(string_quotes_language);
446 if (tmpret == -1) ++tmpret;
447 if (tmpret != LYX_LAYOUT_DEFAULT) {
448 InsetQuotes::quote_language tmpl =
449 InsetQuotes::EnglishQ;
452 tmpl = InsetQuotes::EnglishQ;
455 tmpl = InsetQuotes::SwedishQ;
458 tmpl = InsetQuotes::GermanQ;
461 tmpl = InsetQuotes::PolishQ;
464 tmpl = InsetQuotes::FrenchQ;
467 tmpl = InsetQuotes::DanishQ;
470 params.quotes_language = tmpl;
472 } else if (token == "\\quotes_times") {
474 switch(lex.GetInteger()) {
476 params.quotes_times = InsetQuotes::SingleQ;
479 params.quotes_times = InsetQuotes::DoubleQ;
482 } else if (token == "\\papersize") {
483 tmpret = lex.FindToken(string_papersize);
487 params.papersize2 = tmpret;
488 } else if (token == "\\paperpackage") {
489 tmpret = lex.FindToken(string_paperpackages);
492 params.paperpackage = BufferParams::PACKAGE_NONE;
494 params.paperpackage = tmpret;
495 } else if (token == "\\use_geometry") {
497 params.use_geometry = lex.GetInteger();
498 } else if (token == "\\use_amsmath") {
500 params.use_amsmath = lex.GetInteger();
501 } else if (token == "\\paperorientation") {
502 tmpret = lex.FindToken(string_orientation);
503 if (tmpret == -1) ++tmpret;
504 if (tmpret != LYX_LAYOUT_DEFAULT)
505 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
506 } else if (token == "\\paperwidth") {
508 params.paperwidth = lex.GetString();
509 } else if (token == "\\paperheight") {
511 params.paperheight = lex.GetString();
512 } else if (token == "\\leftmargin") {
514 params.leftmargin = lex.GetString();
515 } else if (token == "\\topmargin") {
517 params.topmargin = lex.GetString();
518 } else if (token == "\\rightmargin") {
520 params.rightmargin = lex.GetString();
521 } else if (token == "\\bottommargin") {
523 params.bottommargin = lex.GetString();
524 } else if (token == "\\headheight") {
526 params.headheight = lex.GetString();
527 } else if (token == "\\headsep") {
529 params.headsep = lex.GetString();
530 } else if (token == "\\footskip") {
532 params.footskip = lex.GetString();
533 } else if (token == "\\paperfontsize") {
535 params.fontsize = strip(lex.GetString());
536 } else if (token == "\\papercolumns") {
538 params.columns = lex.GetInteger();
539 } else if (token == "\\papersides") {
541 switch(lex.GetInteger()) {
543 case 1: params.sides = LyXTextClass::OneSide; break;
544 case 2: params.sides = LyXTextClass::TwoSides; break;
546 } else if (token == "\\paperpagestyle") {
548 params.pagestyle = strip(lex.GetString());
549 } else if (token == "\\bullet") {
551 int index = lex.GetInteger();
553 int temp_int = lex.GetInteger();
554 params.user_defined_bullets[index].setFont(temp_int);
555 params.temp_bullets[index].setFont(temp_int);
557 temp_int = lex.GetInteger();
558 params.user_defined_bullets[index].setCharacter(temp_int);
559 params.temp_bullets[index].setCharacter(temp_int);
561 temp_int = lex.GetInteger();
562 params.user_defined_bullets[index].setSize(temp_int);
563 params.temp_bullets[index].setSize(temp_int);
565 string temp_str = lex.GetString();
566 if (temp_str != "\\end_bullet") {
567 // this element isn't really necessary for
568 // parsing but is easier for humans
569 // to understand bullets. Put it back and
570 // set a debug message?
571 lex.printError("\\end_bullet expected, got" + temp_str);
572 //how can I put it back?
574 } else if (token == "\\bulletLaTeX") {
576 int index = lex.GetInteger();
578 string temp_str = lex.GetString(), sum_str;
579 while (temp_str != "\\end_bullet") {
580 // this loop structure is needed when user
581 // enters an empty string since the first
582 // thing returned will be the \\end_bullet
584 // if the LaTeX entry has spaces. Each element
585 // therefore needs to be read in turn
588 temp_str = lex.GetString();
590 params.user_defined_bullets[index].setText(sum_str);
591 params.temp_bullets[index].setText(sum_str);
592 } else if (token == "\\secnumdepth") {
594 params.secnumdepth = lex.GetInteger();
595 } else if (token == "\\tocdepth") {
597 params.tocdepth = lex.GetInteger();
598 } else if (token == "\\baselinestretch") { // obsolete
599 lex.nextToken(); // should not be used directly
601 // Will probably keep a kind of support just for
603 params.spacing.set(Spacing::Other, lex.GetFloat());
604 } else if (token == "\\spacing") {
606 string tmp = strip(lex.GetString());
607 if (tmp == "single") {
608 params.spacing.set(Spacing::Single);
609 } else if (tmp == "onehalf") {
610 params.spacing.set(Spacing::Onehalf);
611 } else if (tmp == "double") {
612 params.spacing.set(Spacing::Double);
613 } else if (tmp == "other") {
615 params.spacing.set(Spacing::Other,
618 lex.printError("Unknown spacing token: '$$Token'");
620 } else if (token == "\\float_placement") {
622 params.float_placement = lex.GetString();
623 } else if (token == "\\cursor") { // obsolete
624 // this is obsolete, so we just skip it.
626 } else if (token == "\\family") {
628 font.setLyXFamily(lex.GetString());
629 } else if (token == "\\series") {
631 font.setLyXSeries(lex.GetString());
632 } else if (token == "\\shape") {
634 font.setLyXShape(lex.GetString());
635 } else if (token == "\\size") {
637 font.setLyXSize(lex.GetString());
638 } else if (token == "\\latex") {
640 string tok = lex.GetString();
641 // This is dirty, but gone with LyX3. (Asger)
642 if (tok == "no_latex")
643 font.setLatex(LyXFont::OFF);
644 else if (tok == "latex")
645 font.setLatex(LyXFont::ON);
646 else if (tok == "default")
647 font.setLatex(LyXFont::INHERIT);
649 lex.printError("Unknown LaTeX font flag "
651 } else if (token == "\\direction") {
653 string tok = lex.GetString();
655 font.setDirection(LyXFont::LTR_DIR);
656 else if (tok == "rtl")
657 font.setDirection(LyXFont::RTL_DIR);
658 else if (tok == "default")
659 font.setDirection(LyXFont::INHERIT_DIR);
661 lex.printError("Unknown font flag "
663 } else if (token == "\\emph") {
665 font.setEmph(font.setLyXMisc(lex.GetString()));
666 } else if (token == "\\bar") {
668 string tok = lex.GetString();
669 // This is dirty, but gone with LyX3. (Asger)
671 font.setUnderbar(LyXFont::ON);
672 else if (tok == "no")
673 font.setUnderbar(LyXFont::OFF);
674 else if (tok == "default")
675 font.setUnderbar(LyXFont::INHERIT);
677 lex.printError("Unknown bar font flag "
679 } else if (token == "\\noun") {
681 font.setNoun(font.setLyXMisc(lex.GetString()));
682 } else if (token == "\\color") {
684 font.setLyXColor(lex.GetString());
685 } else if (token == "\\align") {
686 tmpret = lex.FindToken(string_align);
687 if (tmpret == -1) ++tmpret;
688 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
690 for (; tmpret > 0; --tmpret)
691 tmpret2 = tmpret2 * 2;
692 par->align = LyXAlignment(tmpret2);
694 } else if (token == "\\added_space_top") {
696 par->added_space_top = lex.GetString();
697 } else if (token == "\\added_space_bottom") {
699 par->added_space_bottom = lex.GetString();
700 } else if (token == "\\pextra_type") {
702 par->pextra_type = lex.GetInteger();
703 } else if (token == "\\pextra_width") {
705 par->pextra_width = lex.GetString();
706 } else if (token == "\\pextra_widthp") {
708 par->pextra_widthp = lex.GetString();
709 } else if (token == "\\pextra_alignment") {
711 par->pextra_alignment = lex.GetInteger();
712 } else if (token == "\\pextra_hfill") {
714 par->pextra_hfill = lex.GetInteger();
715 } else if (token == "\\pextra_start_minipage") {
717 par->pextra_start_minipage = lex.GetInteger();
718 } else if (token == "\\labelwidthstring") {
720 par->labelwidthstring = lex.GetString();
721 /* do not delete this token, it is still needed! */
722 } else if (token == "\\end_inset") {
723 /* simple ignore this. The insets do not have
725 // but insets should read it, it is a part of
726 //the inset isn't it? Lgb.
727 } else if (token == "\\begin_inset") {
729 tmptok = lex.GetString();
730 /* test the different insets */
731 if (tmptok == "Quotes") {
732 inset = new InsetQuotes;
734 par->InsertChar(pos, LyXParagraph::META_INSET);
735 par->InsertInset(pos, inset);
736 par->SetFont(pos, font);
738 } else if (tmptok == "\\i") {
739 inset = new InsetLatexAccent;
741 par->InsertChar(pos, LyXParagraph::META_INSET);
742 par->InsertInset(pos, inset);
743 par->SetFont(pos, font);
745 } else if (tmptok == "FormulaMacro") {
746 inset = new InsetFormulaMacro;
748 par->InsertChar(pos, LyXParagraph::META_INSET);
749 par->InsertInset(pos, inset);
750 par->SetFont(pos, font);
752 } else if (tmptok == "Formula") {
753 inset = new InsetFormula;
755 par->InsertChar(pos, LyXParagraph::META_INSET);
756 par->InsertInset(pos, inset);
757 par->SetFont(pos, font);
759 } else if (tmptok == "Figure") {
760 inset = new InsetFig(100, 100, this);
762 par->InsertChar(pos, LyXParagraph::META_INSET);
763 par->InsertInset(pos, inset);
764 par->SetFont(pos, font);
766 } else if (tmptok == "Info") {
767 inset = new InsetInfo;
769 par->InsertChar(pos, LyXParagraph::META_INSET);
770 par->InsertInset(pos, inset);
771 par->SetFont(pos, font);
773 } else if (tmptok == "Include") {
774 inset = new InsetInclude(string(), this);
776 par->InsertChar(pos, LyXParagraph::META_INSET);
777 par->InsertInset(pos, inset);
778 par->SetFont(pos, font);
780 } else if (tmptok == "ERT") {
781 inset = new InsetERT(this);
783 par->InsertChar(pos, LyXParagraph::META_INSET);
784 par->InsertInset(pos, inset);
785 par->SetFont(pos, font);
787 } else if (tmptok == "Text") {
788 inset = new InsetText(this);
790 par->InsertChar(pos, LyXParagraph::META_INSET);
791 par->InsertInset(pos, inset);
792 par->SetFont(pos, font);
794 } else if (tmptok == "Foot") {
795 inset = new InsetFoot(this);
797 par->InsertChar(pos, LyXParagraph::META_INSET);
798 par->InsertInset(pos, inset);
799 par->SetFont(pos, font);
801 } else if (tmptok == "GRAPHICS") {
802 inset = new InsetGraphics;
804 par->InsertChar(pos, LyXParagraph::META_INSET);
805 par->InsertInset(pos, inset);
806 par->SetFont(pos, font);
807 } else if (tmptok == "LatexCommand") {
810 if (inscmd.getCmdName() == "cite") {
811 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
812 } else if (inscmd.getCmdName() == "bibitem") {
813 lex.printError("Wrong place for bibitem");
814 inset = inscmd.Clone();
815 } else if (inscmd.getCmdName() == "BibTeX") {
816 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
817 } else if (inscmd.getCmdName() == "index") {
818 inset = new InsetIndex(inscmd.getContents());
819 } else if (inscmd.getCmdName() == "include") {
820 inset = new InsetInclude(inscmd.getContents(), this);
821 } else if (inscmd.getCmdName() == "label") {
822 inset = new InsetLabel(inscmd.getCommand());
823 } else if (inscmd.getCmdName() == "url"
824 || inscmd.getCmdName() == "htmlurl") {
825 inset = new InsetUrl(inscmd.getCommand());
826 } else if (inscmd.getCmdName() == "ref"
827 || inscmd.getCmdName() == "pageref") {
828 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
829 inset = new InsetRef(inscmd, this);
831 #warning Verify that this else clause is still needed. (Lgb)
833 // This condition comes from a
834 // temporary solution to the latexdel
835 // ref inset that was transformed to
836 // an empty ref inset plus the body
837 // surronded by latexdel insets
839 string cont, opt, tmptmptok, cmdname;
841 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
846 tmptmptok = lex.GetString();
847 if(tmptmptok[0] == '\\') {
848 if( tmptmptok == "\\backslash")
858 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
863 tmptmptok = lex.GetString();
864 if(tmptmptok[0] == '\\') {
865 if( tmptmptok == "\\backslash")
875 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
881 cmdname = "\\" + inscmd.getCmdName();
882 cmdname += "[" + cont + "]";
883 cmdname += "{" + opt + "}";
884 inset = new InsetRef(cmdname, this);
887 } else if (inscmd.getCmdName() == "tableofcontents") {
888 inset = new InsetTOC(this);
889 } else if (inscmd.getCmdName() == "listoffigures") {
890 inset = new InsetLOF(this);
891 } else if (inscmd.getCmdName() == "listofalgorithms") {
892 inset = new InsetLOA(this);
893 } else if (inscmd.getCmdName() == "listoftables") {
894 inset = new InsetLOT(this);
895 } else if (inscmd.getCmdName() == "printindex") {
896 inset = new InsetPrintIndex(this);
897 } else if (inscmd.getCmdName() == "lyxparent") {
898 inset = new InsetParent(inscmd.getContents(), this);
902 par->InsertChar(pos, LyXParagraph::META_INSET);
903 par->InsertInset(pos, inset);
904 par->SetFont(pos, font);
908 } else if (token == "\\InsetQuotes") {
909 inset = new InsetQuotes;
911 par->InsertChar(pos, LyXParagraph::META_INSET);
912 par->InsertInset(pos, inset);
913 par->SetFont(pos, font);
915 } else if (token == "\\InsetFormula") {
916 inset = new InsetFormula;
918 par->InsertChar(pos, LyXParagraph::META_INSET);
919 par->InsertInset(pos, inset);
920 par->SetFont(pos, font);
922 } else if (token == "\\SpecialChar") {
923 LyXLayout const & layout =
924 textclasslist.Style(params.textclass,
927 // Insets don't make sense in a free-spacing context! ---Kayvan
928 if (layout.free_spacing)
933 next_token = lex.GetString();
934 if (next_token == "\\-") {
935 par->InsertChar(pos, '-');
936 par->SetFont(pos, font);
937 } else if (next_token == "\\protected_separator") {
938 par->InsertChar(pos, ' ');
939 par->SetFont(pos, font);
941 lex.printError("Token `$$Token' "
943 "paragraph layout!");
950 inset = new InsetSpecialChar;
952 par->InsertChar(pos, LyXParagraph::META_INSET);
953 par->InsertInset(pos, inset);
954 par->SetFont(pos, font);
957 } else if (token == "\\Figure") {
958 inset = new InsetFig(100, 100, this);
960 par->InsertChar(pos, LyXParagraph::META_INSET);
961 par->InsertInset(pos, inset);
962 par->SetFont(pos, font);
964 } else if (token == "\\newline") { // soon obsolete
966 par->InsertChar(pos, LyXParagraph::META_NEWLINE);
967 par->SetFont(pos, font);
969 inset = new InsetSpecialChar(InsetSpecialChar::NEWLINE);
970 par->InsertChar(pos, LyXParagraph::META_INSET);
971 par->InsertInset(pos, inset);
972 par->SetFont(pos, font);
975 } else if (token == "\\LyXTable") {
976 par->table = new LyXTable(lex);
977 } else if (token == "\\hfill") {
978 par->InsertChar(pos, LyXParagraph::META_HFILL);
979 par->SetFont(pos, font);
981 } else if (token == "\\protected_separator") { // obsolete
983 LyXLayout const & layout =
984 textclasslist.Style(params.textclass,
987 if (layout.free_spacing) {
988 par->InsertChar(pos, ' ');
989 par->SetFont(pos, font);
991 inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
992 par->InsertChar(pos, LyXParagraph::META_INSET);
993 par->InsertInset(pos, inset);
994 par->SetFont(pos, font);
997 par->InsertChar(pos, LyXParagraph::META_PROTECTED_SEPARATOR);
998 par->SetFont(pos, font);
1001 } else if (token == "\\bibitem") { // ale970302
1003 par->bibkey = new InsetBibKey;
1004 par->bibkey->Read(lex);
1005 }else if (token == "\\backslash") {
1006 par->InsertChar(pos, '\\');
1007 par->SetFont(pos, font);
1009 }else if (token == "\\the_end") {
1010 the_end_read = true;
1012 // This should be insurance for the future: (Asger)
1013 lex.printError("Unknown token `$$Token'. "
1014 "Inserting as text.");
1015 int n = token.length();
1016 for (int i = 0; i < n; ++i) {
1017 par->InsertChar(pos, token[i]);
1018 par->SetFont(pos, font);
1022 return the_end_read;
1025 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1031 token = lex.GetString();
1032 if (token == "\\lyxformat") { // the first token _must_ be...
1034 format = lex.GetFloat();
1036 if (LYX_FORMAT - format > 0.05) {
1037 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1038 LYX_FORMAT, format);
1040 if (format - LYX_FORMAT > 0.05) {
1041 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1042 LYX_FORMAT, format);
1044 bool the_end = readLyXformat2(lex, par);
1045 // Formats >= 2.13 support "\the_end" marker
1052 WriteAlert(_("Warning!"),
1053 _("Reading of document is not complete"),
1054 _("Maybe the document is truncated"));
1055 // We simulate a safe reading anyways to allow
1056 // users to take the chance... (Asger)
1060 WriteAlert(_("ERROR!"),
1061 _("Old LyX file format found. "
1062 "Use LyX 0.10.x to read this!"));
1066 } else { // "\\lyxformat" not found
1067 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1070 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1076 // Should probably be moved to somewhere else: BufferView? LyXView?
1077 bool Buffer::save(bool makeBackup) const
1079 // We don't need autosaves in the immediate future. (Asger)
1080 resetAutosaveTimers();
1084 string s = fileName() + '~';
1085 // Rename is the wrong way of making a backup,
1086 // this is the correct way.
1087 /* truss cp fil fil2:
1088 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1089 stat("LyXVC.lyx", 0xEFFFF688) = 0
1090 open("LyXVC.lyx", O_RDONLY) = 3
1091 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1092 fstat(4, 0xEFFFF508) = 0
1093 fstat(3, 0xEFFFF508) = 0
1094 read(3, " # T h i s f i l e w".., 8192) = 5579
1095 write(4, " # T h i s f i l e w".., 5579) = 5579
1096 read(3, 0xEFFFD4A0, 8192) = 0
1099 chmod("LyXVC3.lyx", 0100644) = 0
1100 lseek(0, 0, SEEK_CUR) = 46440
1104 // Should proabaly have some more error checking here.
1105 // Should be cleaned up in 0.13, at least a bit.
1106 // Doing it this way, also makes the inodes stay the same.
1107 // This is still not a very good solution, in particular we
1108 // might loose the owner of the backup.
1109 FileInfo finfo(fileName());
1110 if (finfo.exist()) {
1111 mode_t fmode = finfo.getMode();
1112 struct utimbuf * times = new struct utimbuf;
1114 times->actime = finfo.getAccessTime();
1115 times->modtime = finfo.getModificationTime();
1116 ifstream ifs(fileName().c_str());
1117 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1122 ::chmod(s.c_str(), fmode);
1124 if (::utime(s.c_str(), times)) {
1125 lyxerr << "utime error." << endl;
1128 lyxerr << "LyX was not able to make "
1129 "backupcopy. Beware." << endl;
1135 if (writeFile(fileName(), false)) {
1138 // now delete the autosavefile
1139 string a = OnlyPath(fileName());
1141 a += OnlyFilename(fileName());
1143 FileInfo fileinfo(a);
1144 if (fileinfo.exist()) {
1145 if (::remove(a.c_str()) != 0) {
1146 WriteFSAlert(_("Could not delete "
1147 "auto-save file!"), a);
1151 // Saving failed, so backup is not backup
1153 string s = fileName() + '~';
1154 ::rename(s.c_str(), fileName().c_str());
1162 // Returns false if unsuccesful
1163 bool Buffer::writeFile(string const & fname, bool flag) const
1165 // if flag is false writeFile will not create any GUI
1166 // warnings, only cerr.
1167 // Needed for autosave in background or panic save (Matthias 120496)
1169 if (read_only && (fname == filename)) {
1170 // Here we should come with a question if we should
1171 // perform the write anyway.
1173 lyxerr << _("Error! Document is read-only: ")
1176 WriteAlert(_("Error! Document is read-only: "),
1181 FileInfo finfo(fname);
1182 if (finfo.exist() && !finfo.writable()) {
1183 // Here we should come with a question if we should
1184 // try to do the save anyway. (i.e. do a chmod first)
1186 lyxerr << _("Error! Cannot write file: ")
1189 WriteFSAlert(_("Error! Cannot write file: "),
1194 ofstream ofs(fname.c_str());
1197 lyxerr << _("Error! Cannot open file: ")
1200 WriteFSAlert(_("Error! Cannot open file: "),
1204 // The top of the file should not be written by params.
1206 // write out a comment in the top of the file
1207 ofs << '#' << LYX_DOCVERSION
1208 << " created this file. For more info see http://www.lyx.org/\n";
1209 ofs.setf(ios::showpoint|ios::fixed);
1211 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1213 // now write out the buffer paramters.
1214 params.writeFile(ofs);
1216 char footnoteflag = 0;
1219 // this will write out all the paragraphs
1220 // using recursive descent.
1221 paragraph->writeFile(ofs, params, footnoteflag, depth);
1223 // Write marker that shows file is complete
1224 ofs << "\n\\the_end" << endl;
1226 // how to check if close went ok?
1231 void Buffer::writeFileAscii(string const & fname, int linelen)
1233 LyXFont font1, font2;
1235 char c, footnoteflag = 0, depth = 0;
1237 LyXParagraph::size_type i;
1238 int j, h, ltype = 0, ltype_depth = 0,
1239 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1242 bool ref_printed = false;
1244 ofstream ofs(fname.c_str());
1246 WriteFSAlert(_("Error: Cannot write file:"), fname);
1250 string fname1 = TmpFileName();
1251 LyXParagraph * par = paragraph;
1255 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1257 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1259 /* begins a footnote environment ? */
1260 if (footnoteflag != par->footnoteflag) {
1261 footnoteflag = par->footnoteflag;
1263 j = strlen(string_footnotekinds[par->footnotekind])+4;
1264 if (currlinelen + j > linelen)
1267 << string_footnotekinds[par->footnotekind] << "] ";
1272 /* begins or ends a deeper area ?*/
1273 if (depth != par->depth) {
1274 if (par->depth > depth) {
1275 while (par->depth > depth) {
1280 while (par->depth < depth) {
1286 /* First write the layout */
1287 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1288 if (tmp == "Itemize") {
1290 ltype_depth = depth+1;
1291 } else if (tmp == "Enumerate") {
1293 ltype_depth = depth+1;
1294 } else if (strstr(tmp.c_str(), "ection")) {
1296 ltype_depth = depth+1;
1297 } else if (strstr(tmp.c_str(), "aragraph")) {
1299 ltype_depth = depth+1;
1300 } else if (tmp == "Description") {
1302 ltype_depth = depth+1;
1303 } else if (tmp == "Abstract") {
1306 } else if (tmp == "Bibliography") {
1314 /* maybe some vertical spaces */
1316 /* the labelwidthstring used in lists */
1320 /* some pagebreaks? */
1324 /* what about the alignment */
1327 /* dummy layout, that means a footnote ended */
1328 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1333 LyXLayout const & layout =
1334 textclasslist.Style(params.textclass,
1336 bool free_spc = layout.free_spacing;
1338 /* It might be a table */
1341 if (!lyxrc.ascii_roff_command.empty() &&
1342 lyxrc.ascii_roff_command != "none") {
1343 RoffAsciiTable(ofs, par);
1350 cells = par->table->columns;
1351 clen = new int [cells];
1352 memset(clen, 0, sizeof(int) * cells);
1354 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1355 c = par->GetChar(i);
1356 if (c == LyXParagraph::META_INSET) {
1357 if ((inset = par->GetInset(i))) {
1361 inset->Latex(ost, -1, free_spc);
1362 h += ost.str().length();
1365 inset->Latex(ost, -1, free_spc);
1367 char * tmp = ost.str();
1373 ofstream fs(fname1.c_str());
1375 WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1378 inset->Latex(fs, -1, free_spc);
1379 h += fs.tellp() - 1;
1380 ::remove(fname1.c_str());
1383 } else if (c == LyXParagraph::META_NEWLINE) {
1387 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1395 font1 = LyXFont(LyXFont::ALL_INHERIT);
1397 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1398 if (!i && !footnoteflag && !noparbreak){
1400 for(j = 0; j < depth; ++j)
1402 currlinelen = depth * 2;
1404 case 0: /* Standard */
1405 case 4: /* (Sub)Paragraph */
1406 case 5: /* Description */
1408 case 6: /* Abstract */
1409 ofs << "Abstract\n\n";
1411 case 7: /* Bibliography */
1413 ofs << "References\n\n";
1418 ofs << par->labelstring << " ";
1421 if (ltype_depth > depth) {
1422 for(j = ltype_depth - 1; j > depth; --j)
1424 currlinelen += (ltype_depth-depth)*2;
1427 for(j = 0; j < cells; ++j) {
1429 for(h = 0; h < (clen[j] + 1);
1434 for(j = 0; j < depth; ++j)
1436 currlinelen = depth * 2;
1437 if (ltype_depth > depth) {
1438 for(j = ltype_depth;
1441 currlinelen += (ltype_depth-depth)*2;
1446 font2 = par->GetFontSettings(i);
1447 if (font1.latex() != font2.latex()) {
1448 if (font2.latex() == LyXFont::OFF)
1456 c = par->GetChar(i);
1460 case LyXParagraph::META_INSET:
1461 if ((inset = par->GetInset(i))) {
1463 inset->Latex(ofs, -1, free_spc);
1464 currlinelen += (ofs.tellp() - fpos);
1465 actpos += (ofs.tellp() - fpos) - 1;
1468 case LyXParagraph::META_NEWLINE:
1470 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1471 for(j = actpos; j < clen[cell - 1]; ++j)
1474 for(j = 0; j < depth; ++j)
1476 currlinelen = depth*2;
1477 if (ltype_depth > depth) {
1478 for(j = ltype_depth; j > depth; --j)
1480 currlinelen += (ltype_depth-depth) * 2;
1482 for(j = 0; j < cells; ++j) {
1484 for(h = 0; h < (clen[j] + 1); ++h)
1488 for(j = 0; j < depth; ++j)
1490 currlinelen = depth * 2;
1491 if (ltype_depth > depth) {
1492 for(j = ltype_depth;
1495 currlinelen += (ltype_depth-depth)*2;
1501 j < clen[cell - 1]; ++j)
1507 currlinelen = actpos = 0;
1510 for(j = 0; j < depth; ++j)
1512 currlinelen = depth * 2;
1513 if (ltype_depth > depth) {
1514 for(j = ltype_depth;
1517 currlinelen += (ltype_depth - depth) * 2;
1521 case LyXParagraph::META_HFILL:
1525 case LyXParagraph::META_PROTECTED_SEPARATOR:
1533 if (currlinelen > linelen - 10
1534 && c == ' ' && i + 2 < par->size()) {
1536 for(j = 0; j < depth; ++j)
1538 currlinelen = depth * 2;
1539 if (ltype_depth > depth) {
1540 for(j = ltype_depth;
1543 currlinelen += (ltype_depth-depth)*2;
1545 } else if (c != '\0')
1548 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1554 for(j = actpos; j < clen[cell - 1]; ++j)
1557 for(j = 0; j < depth; ++j)
1559 currlinelen = depth * 2;
1560 if (ltype_depth > depth) {
1561 for(j = ltype_depth; j > depth; --j)
1563 currlinelen += (ltype_depth - depth) * 2;
1565 for(j = 0; j < cells; ++j) {
1567 for(h = 0; h < (clen[j] + 1); ++h)
1580 void Buffer::makeLaTeXFile(string const & fname,
1581 string const & original_path,
1582 bool nice, bool only_body)
1584 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1586 niceFile = nice; // this will be used by Insetincludes.
1588 tex_code_break_column = lyxrc.ascii_linelen;
1590 LyXTextClass const & tclass =
1591 textclasslist.TextClass(params.textclass);
1593 ofstream ofs(fname.c_str());
1595 WriteFSAlert(_("Error: Cannot open file: "), fname);
1599 // validate the buffer.
1600 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1601 LaTeXFeatures features(tclass.numLayouts());
1603 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1606 // The starting paragraph of the coming rows is the
1607 // first paragraph of the document. (Asger)
1608 texrow.start(paragraph, 0);
1610 if (!only_body && nice) {
1611 ofs << "%% " LYX_DOCVERSION " created this file. "
1612 "For more info, see http://www.lyx.org/.\n"
1613 "%% Do not edit unless you really know what "
1618 lyxerr.debug() << "lyx header finished" << endl;
1619 // There are a few differences between nice LaTeX and usual files:
1620 // usual is \batchmode and has a
1621 // special input@path to allow the including of figures
1622 // with either \input or \includegraphics (what figinsets do).
1623 // batchmode is not set if there is a tex_code_break_column.
1624 // In this case somebody is interested in the generated LaTeX,
1625 // so this is OK. input@path is set when the actual parameter
1626 // original_path is set. This is done for usual tex-file, but not
1627 // for nice-latex-file. (Matthias 250696)
1630 // code for usual, NOT nice-latex-file
1631 ofs << "\\batchmode\n"; // changed
1632 // from \nonstopmode
1635 if (!original_path.empty()) {
1636 ofs << "\\makeatletter\n"
1637 << "\\def\\input@path{{"
1638 << original_path << "/}}\n"
1639 << "\\makeatother\n";
1645 ofs << "\\documentclass";
1647 string options; // the document class options.
1649 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1650 // only write if existing in list (and not default)
1651 options += params.fontsize;
1656 if (!params.use_geometry &&
1657 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1658 switch (params.papersize) {
1659 case BufferParams::PAPER_A4PAPER:
1660 options += "a4paper,";
1662 case BufferParams::PAPER_USLETTER:
1663 options += "letterpaper,";
1665 case BufferParams::PAPER_A5PAPER:
1666 options += "a5paper,";
1668 case BufferParams::PAPER_B5PAPER:
1669 options += "b5paper,";
1671 case BufferParams::PAPER_EXECUTIVEPAPER:
1672 options += "executivepaper,";
1674 case BufferParams::PAPER_LEGALPAPER:
1675 options += "legalpaper,";
1681 if (params.sides != tclass.sides()) {
1682 switch (params.sides) {
1683 case LyXTextClass::OneSide:
1684 options += "oneside,";
1686 case LyXTextClass::TwoSides:
1687 options += "twoside,";
1694 if (params.columns != tclass.columns()) {
1695 if (params.columns == 2)
1696 options += "twocolumn,";
1698 options += "onecolumn,";
1701 if (!params.use_geometry
1702 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1703 options += "landscape,";
1705 // language should be a parameter to \documentclass
1706 if (params.language != "default") {
1707 if (params.language == "hebrew")
1708 options += "english,";
1709 else if (lyxrc.rtl_support)
1710 options += "hebrew,";
1711 options += params.language + ',';
1714 // the user-defined options
1715 if (!params.options.empty()) {
1716 options += params.options + ',';
1719 if (!options.empty()){
1720 options = strip(options, ',');
1721 ofs << '[' << options << ']';
1725 << textclasslist.LatexnameOfClass(params.textclass)
1728 // end of \documentclass defs
1730 // font selection must be done before loading fontenc.sty
1731 if (params.fonts != "default") {
1732 ofs << "\\usepackage{" << params.fonts << "}\n";
1735 // this one is not per buffer
1736 if (lyxrc.fontenc != "default") {
1737 ofs << "\\usepackage[" << lyxrc.fontenc
1741 if (params.inputenc != "default") {
1742 ofs << "\\usepackage[" << params.inputenc
1747 /* at the very beginning the text parameters */
1748 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1749 switch (params.paperpackage) {
1750 case BufferParams::PACKAGE_A4:
1751 ofs << "\\usepackage{a4}\n";
1754 case BufferParams::PACKAGE_A4WIDE:
1755 ofs << "\\usepackage{a4wide}\n";
1758 case BufferParams::PACKAGE_WIDEMARGINSA4:
1759 ofs << "\\usepackage[widemargins]{a4}\n";
1764 if (params.use_geometry) {
1765 ofs << "\\usepackage{geometry}\n";
1767 ofs << "\\geometry{verbose";
1768 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1769 ofs << ",landscape";
1770 switch (params.papersize2) {
1771 case BufferParams::VM_PAPER_CUSTOM:
1772 if (!params.paperwidth.empty())
1773 ofs << ",paperwidth="
1774 << params.paperwidth;
1775 if (!params.paperheight.empty())
1776 ofs << ",paperheight="
1777 << params.paperheight;
1779 case BufferParams::VM_PAPER_USLETTER:
1780 ofs << ",letterpaper";
1782 case BufferParams::VM_PAPER_USLEGAL:
1783 ofs << ",legalpaper";
1785 case BufferParams::VM_PAPER_USEXECUTIVE:
1786 ofs << ",executivepaper";
1788 case BufferParams::VM_PAPER_A3:
1791 case BufferParams::VM_PAPER_A4:
1794 case BufferParams::VM_PAPER_A5:
1797 case BufferParams::VM_PAPER_B3:
1800 case BufferParams::VM_PAPER_B4:
1803 case BufferParams::VM_PAPER_B5:
1807 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1808 switch (lyxrc.default_papersize) {
1809 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1810 case BufferParams::PAPER_USLETTER:
1811 ofs << ",letterpaper";
1813 case BufferParams::PAPER_LEGALPAPER:
1814 ofs << ",legalpaper";
1816 case BufferParams::PAPER_EXECUTIVEPAPER:
1817 ofs << ",executivepaper";
1819 case BufferParams::PAPER_A3PAPER:
1822 case BufferParams::PAPER_A4PAPER:
1825 case BufferParams::PAPER_A5PAPER:
1828 case BufferParams::PAPER_B5PAPER:
1833 if (!params.topmargin.empty())
1834 ofs << ",tmargin=" << params.topmargin;
1835 if (!params.bottommargin.empty())
1836 ofs << ",bmargin=" << params.bottommargin;
1837 if (!params.leftmargin.empty())
1838 ofs << ",lmargin=" << params.leftmargin;
1839 if (!params.rightmargin.empty())
1840 ofs << ",rmargin=" << params.rightmargin;
1841 if (!params.headheight.empty())
1842 ofs << ",headheight=" << params.headheight;
1843 if (!params.headsep.empty())
1844 ofs << ",headsep=" << params.headsep;
1845 if (!params.footskip.empty())
1846 ofs << ",footskip=" << params.footskip;
1850 if (params.use_amsmath
1851 && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1852 ofs << "\\usepackage{amsmath}\n";
1856 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1857 if (params.pagestyle == "fancy") {
1858 ofs << "\\usepackage{fancyhdr}\n";
1861 ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1865 // We try to load babel late, in case it interferes
1866 // with other packages.
1867 if (params.language != "default") {
1868 ofs << lyxrc.language_package;
1872 if (params.secnumdepth != tclass.secnumdepth()) {
1873 ofs << "\\setcounter{secnumdepth}{"
1874 << params.secnumdepth
1878 if (params.tocdepth != tclass.tocdepth()) {
1879 ofs << "\\setcounter{tocdepth}{"
1885 if (params.paragraph_separation) {
1886 switch (params.defskip.kind()) {
1887 case VSpace::SMALLSKIP:
1888 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1890 case VSpace::MEDSKIP:
1891 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1893 case VSpace::BIGSKIP:
1894 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1896 case VSpace::LENGTH:
1897 ofs << "\\setlength\\parskip{"
1898 << params.defskip.length().asLatexString()
1901 default: // should never happen // Then delete it.
1902 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1907 ofs << "\\setlength\\parindent{0pt}\n";
1911 // Now insert the LyX specific LaTeX commands...
1912 string preamble, tmppreamble;
1914 // The optional packages;
1915 preamble = features.getPackages(params);
1917 // this might be useful...
1918 preamble += "\n\\makeatletter\n\n";
1920 // Some macros LyX will need
1921 tmppreamble = features.getMacros(params);
1923 if (!tmppreamble.empty()) {
1924 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1925 "LyX specific LaTeX commands.\n"
1926 + tmppreamble + '\n';
1929 // the text class specific preamble
1930 tmppreamble = features.getTClassPreamble(params);
1931 if (!tmppreamble.empty()) {
1932 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1933 "Textclass specific LaTeX commands.\n"
1934 + tmppreamble + '\n';
1937 /* the user-defined preamble */
1938 if (!params.preamble.empty()) {
1939 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1940 "User specified LaTeX commands.\n"
1941 + params.preamble + '\n';
1944 preamble += "\\makeatother\n\n";
1946 // Itemize bullet settings need to be last in case the user
1947 // defines their own bullets that use a package included
1948 // in the user-defined preamble -- ARRae
1949 // Actually it has to be done much later than that
1950 // since some packages like frenchb make modifications
1951 // at \begin{document} time -- JMarc
1953 for (int i = 0; i < 4; ++i) {
1954 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1955 if (bullets_def.empty())
1956 bullets_def="\\AtBeginDocument{\n";
1957 bullets_def += " \\renewcommand{\\labelitemi";
1959 // `i' is one less than the item to modify
1966 bullets_def += "ii";
1972 bullets_def += "}{" +
1973 params.user_defined_bullets[i].getText()
1978 if (!bullets_def.empty())
1979 preamble += bullets_def + "}\n\n";
1981 for (int j = countChar(preamble, '\n'); j-- ;) {
1988 ofs << "\\begin{document}\n\n";
1992 lyxerr.debug() << "preamble finished, now the body." << endl;
1993 if (lyxrc.language_command_begin &&
1994 params.getDocumentDirection() == LYX_DIR_RIGHT_TO_LEFT)
1995 ofs << lyxrc.language_command_rtl;
1997 bool was_title = false;
1998 bool already_title = false;
2000 ostringstream ftnote;
2002 char * tmpholder = 0;
2007 LyXParagraph * par = paragraph;
2011 #ifndef HAVE_SSTREAM
2014 ftnote << tmpholder;
2015 delete [] tmpholder;
2020 lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
2022 LyXLayout const & layout =
2023 textclasslist.Style(params.textclass,
2026 if (layout.intitle) {
2027 if (already_title) {
2028 lyxerr <<"Error in MakeLatexFile: You"
2029 " should not mix title layouts"
2030 " with normal ones." << endl;
2033 } else if (was_title && !already_title) {
2034 ofs << "\\maketitle\n";
2036 already_title = true;
2039 // We are at depth 0 so we can just use
2040 // ordinary \footnote{} generation
2041 // flag this with ftcount
2043 if (layout.isEnvironment()
2044 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2045 par = par->TeXEnvironment(ofs, texrow,
2046 ftnote, ft_texrow, ftcount);
2048 par = par->TeXOnePar(ofs, texrow,
2049 ftnote, ft_texrow, ftcount);
2052 // Write out what we've generated...
2055 ofs << "\\addtocounter{footnote}{-"
2059 ofs << ftnote.str();
2060 texrow += ft_texrow;
2062 // The extra .c_str() is needed when we use
2063 // lyxstring instead of the STL string class.
2064 ftnote.str(string().c_str());
2066 delete [] ftnote.str();
2071 #ifndef HAVE_SSTREAM
2073 // I hate strstreams
2074 tmpholder = ftnote.str();
2078 #ifndef HAVE_SSTREAM
2079 delete [] tmpholder;
2081 // It might be that we only have a title in this document
2082 if (was_title && !already_title) {
2083 ofs << "\\maketitle\n";
2087 if (lyxrc.language_command_end &&
2088 params.getDocumentDirection() == LYX_DIR_RIGHT_TO_LEFT)
2089 ofs << lyxrc.language_command_ltr;
2092 ofs << "\\end{document}\n";
2095 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2097 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2101 // Just to be sure. (Asger)
2104 // tex_code_break_column's value is used to decide
2105 // if we are in batchmode or not (within mathed_write()
2106 // in math_write.C) so we must set it to a non-zero
2107 // value when we leave otherwise we save incorrect .lyx files.
2108 tex_code_break_column = lyxrc.ascii_linelen;
2112 lyxerr << "File was not closed properly." << endl;
2115 lyxerr.debug() << "Finished making latex file." << endl;
2119 bool Buffer::isLatex() const
2121 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2125 bool Buffer::isLinuxDoc() const
2127 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2131 bool Buffer::isLiterate() const
2133 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2137 bool Buffer::isDocBook() const
2139 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2143 bool Buffer::isSGML() const
2145 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2146 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2150 void Buffer::sgmlOpenTag(ostream & os, int depth,
2151 string const & latexname) const
2153 os << string(depth, ' ') << "<" << latexname << ">\n";
2157 void Buffer::sgmlCloseTag(ostream & os, int depth,
2158 string const & latexname) const
2160 os << string(depth, ' ') << "</" << latexname << ">\n";
2164 void Buffer::makeLinuxDocFile(string const & fname, int column)
2166 LyXParagraph * par = paragraph;
2168 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2169 string environment_stack[10];
2172 int depth = 0; /* paragraph depth */
2174 ofstream ofs(fname.c_str());
2177 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2181 tex_code_break_column = column;
2184 if (params.preamble.empty()) {
2185 ofs << "<!doctype linuxdoc system>\n\n";
2188 ofs << "<!doctype linuxdoc system \n [ "
2189 << params.preamble << " \n]>\n\n";
2192 ofs << "<!-- " << LYX_DOCVERSION
2193 << " created this file. For more info see http://www.lyx.org/"
2196 if(params.options.empty())
2197 sgmlOpenTag(ofs, 0, top_element);
2199 string top = top_element;
2201 top += params.options;
2202 sgmlOpenTag(ofs, 0, top);
2206 int desc_on = 0; /* description mode*/
2207 LyXLayout const & style =
2208 textclasslist.Style(users->buffer()->params.textclass,
2210 par->AutoDeleteInsets();
2212 /* treat <toc> as a special case for compatibility with old code */
2213 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2214 Inset * inset = par->GetInset(0);
2215 char lyx_code = inset->LyxCode();
2216 if (lyx_code == Inset::TOC_CODE){
2217 string temp = "toc";
2218 sgmlOpenTag(ofs, depth, temp);
2221 linuxDocHandleFootnote(ofs, par, depth);
2226 // environment tag closing
2227 for( ; depth > par->depth; --depth) {
2228 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2229 environment_stack[depth].clear();
2232 // write opening SGML tags
2233 switch(style.latextype) {
2234 case LATEX_PARAGRAPH:
2235 if(depth == par->depth
2236 && !environment_stack[depth].empty()) {
2237 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2238 environment_stack[depth].clear();
2244 sgmlOpenTag(ofs, depth, style.latexname());
2249 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2251 if (!environment_stack[depth].empty()){
2252 sgmlCloseTag(ofs, depth,
2253 environment_stack[depth]);
2257 environment_stack[depth].clear();
2258 sgmlOpenTag(ofs, depth, style.latexname());
2261 case LATEX_ENVIRONMENT:
2262 case LATEX_ITEM_ENVIRONMENT:
2263 if(depth == par->depth
2264 && environment_stack[depth] != style.latexname()
2265 && !environment_stack[depth].empty()) {
2267 sgmlCloseTag(ofs, depth,
2268 environment_stack[depth]);
2269 environment_stack[depth].clear();
2271 if (depth < par->depth) {
2273 environment_stack[depth].clear();
2275 if (environment_stack[depth] != style.latexname()) {
2278 sgmlOpenTag(ofs, depth, temp);
2280 environment_stack[depth] = style.latexname();
2281 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2283 if(style.latextype == LATEX_ENVIRONMENT) break;
2285 desc_on = (style.labeltype == LABEL_MANUAL);
2292 sgmlOpenTag(ofs, depth + 1, item_name);
2295 sgmlOpenTag(ofs, depth, style.latexname());
2300 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2303 linuxDocHandleFootnote(ofs, par, depth);
2305 while(par && par->IsDummy());
2308 /* write closing SGML tags */
2309 switch(style.latextype) {
2311 case LATEX_ENVIRONMENT:
2312 case LATEX_ITEM_ENVIRONMENT:
2315 sgmlCloseTag(ofs, depth, style.latexname());
2320 /* Close open tags */
2321 for(; depth > 0; --depth)
2322 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2324 if(!environment_stack[depth].empty())
2325 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2328 sgmlCloseTag(ofs, 0, top_element);
2331 // How to check for successful close
2335 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2338 string tag = "footnote";
2340 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2341 sgmlOpenTag(os, depth + 1, tag);
2342 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2343 sgmlCloseTag(os, depth + 1, tag);
2349 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2350 int const depth, int desc_on,
2351 LyXParagraph * & par)
2353 LyXParagraph * tpar = par;
2354 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2355 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2359 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2360 "Caption").second) {
2361 sgmlOpenTag(os, depth + 1, inner_tag);
2363 SimpleDocBookOnePar(os, extra_par, tpar,
2364 desc_on, depth + 2);
2365 sgmlCloseTag(os, depth+1, inner_tag);
2366 if(!extra_par.empty())
2372 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2375 string tag, inner_tag;
2376 string tmp_par, extra_par;
2377 bool inner_span = false;
2380 // Someone should give this enum a proper name (Lgb)
2388 SOME_ENUM last = NO_ONE;
2389 SOME_ENUM present = FOOTNOTE_LIKE;
2391 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2392 if(last == present) {
2394 if(!tmp_par.empty()) {
2397 sgmlCloseTag(os, depth + 1, inner_tag);
2398 sgmlOpenTag(os, depth + 1, inner_tag);
2405 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2407 if(!extra_par.empty()) os << extra_par;
2408 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2411 switch (par->footnotekind) {
2412 case LyXParagraph::FOOTNOTE:
2413 case LyXParagraph::ALGORITHM:
2416 present = FOOTNOTE_LIKE;
2419 case LyXParagraph::MARGIN:
2422 present = MARGIN_LIKE;
2425 case LyXParagraph::FIG:
2426 case LyXParagraph::WIDE_FIG:
2428 inner_tag = "title";
2432 case LyXParagraph::TAB:
2433 case LyXParagraph::WIDE_TAB:
2435 inner_tag = "title";
2440 sgmlOpenTag(os, depth, tag);
2441 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2442 DocBookHandleCaption(os, inner_tag, depth,
2446 sgmlOpenTag(os, depth + 1, inner_tag);
2449 // ignore all caption here, we processed them above!!!
2450 if (par->layout != textclasslist
2451 .NumberOfLayout(params.textclass,
2452 "Caption").second) {
2458 SimpleDocBookOnePar(ost, extra_par, par,
2459 desc_on, depth + 2);
2461 tmp_par += ost.str().c_str();
2464 char * ctmp = ost.str();
2469 tmp_par = frontStrip(strip(tmp_par));
2475 if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2476 if(!extra_par.empty()) os << extra_par;
2477 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2481 /* push a tag in a style stack */
2482 void Buffer::push_tag(ostream & os, char const * tag,
2483 int & pos, char stack[5][3])
2485 /* pop all previous tags */
2486 for (int j = pos; j >= 0; --j)
2487 os << "</" << stack[j] << ">";
2490 sprintf(stack[++pos], "%s", tag);
2493 for (int i = 0; i <= pos; ++i)
2494 os << "<" << stack[i] << ">";
2497 void Buffer::pop_tag(ostream & os, char const * tag,
2498 int & pos, char stack[5][3])
2502 // pop all tags till specified one
2503 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2504 os << "</" << stack[j] << ">";
2507 os << "</" << tag << ">";
2509 // push all tags, but the specified one
2510 for (j = j + 1; j <= pos; ++j) {
2511 os << "<" << stack[j] << ">";
2512 strcpy(stack[j-1], stack[j]);
2518 /* handle internal paragraph parsing -- layout already processed */
2520 // checks, if newcol chars should be put into this line
2521 // writes newline, if necessary.
2523 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2524 const unsigned int newcol)
2527 if (colcount > lyxrc.ascii_linelen) {
2529 colcount = newcol; // assume write after this call
2534 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2535 int desc_on, int const /*depth*/)
2537 LyXFont font1, font2;
2540 LyXParagraph::size_type main_body;
2542 LyXLayout const & style = textclasslist.Style(params.textclass,
2545 char family_type = 0; // family font flag
2546 bool is_bold = false; // series font flag
2547 char shape_type = 0; // shape font flag
2548 bool is_em = false; // emphasis (italic) font flag
2550 int stack_num = -1; // style stack position
2551 char stack[5][3]; // style stack
2552 unsigned int char_line_count = 5; // Heuristic choice ;-)
2554 if (style.labeltype != LABEL_MANUAL)
2557 main_body = par->BeginningOfMainBody();
2559 /* gets paragraph main font */
2561 font1 = style.labelfont;
2566 /* parsing main loop */
2567 for (LyXParagraph::size_type i = 0;
2568 i < par->size(); ++i) {
2570 /* handle quote tag */
2571 if (i == main_body && !par->IsDummy()) {
2576 font2 = par->getFont(i);
2578 if (font1.family() != font2.family()) {
2579 switch(family_type) {
2581 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2582 push_tag(os, "tt", stack_num, stack);
2585 else if (font2.family() == LyXFont::SANS_FAMILY) {
2586 push_tag(os, "sf", stack_num, stack);
2591 pop_tag(os, "tt", stack_num, stack);
2592 if (font2.family() == LyXFont::SANS_FAMILY) {
2593 push_tag(os, "sf", stack_num, stack);
2601 pop_tag(os, "sf", stack_num, stack);
2602 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2603 push_tag(os, "tt", stack_num, stack);
2612 /* handle bold face */
2613 if (font1.series() != font2.series()) {
2614 if (font2.series() == LyXFont::BOLD_SERIES) {
2615 push_tag(os, "bf", stack_num, stack);
2619 pop_tag(os, "bf", stack_num, stack);
2624 /* handle italic and slanted fonts */
2625 if (font1.shape() != font2.shape()) {
2626 switch(shape_type) {
2628 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2629 push_tag(os, "it", stack_num, stack);
2632 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2633 push_tag(os, "sl", stack_num, stack);
2638 pop_tag(os, "it", stack_num, stack);
2639 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2640 push_tag(os, "sl", stack_num, stack);
2648 pop_tag(os, "sl", stack_num, stack);
2649 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2650 push_tag(os, "it", stack_num, stack);
2658 /* handle <em> tag */
2659 if (font1.emph() != font2.emph()) {
2660 if (font2.emph() == LyXFont::ON) {
2661 push_tag(os, "em", stack_num, stack);
2664 pop_tag(os, "em", stack_num, stack);
2669 c = par->GetChar(i);
2671 if (font2.latex() == LyXFont::ON) {
2672 // "TeX"-Mode on == > SGML-Mode on.
2674 os << c; // see LaTeX-Generation...
2676 } else if (c == LyXParagraph::META_INSET) {
2677 inset = par->GetInset(i);
2678 inset->Linuxdoc(os);
2681 if (par->linuxDocConvertChar(c, sgml_string)
2682 && !style.free_spacing) { // in freespacing
2684 // non-breaking characters
2688 linux_doc_line_break(os, char_line_count, 6);
2693 linux_doc_line_break(os, char_line_count, 1);
2699 char_line_count += sgml_string.length();
2705 if (lyxrc.language_command_end &&
2706 params.getDocumentDirection() == LYX_DIR_RIGHT_TO_LEFT)
2707 os << lyxrc.language_command_ltr;
2709 /* needed if there is an optional argument but no contents */
2710 if (main_body > 0 && main_body == par->size()) {
2714 /* pop all defined Styles */
2715 for (j = stack_num; j >= 0; --j) {
2716 linux_doc_line_break(os,
2718 3 + strlen(stack[j]));
2719 os << "</" << stack[j] << ">";
2722 /* resets description flag correctly */
2725 /* <tag> not closed... */
2726 linux_doc_line_break(os, char_line_count, 6);
2730 /* fprintf(file, "</p>");*/
2736 /* print an error message */
2737 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2738 char const * message)
2740 InsetError * new_inset;
2742 /* insert an error marker in text */
2743 new_inset = new InsetError(message);
2744 par->InsertChar(pos, LyXParagraph::META_INSET);
2745 par->InsertInset(pos, new_inset);
2748 // This constant defines the maximum number of
2749 // environment layouts that can be nesteded.
2750 // The same applies for command layouts.
2751 // These values should be more than enough.
2752 // José Matos (1999/07/22)
2754 enum { MAX_NEST_LEVEL = 25};
2756 void Buffer::makeDocBookFile(string const & fname, int column)
2758 LyXParagraph * par = paragraph;
2760 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2761 string environment_stack[MAX_NEST_LEVEL];
2762 string environment_inner[MAX_NEST_LEVEL];
2763 string command_stack[MAX_NEST_LEVEL];
2764 bool command_flag= false;
2765 int command_depth= 0, command_base= 0, cmd_depth= 0;
2767 string item_name, command_name;
2768 string c_depth, c_params, tmps;
2770 int depth= 0; /* paragraph depth */
2772 tex_code_break_column = column;
2774 ofstream ofs(fname.c_str());
2776 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2782 ofs << "<!doctype " << top_element
2783 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2785 if (params.preamble.empty())
2788 ofs << "\n [ " << params.preamble << " \n]>\n\n";
2790 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2791 << "\n See http://www.lyx.org/ for more information -->\n";
2793 if(params.options.empty())
2794 sgmlOpenTag(ofs, 0, top_element);
2796 string top = top_element;
2798 top += params.options;
2799 sgmlOpenTag(ofs, 0, top);
2803 int desc_on = 0; /* description mode*/
2804 LyXLayout const & style =
2805 textclasslist.Style(users->buffer()->params.textclass,
2807 par->AutoDeleteInsets();
2809 /* environment tag closing */
2810 for( ; depth > par->depth; --depth) {
2811 if(environment_inner[depth] != "!-- --") {
2812 item_name= "listitem";
2813 sgmlCloseTag(ofs, command_depth + depth,
2815 if( environment_inner[depth] == "varlistentry")
2816 sgmlCloseTag(ofs, depth+command_depth,
2817 environment_inner[depth]);
2819 sgmlCloseTag(ofs, depth + command_depth,
2820 environment_stack[depth]);
2821 environment_stack[depth].clear();
2822 environment_inner[depth].clear();
2825 if(depth == par->depth
2826 && environment_stack[depth] != style.latexname()
2827 && !environment_stack[depth].empty()) {
2828 if(environment_inner[depth] != "!-- --") {
2829 item_name= "listitem";
2830 sgmlCloseTag(ofs, command_depth+depth,
2832 if( environment_inner[depth] == "varlistentry")
2834 depth + command_depth,
2835 environment_inner[depth]);
2838 sgmlCloseTag(ofs, depth + command_depth,
2839 environment_stack[depth]);
2841 environment_stack[depth].clear();
2842 environment_inner[depth].clear();
2845 // Write opening SGML tags.
2846 switch(style.latextype) {
2847 case LATEX_PARAGRAPH:
2848 if(style.latexname() != "dummy")
2849 sgmlOpenTag(ofs, depth+command_depth,
2855 LinuxDocError(par, 0,
2856 _("Error : Wrong depth for "
2857 "LatexType Command.\n"));
2859 command_name = style.latexname();
2861 tmps = style.latexparam();
2862 c_params = split(tmps, c_depth,'|');
2864 cmd_depth= atoi(c_depth.c_str());
2867 if(cmd_depth<command_base) {
2868 for(int j = command_depth;
2869 j >= command_base; --j)
2870 if(!command_stack[j].empty())
2871 sgmlCloseTag(ofs, j, command_stack[j]);
2872 command_depth= command_base= cmd_depth;
2874 else if(cmd_depth <= command_depth) {
2875 for(int j = command_depth;
2876 j >= cmd_depth; --j)
2878 if(!command_stack[j].empty())
2879 sgmlCloseTag(ofs, j, command_stack[j]);
2880 command_depth= cmd_depth;
2883 command_depth= cmd_depth;
2886 command_depth = command_base = cmd_depth;
2887 command_flag = true;
2889 command_stack[command_depth]= command_name;
2891 // treat label as a special case for
2892 // more WYSIWYM handling.
2893 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2894 Inset * inset = par->GetInset(0);
2895 char lyx_code = inset->LyxCode();
2896 if (lyx_code == Inset::LABEL_CODE){
2897 command_name += " id=\"";
2898 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2899 command_name += "\"";
2904 sgmlOpenTag(ofs, depth+command_depth, command_name);
2905 item_name = "title";
2906 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2909 case LATEX_ENVIRONMENT:
2910 case LATEX_ITEM_ENVIRONMENT:
2911 if (depth < par->depth) {
2913 environment_stack[depth].clear();
2916 if (environment_stack[depth] != style.latexname()) {
2917 environment_stack[depth] = style.latexname();
2918 environment_inner[depth] = "!-- --";
2919 sgmlOpenTag(ofs, depth + command_depth,
2920 environment_stack[depth]);
2922 if(environment_inner[depth] != "!-- --") {
2923 item_name= "listitem";
2925 command_depth + depth,
2927 if (environment_inner[depth] == "varlistentry")
2929 depth + command_depth,
2930 environment_inner[depth]);
2934 if(style.latextype == LATEX_ENVIRONMENT) {
2935 if(!style.latexparam().empty())
2936 sgmlOpenTag(ofs, depth + command_depth,
2937 style.latexparam());
2941 desc_on = (style.labeltype == LABEL_MANUAL);
2944 environment_inner[depth]= "varlistentry";
2946 environment_inner[depth]= "listitem";
2948 sgmlOpenTag(ofs, depth + 1 + command_depth,
2949 environment_inner[depth]);
2953 sgmlOpenTag(ofs, depth + 1 + command_depth,
2958 sgmlOpenTag(ofs, depth + 1 + command_depth,
2963 sgmlOpenTag(ofs, depth + command_depth,
2970 SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
2971 depth + 1 + command_depth);
2973 DocBookHandleFootnote(ofs, par,
2974 depth + 1 + command_depth);
2976 while(par && par->IsDummy());
2979 /* write closing SGML tags */
2980 switch(style.latextype) {
2983 sgmlCloseTag(ofs, depth + command_depth, end_tag);
2985 case LATEX_ENVIRONMENT:
2986 if(!style.latexparam().empty())
2987 sgmlCloseTag(ofs, depth + command_depth,
2988 style.latexparam());
2990 case LATEX_ITEM_ENVIRONMENT:
2991 if(desc_on == 1) break;
2993 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2995 case LATEX_PARAGRAPH:
2996 if(style.latexname() != "dummy")
2997 sgmlCloseTag(ofs, depth + command_depth,
3001 sgmlCloseTag(ofs, depth + command_depth,
3008 for(; depth >= 0; --depth) {
3009 if(!environment_stack[depth].empty()) {
3010 if(environment_inner[depth] != "!-- --") {
3011 item_name= "listitem";
3012 sgmlCloseTag(ofs, command_depth + depth,
3014 if( environment_inner[depth] == "varlistentry")
3015 sgmlCloseTag(ofs, depth + command_depth,
3016 environment_inner[depth]);
3019 sgmlCloseTag(ofs, depth + command_depth,
3020 environment_stack[depth]);
3024 for(int j = command_depth; j >= command_base; --j)
3025 if(!command_stack[j].empty())
3026 sgmlCloseTag(ofs, j, command_stack[j]);
3029 sgmlCloseTag(ofs, 0, top_element);
3032 // How to check for successful close
3036 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3037 LyXParagraph * par, int & desc_on,
3041 par->SimpleDocBookOneTablePar(os, extra, desc_on, depth);
3045 bool emph_flag = false;
3047 LyXLayout const & style = textclasslist.Style(params.textclass,
3050 LyXParagraph::size_type main_body;
3051 if (style.labeltype != LABEL_MANUAL)
3054 main_body = par->BeginningOfMainBody();
3056 // gets paragraph main font
3057 //if (main_body > 0)
3058 // font1 = style.labelfont;
3060 // font1 = style.font;
3061 LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3063 int char_line_count = depth;
3064 if(!style.free_spacing)
3065 for (int j = 0; j < depth; ++j)
3068 // parsing main loop
3069 for (LyXParagraph::size_type i = 0;
3070 i < par->size(); ++i) {
3071 LyXFont font2 = par->getFont(i);
3073 // handle <emphasis> tag
3074 if (font1.emph() != font2.emph() && i) {
3075 if (font2.emph() == LyXFont::ON) {
3079 os << "</emphasis>";
3084 char c = par->GetChar(i);
3086 if (c == LyXParagraph::META_INSET) {
3087 Inset * inset = par->GetInset(i);
3090 inset->DocBook(ost);
3091 string tmp_out = ost.str().c_str();
3094 inset->DocBook(ost);
3096 char * ctmp = ost.str();
3097 string tmp_out(ctmp);
3101 // This code needs some explanation:
3102 // Two insets are treated specially
3103 // label if it is the first element in a command paragraph
3105 // graphics inside tables or figure floats can't go on
3106 // title (the equivalente in latex for this case is caption
3107 // and title should come first
3110 if(desc_on!= 3 || i!= 0) {
3111 if(!tmp_out.empty() && tmp_out[0] == '@') {
3113 extra += frontStrip(tmp_out, '@');
3115 os << frontStrip(tmp_out, '@');
3120 } else if (font2.latex() == LyXFont::ON) {
3121 // "TeX"-Mode on ==> SGML-Mode on.
3128 if (par->linuxDocConvertChar(c, sgml_string)
3129 && !style.free_spacing) { // in freespacing
3131 // non-breaking characters
3135 os << "\n</term><listitem><para>";
3149 /* needed if there is an optional argument but no contents */
3150 if (main_body > 0 && main_body == par->size()) {
3154 os << "</emphasis>";
3157 /* resets description flag correctly */
3160 /* <term> not closed... */
3168 int Buffer::runLaTeX()
3170 if (!users->text) return 0;
3174 // get LaTeX-Filename
3175 string name = getLatexName();
3177 string path = OnlyPath(filename);
3179 string org_path = path;
3180 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3184 Path p(path); // path to LaTeX file
3185 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3187 // Remove all error insets
3188 bool a = users->removeAutoInsets();
3190 // Always generate the LaTeX file
3191 makeLaTeXFile(name, org_path, false);
3194 // do the LaTex run(s)
3196 string latex_command = lyxrc.pdf_mode ?
3197 lyxrc.pdflatex_command : lyxrc.latex_command;
3198 LaTeX latex(latex_command, name, filepath);
3199 int res = latex.run(terr,
3200 users->owner()->getMiniBuffer()); // running latex
3202 // check return value from latex.run().
3203 if ((res & LaTeX::NO_LOGFILE)) {
3204 WriteAlert(_("LaTeX did not work!"),
3205 _("Missing log file:"), name);
3206 } else if ((res & LaTeX::ERRORS)) {
3207 users->owner()->getMiniBuffer()->Set(_("Done"));
3208 // Insert all errors as errors boxes
3209 users->insertErrors(terr);
3211 // Dvi should also be kept dirty if the latex run
3212 // ends up with errors. However it should be possible
3213 // to view a dirty dvi too.
3215 //no errors or any other things to think about so:
3216 users->owner()->getMiniBuffer()->Set(_("Done"));
3220 // if we removed error insets before we ran LaTeX or if we inserted
3221 // error insets after we ran LaTeX this must be run:
3222 if (a || (res & LaTeX::ERRORS)){
3225 users->updateScrollbar();
3229 return latex.getNumErrors();
3233 int Buffer::runLiterate()
3235 if (!users->text) return 0;
3239 // get LaTeX-Filename
3240 string name = getLatexName();
3241 // get Literate-Filename
3242 string lit_name = ChangeExtension (getLatexName(),
3243 lyxrc.literate_extension, true);
3245 string path = OnlyPath(filename);
3247 string org_path = path;
3248 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3252 Path p(path); // path to Literate file
3253 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3255 // Remove all error insets
3256 bool a = users->removeAutoInsets();
3258 // generate the Literate file if necessary
3259 if (!isDviClean() || a) {
3260 makeLaTeXFile(lit_name, org_path, false);
3264 string latex_command = lyxrc.pdf_mode ?
3265 lyxrc.pdflatex_command : lyxrc.latex_command;
3266 Literate literate(latex_command, name, filepath,
3268 lyxrc.literate_command, lyxrc.literate_error_filter,
3269 lyxrc.build_command, lyxrc.build_error_filter);
3271 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3273 // check return value from literate.weave().
3274 if ((res & Literate::NO_LOGFILE)) {
3275 WriteAlert(_("Literate command did not work!"),
3276 _("Missing log file:"), name);
3277 } else if ((res & Literate::ERRORS)) {
3278 users->owner()->getMiniBuffer()->Set(_("Done"));
3279 // Insert all errors as errors boxes
3280 users->insertErrors(terr);
3282 // Dvi should also be kept dirty if the latex run
3283 // ends up with errors. However it should be possible
3284 // to view a dirty dvi too.
3286 //no errors or any other things to think about so:
3287 users->owner()->getMiniBuffer()->Set(_("Done"));
3291 // if we removed error insets before we ran LaTeX or if we inserted
3292 // error insets after we ran LaTeX this must be run:
3293 if (a || (res & Literate::ERRORS)){
3296 users->updateScrollbar();
3300 return literate.getNumErrors();
3304 int Buffer::buildProgram()
3306 if (!users->text) return 0;
3310 // get LaTeX-Filename
3311 string name = getLatexName();
3312 // get Literate-Filename
3313 string lit_name = ChangeExtension(getLatexName(),
3314 lyxrc.literate_extension, true);
3316 string path = OnlyPath(filename);
3318 string org_path = path;
3319 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3323 Path p(path); // path to Literate file
3324 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3326 // Remove all error insets
3327 bool a = users->removeAutoInsets();
3329 // generate the LaTeX file if necessary
3330 if (!isNwClean() || a) {
3331 makeLaTeXFile(lit_name, org_path, false);
3335 string latex_command = lyxrc.pdf_mode ?
3336 lyxrc.pdflatex_command : lyxrc.latex_command;
3337 Literate literate(latex_command, name, filepath,
3339 lyxrc.literate_command, lyxrc.literate_error_filter,
3340 lyxrc.build_command, lyxrc.build_error_filter);
3342 int res = literate.build(terr, users->owner()->getMiniBuffer());
3344 // check return value from literate.build().
3345 if ((res & Literate::NO_LOGFILE)) {
3346 WriteAlert(_("Build did not work!"),
3347 _("Missing log file:"), name);
3348 } else if ((res & Literate::ERRORS)) {
3349 users->owner()->getMiniBuffer()->Set(_("Done"));
3350 // Insert all errors as errors boxes
3351 users->insertErrors(terr);
3353 // Literate files should also be kept dirty if the literate
3354 // command run ends up with errors.
3356 //no errors or any other things to think about so:
3357 users->owner()->getMiniBuffer()->Set(_("Done"));
3361 // if we removed error insets before we ran Literate/Build or if we inserted
3362 // error insets after we ran Literate/Build this must be run:
3363 if (a || (res & Literate::ERRORS)){
3366 users->updateScrollbar();
3370 return literate.getNumErrors();
3374 // This should be enabled when the Chktex class is implemented. (Asger)
3375 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3376 // Other flags: -wall -v0 -x
3377 int Buffer::runChktex()
3379 if (!users->text) return 0;
3383 // get LaTeX-Filename
3384 string name = getLatexName();
3385 string path = OnlyPath(filename);
3387 string org_path = path;
3388 if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3392 Path p(path); // path to LaTeX file
3393 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3395 // Remove all error insets
3396 bool a = users->removeAutoInsets();
3398 // Generate the LaTeX file if neccessary
3399 if (!isDviClean() || a) {
3400 makeLaTeXFile(name, org_path, false);
3405 Chktex chktex(lyxrc.chktex_command, name, filepath);
3406 int res = chktex.run(terr); // run chktex
3409 WriteAlert(_("chktex did not work!"),
3410 _("Could not run with file:"), name);
3411 } else if (res > 0) {
3412 // Insert all errors as errors boxes
3413 users->insertErrors(terr);
3416 // if we removed error insets before we ran chktex or if we inserted
3417 // error insets after we ran chktex, this must be run:
3421 users->updateScrollbar();
3430 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
3432 LyXFont font1(LyXFont::ALL_INHERIT);
3435 LyXParagraph::size_type i;
3439 string fname1 = TmpFileName(string(), "RAT1");
3440 string fname2 = TmpFileName(string(), "RAT2");
3442 ofstream ofs(fname1.c_str());
3444 WriteAlert(_("LYX_ERROR:"),
3445 _("Cannot open temporary file:"), fname1);
3448 par->table->RoffEndOfCell(ofs, -1);
3449 for (i = 0; i < par->size(); ++i) {
3450 c = par->GetChar(i);
3451 if (par->table->IsContRow(cell)) {
3452 if (c == LyXParagraph::META_NEWLINE)
3456 font2 = par->GetFontSettings(i);
3457 if (font1.latex() != font2.latex()) {
3458 if (font2.latex() != LyXFont::OFF)
3462 case LyXParagraph::META_INSET:
3463 if ((inset = par->GetInset(i))) {
3466 stringstresm ss(ios::in | ios::out);
3467 inset->Latex(ss, -1);
3479 inset->Latex(ss, -1);
3492 fstream fs(fname2.c_str(), ios::in|ios::out);
3494 WriteAlert(_("LYX_ERROR:"),
3495 _("Cannot open temporary file:"), fname2);
3497 remove(fname1.c_str());
3500 inset->Latex(fs, -1);
3514 case LyXParagraph::META_NEWLINE:
3515 if (par->table->CellHasContRow(cell)>= 0)
3516 par->RoffContTableRows(ofs, i+1, cell);
3517 par->table->RoffEndOfCell(ofs, cell);
3520 case LyXParagraph::META_HFILL:
3523 case LyXParagraph::META_PROTECTED_SEPARATOR:
3534 << "RoffAsciiTable:"
3535 " NULL char in structure." << endl;
3539 par->table->RoffEndOfCell(ofs, cell);
3541 string cmd = lyxrc.ascii_roff_command + " >" + fname2;
3542 cmd = subst(cmd, "$$FName", fname1);
3543 Systemcalls one(Systemcalls::System, cmd);
3544 if (!(lyxerr.debugging(Debug::ROFF))) {
3545 remove(fname1.c_str());
3547 ifstream ifs(fname2.c_str());
3549 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3552 // now output the produced file
3556 WriteAlert(_("Error!"),
3557 _("Error executing *roff command on table"));
3558 // overread leading blank lines
3559 while(!ifs && (c == '\n'))
3562 for(j = 0; j < par->depth; ++j)
3564 while(!ifs && (c != '\n')) {
3569 // overread trailing blank lines
3570 while(!ifs && (c == '\n'))
3574 remove(fname2.c_str());
3579 /// changed Heinrich Bauer, 23/03/98
3580 bool Buffer::isDviClean() const
3582 if (lyxrc.use_tempdir)
3583 return dvi_clean_tmpd;
3585 return dvi_clean_orgd;
3589 /// changed Heinrich Bauer, 23/03/98
3590 void Buffer::markDviClean()
3592 if (lyxrc.use_tempdir)
3593 dvi_clean_tmpd = true;
3595 dvi_clean_orgd = true;
3599 /// changed Heinrich Bauer, 23/03/98
3600 void Buffer::markDviDirty()
3602 if (lyxrc.use_tempdir)
3603 dvi_clean_tmpd = false;
3605 dvi_clean_orgd = false;
3609 void Buffer::validate(LaTeXFeatures & features) const
3611 LyXParagraph * par = paragraph;
3612 LyXTextClass const & tclass =
3613 textclasslist.TextClass(params.textclass);
3615 // AMS Style is at document level
3617 features.amsstyle = (params.use_amsmath ||
3618 tclass.provides(LyXTextClass::amsmath));
3621 // We don't use "lyxerr.debug" because of speed. (Asger)
3622 if (lyxerr.debugging(Debug::LATEX))
3623 lyxerr << "Paragraph: " << par << endl;
3625 // Now just follow the list of paragraphs and run
3626 // validate on each of them.
3627 par->validate(features);
3629 // and then the next paragraph
3633 // the bullet shapes are buffer level not paragraph level
3634 // so they are tested here
3635 for (int i = 0; i < 4; ++i) {
3636 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3637 int font = params.user_defined_bullets[i].getFont();
3640 .user_defined_bullets[i]
3647 features.latexsym = true;
3651 features.amssymb = true;
3653 else if ((font >= 2 && font <= 5)) {
3654 features.pifont = true;
3659 if (lyxerr.debugging(Debug::LATEX)) {
3660 features.showStruct(params);
3665 void Buffer::setPaperStuff()
3667 params.papersize = BufferParams::PAPER_DEFAULT;
3668 char c1 = params.paperpackage;
3669 if (c1 == BufferParams::PACKAGE_NONE) {
3670 char c2 = params.papersize2;
3671 if (c2 == BufferParams::VM_PAPER_USLETTER)
3672 params.papersize = BufferParams::PAPER_USLETTER;
3673 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3674 params.papersize = BufferParams::PAPER_LEGALPAPER;
3675 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3676 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3677 else if (c2 == BufferParams::VM_PAPER_A3)
3678 params.papersize = BufferParams::PAPER_A3PAPER;
3679 else if (c2 == BufferParams::VM_PAPER_A4)
3680 params.papersize = BufferParams::PAPER_A4PAPER;
3681 else if (c2 == BufferParams::VM_PAPER_A5)
3682 params.papersize = BufferParams::PAPER_A5PAPER;
3683 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3684 (c2 == BufferParams::VM_PAPER_B5))
3685 params.papersize = BufferParams::PAPER_B5PAPER;
3686 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3687 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3688 params.papersize = BufferParams::PAPER_A4PAPER;
3692 // This function should be in Buffer because it's a buffer's property (ale)
3693 string Buffer::getIncludeonlyList(char delim)
3696 LyXParagraph * par = paragraph;
3697 LyXParagraph::size_type pos;
3701 while ((inset = par->ReturnNextInsetPointer(pos))){
3702 if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3703 InsetInclude * insetinc =
3704 static_cast<InsetInclude*>(inset);
3705 if (insetinc->isInclude()
3706 && insetinc->isNoLoad()) {
3709 lst += ChangeExtension(insetinc->getContents(), string(), true);
3716 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3721 // This is also a buffer property (ale)
3722 string Buffer::getReferenceList(char delim)
3724 /// if this is a child document and the parent is already loaded
3725 /// Use the parent's list instead [ale990407]
3726 if (!params.parentname.empty()
3727 && bufferlist.exists(params.parentname)) {
3728 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3730 return tmp->getReferenceList(delim);
3733 LyXParagraph * par = paragraph;
3734 LyXParagraph::size_type pos;
3739 while ((inset = par->ReturnNextInsetPointer(pos))){
3740 for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
3743 lst += inset->getLabel(i);
3749 lyxerr.debug() << "References(" << lst << ")" << endl;
3754 // This is also a buffer property (ale)
3755 string Buffer::getBibkeyList(char delim)
3757 /// if this is a child document and the parent is already loaded
3758 /// Use the parent's list instead [ale990412]
3759 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3760 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3762 return tmp->getBibkeyList(delim);
3766 LyXParagraph * par = paragraph;
3769 if (!bibkeys.empty())
3771 bibkeys += par->bibkey->getContents();
3776 // Might be either using bibtex or a child has bibliography
3777 if (bibkeys.empty()) {
3781 LyXParagraph::size_type pos = -1;
3783 // Search for Bibtex or Include inset
3784 while ((inset = par->ReturnNextInsetPointer(pos))) {
3785 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3786 if (!bibkeys.empty())
3788 bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
3789 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3790 string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
3792 if (!bibkeys.empty())
3803 lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3808 bool Buffer::isDepClean(string const & name) const
3810 DEPCLEAN * item = dep_clean;
3811 while (item && item->master != name)
3813 if (!item) return true;
3818 void Buffer::markDepClean(string const & name)
3821 dep_clean = new DEPCLEAN;
3822 dep_clean->clean = true;
3823 dep_clean->master = name;
3824 dep_clean->next = 0;
3826 DEPCLEAN* item = dep_clean;
3827 while (item && item->master != name)
3832 item = new DEPCLEAN;
3834 item->master = name;
3841 void Buffer::Dispatch(string const & command)
3843 // Split command string into command and argument
3844 string cmd, line = frontStrip(command);
3845 string arg = strip(frontStrip(split(line, cmd, ' ')));
3847 Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3851 void Buffer::Dispatch(int action, string const & argument)
3855 MenuExport(this, argument);
3859 lyxerr << "A truly unknown func!" << endl;