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 "support/filetools.h"
79 #include "support/path.h"
85 #include "LaTeXFeatures.h"
86 #include "support/syscall.h"
87 #include "support/lyxlib.h"
88 #include "support/FileInfo.h"
92 // Uncomment this line to enable a workaround for the weird behaviour
93 // of the cursor between a displayed inset and last character
94 // at the upper line. (Alejandro 20.9.96)
95 // #define BREAK_BEFORE_INSET
97 /* Lars, when changing this file sometime in the future to a list,
98 * please check out the figinsets-sideeffects described at the
99 * beginning of figinset.C Matthias (04.07.1996)
103 // all these externs should eventually be removed.
104 extern BufferList bufferlist;
106 extern void MenuExport(Buffer *, string const &);
107 extern LyXAction lyxaction;
110 static const float LYX_FORMAT = 2.15;
112 extern int tex_code_break_column;
114 extern void FreeUpdateTimer();
117 Buffer::Buffer(string const & file, LyXRC * lyxrc, bool ronly)
119 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
121 filepath = OnlyPath(file);
125 dvi_clean_orgd = false; // Heinrich Bauer, 23/03/98
126 dvi_clean_tmpd = false; // Heinrich Bauer, 23/03/98
131 if (read_only || (lyxrc && lyxrc->use_tempdir)) {
132 tmppath = CreateBufferTmpDir();
133 } else tmppath.clear();
139 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
140 // here the buffer should take care that it is
141 // saved properly, before it goes into the void.
143 // make sure that views using this buffer
148 if (!tmppath.empty()) {
149 DestroyBufferTmpDir(tmppath);
152 LyXParagraph * par = paragraph;
153 LyXParagraph * tmppar;
163 bool Buffer::saveParamsAsDefaults()
165 string fname = AddName(AddPath(user_lyxdir, "templates/"),
167 Buffer defaults = Buffer(fname);
169 // Use the current buffer's parameters as default
170 defaults.params = params;
172 // add an empty paragraph. Is this enough?
173 defaults.paragraph = new LyXParagraph;
175 return defaults.writeFile(defaults.filename, false);
179 /// Update window titles of all users
180 // Should work on a list
181 void Buffer::updateTitles() const
183 if (users) users->owner()->updateWindowTitle();
187 /// Reset autosave timer of all users
188 // Should work on a list
189 void Buffer::resetAutosaveTimers() const
191 if (users) users->owner()->resetAutosaveTimer();
195 void Buffer::fileName(string const & newfile)
197 filename = MakeAbsPath(newfile);
198 filepath = OnlyPath(filename);
199 setReadonly(IsFileWriteable(filename) == 0);
204 // candidate for move to BufferView
205 // (at least some parts in the beginning of the func)
208 // changed to be public and have one parameter
209 // if par = 0 normal behavior
210 // else insert behavior
211 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
212 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
218 char depth = 0; // signed or unsigned?
219 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
220 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
221 bool the_end_read = false;
223 LyXParagraph * return_par = 0;
224 LyXFont font(LyXFont::ALL_INHERIT);
226 // If we are inserting, we cheat and get a token in advance
227 bool has_token = false;
231 par = new LyXParagraph;
233 users->text->BreakParagraph();
234 return_par = users->text->FirstParagraph();
237 // We don't want to adopt the parameters from the
238 // document we insert, so we skip until the text begins:
241 pretoken = lex.GetString();
242 if (pretoken == "\\layout") {
254 pretoken = lex.GetString();
257 // Profiling show this should give a lot: (Asger)
258 string const token = pretoken;
262 else if (token[0] != '\\') {
263 int n = token.length();
264 for (int i = 0; i < n; ++i) {
265 par->InsertChar(pos, token[i]);
266 par->SetFont(pos, font);
269 } else if (token == "\\i") {
270 inset = new InsetLatexAccent;
272 par->InsertChar(pos, LyXParagraph::META_INSET);
274 par->InsertInset(pos, inset);
275 par->SetFont(pos, font);
277 } else if (token == "\\layout") {
281 par->text.resize(par->text.size());
282 par = new LyXParagraph(par);
286 string layoutname = lex.GetString();
287 pair<bool, LyXTextClass::LayoutList::size_type> pp
288 = textclasslist.NumberOfLayout(params.textclass,
291 par->layout = pp.second;
292 } else { // layout not found
293 // use default layout "Standard" (0)
296 // Test whether the layout is obsolete.
297 LyXLayout const & layout = textclasslist.Style(params.textclass,
299 if (!layout.obsoleted_by().empty())
301 textclasslist.NumberOfLayout(params.textclass,
302 layout.obsoleted_by()).second;
303 par->footnoteflag = footnoteflag;
304 par->footnotekind = footnotekind;
306 font = LyXFont(LyXFont::ALL_INHERIT);
307 } else if (token == "\\end_float") {
311 par->text.resize(par->text.size());
312 par = new LyXParagraph(par);
314 footnotekind = LyXParagraph::FOOTNOTE;
315 footnoteflag = LyXParagraph::NO_FOOTNOTE;
318 par->layout = LYX_DUMMY_LAYOUT;
319 font = LyXFont(LyXFont::ALL_INHERIT);
320 } else if (token == "\\begin_float") {
321 tmpret = lex.FindToken(string_footnotekinds);
322 if (tmpret == -1) ++tmpret;
323 if (tmpret != LYX_LAYOUT_DEFAULT)
324 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
325 if (footnotekind == LyXParagraph::FOOTNOTE
326 || footnotekind == LyXParagraph::MARGIN)
327 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
329 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
330 } else if (token == "\\begin_deeper") {
332 } else if (token == "\\end_deeper") {
334 lex.printError("\\end_deeper: "
335 "depth is already null");
339 } else if (token == "\\begin_preamble") {
340 params.readPreamble(lex);
341 } else if (token == "\\textclass") {
343 pair<bool, LyXTextClassList::size_type> pp =
344 textclasslist.NumberOfClass(lex.GetString());
346 params.textclass = pp.second;
348 lex.printError("Unknown textclass `$$Token'");
349 params.textclass = 0;
351 if (!textclasslist.Load(params.textclass)) {
352 // if the textclass wasn't loaded properly
353 // we need to either substitute another
354 // or stop loading the file.
355 // I can substitute but I don't see how I can
356 // stop loading... ideas?? ARRae980418
357 WriteAlert(_("Textclass Loading Error!"),
358 string(_("Can't load textclass ")) +
359 textclasslist.NameOfClass(params.textclass),
360 _("-- substituting default"));
361 params.textclass = 0;
363 } else if (token == "\\options") {
365 params.options = lex.GetString();
366 } else if (token == "\\language") {
367 params.readLanguage(lex);
368 } else if (token == "\\fontencoding") {
370 } else if (token == "\\inputencoding") {
372 params.inputenc = lex.GetString();
373 } else if (token == "\\graphics") {
374 params.readGraphicsDriver(lex);
375 } else if (token == "\\fontscheme") {
377 params.fonts = lex.GetString();
378 } else if (token == "\\noindent") {
379 par->noindent = true;
380 } else if (token == "\\fill_top") {
381 par->added_space_top = VSpace(VSpace::VFILL);
382 } else if (token == "\\fill_bottom") {
383 par->added_space_bottom = VSpace(VSpace::VFILL);
384 } else if (token == "\\line_top") {
385 par->line_top = true;
386 } else if (token == "\\line_bottom") {
387 par->line_bottom = true;
388 } else if (token == "\\pagebreak_top") {
389 par->pagebreak_top = true;
390 } else if (token == "\\pagebreak_bottom") {
391 par->pagebreak_bottom = true;
392 } else if (token == "\\start_of_appendix") {
393 par->start_of_appendix = true;
394 } else if (token == "\\paragraph_separation") {
395 tmpret = lex.FindToken(string_paragraph_separation);
396 if (tmpret == -1) ++tmpret;
397 if (tmpret != LYX_LAYOUT_DEFAULT)
398 params.paragraph_separation =
399 static_cast<BufferParams::PARSEP>(tmpret);
400 } else if (token == "\\defskip") {
402 params.defskip = VSpace(lex.GetString());
403 } else if (token == "\\no_isolatin1") { // obsolete
405 } else if (token == "\\no_babel") { // obsolete
407 } else if (token == "\\no_epsfig") { // obsolete
409 } else if (token == "\\epsfig") { // obsolete
410 // Indeed it is obsolete, but we HAVE to be backwards
411 // compatible until 0.14, because otherwise all figures
412 // in existing documents are irretrivably lost. (Asger)
413 params.readGraphicsDriver(lex);
414 } else if (token == "\\quotes_language") {
415 tmpret = lex.FindToken(string_quotes_language);
416 if (tmpret == -1) ++tmpret;
417 if (tmpret != LYX_LAYOUT_DEFAULT) {
418 InsetQuotes::quote_language tmpl =
419 InsetQuotes::EnglishQ;
422 tmpl = InsetQuotes::EnglishQ;
425 tmpl = InsetQuotes::SwedishQ;
428 tmpl = InsetQuotes::GermanQ;
431 tmpl = InsetQuotes::PolishQ;
434 tmpl = InsetQuotes::FrenchQ;
437 tmpl = InsetQuotes::DanishQ;
440 params.quotes_language = tmpl;
442 } else if (token == "\\quotes_times") {
444 switch(lex.GetInteger()) {
446 params.quotes_times = InsetQuotes::SingleQ;
449 params.quotes_times = InsetQuotes::DoubleQ;
452 } else if (token == "\\papersize") {
453 tmpret = lex.FindToken(string_papersize);
457 params.papersize2 = tmpret;
458 } else if (token == "\\paperpackage") {
459 tmpret = lex.FindToken(string_paperpackages);
462 params.paperpackage = BufferParams::PACKAGE_NONE;
464 params.paperpackage = tmpret;
465 } else if (token == "\\use_geometry") {
467 params.use_geometry = lex.GetInteger();
468 } else if (token == "\\use_amsmath") {
470 params.use_amsmath = lex.GetInteger();
471 } else if (token == "\\paperorientation") {
472 tmpret = lex.FindToken(string_orientation);
473 if (tmpret == -1) ++tmpret;
474 if (tmpret != LYX_LAYOUT_DEFAULT)
475 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
476 } else if (token == "\\paperwidth") {
478 params.paperwidth = lex.GetString();
479 } else if (token == "\\paperheight") {
481 params.paperheight = lex.GetString();
482 } else if (token == "\\leftmargin") {
484 params.leftmargin = lex.GetString();
485 } else if (token == "\\topmargin") {
487 params.topmargin = lex.GetString();
488 } else if (token == "\\rightmargin") {
490 params.rightmargin = lex.GetString();
491 } else if (token == "\\bottommargin") {
493 params.bottommargin = lex.GetString();
494 } else if (token == "\\headheight") {
496 params.headheight = lex.GetString();
497 } else if (token == "\\headsep") {
499 params.headsep = lex.GetString();
500 } else if (token == "\\footskip") {
502 params.footskip = lex.GetString();
503 } else if (token == "\\paperfontsize") {
505 params.fontsize = strip(lex.GetString());
506 } else if (token == "\\papercolumns") {
508 params.columns = lex.GetInteger();
509 } else if (token == "\\papersides") {
511 switch(lex.GetInteger()) {
513 case 1: params.sides = LyXTextClass::OneSide; break;
514 case 2: params.sides = LyXTextClass::TwoSides; break;
516 } else if (token == "\\paperpagestyle") {
518 params.pagestyle = strip(lex.GetString());
519 } else if (token == "\\bullet") {
521 int index = lex.GetInteger();
523 int temp_int = lex.GetInteger();
524 params.user_defined_bullets[index].setFont(temp_int);
525 params.temp_bullets[index].setFont(temp_int);
527 temp_int = lex.GetInteger();
528 params.user_defined_bullets[index].setCharacter(temp_int);
529 params.temp_bullets[index].setCharacter(temp_int);
531 temp_int = lex.GetInteger();
532 params.user_defined_bullets[index].setSize(temp_int);
533 params.temp_bullets[index].setSize(temp_int);
535 string temp_str = lex.GetString();
536 if (temp_str != "\\end_bullet") {
537 // this element isn't really necessary for
538 // parsing but is easier for humans
539 // to understand bullets. Put it back and
540 // set a debug message?
541 lex.printError("\\end_bullet expected, got" + temp_str);
542 //how can I put it back?
544 } else if (token == "\\bulletLaTeX") {
546 int index = lex.GetInteger();
548 string temp_str = lex.GetString(), sum_str;
549 while (temp_str != "\\end_bullet") {
550 // this loop structure is needed when user
551 // enters an empty string since the first
552 // thing returned will be the \\end_bullet
554 // if the LaTeX entry has spaces. Each element
555 // therefore needs to be read in turn
558 temp_str = lex.GetString();
560 params.user_defined_bullets[index].setText(sum_str);
561 params.temp_bullets[index].setText(sum_str);
562 } else if (token == "\\secnumdepth") {
564 params.secnumdepth = lex.GetInteger();
565 } else if (token == "\\tocdepth") {
567 params.tocdepth = lex.GetInteger();
568 } else if (token == "\\baselinestretch") { // obsolete
569 lex.nextToken(); // should not be used directly
571 // Will probably keep a kind of support just for
573 params.spacing.set(Spacing::Other, lex.GetFloat());
574 } else if (token == "\\spacing") {
576 string tmp = strip(lex.GetString());
577 if (tmp == "single") {
578 params.spacing.set(Spacing::Single);
579 } else if (tmp == "onehalf") {
580 params.spacing.set(Spacing::Onehalf);
581 } else if (tmp == "double") {
582 params.spacing.set(Spacing::Double);
583 } else if (tmp == "other") {
585 params.spacing.set(Spacing::Other,
588 lex.printError("Unknown spacing token: '$$Token'");
590 } else if (token == "\\float_placement") {
592 params.float_placement = lex.GetString();
593 } else if (token == "\\cursor") { // obsolete
594 // this is obsolete, so we just skip it.
596 } else if (token == "\\family") {
598 font.setLyXFamily(lex.GetString());
599 } else if (token == "\\series") {
601 font.setLyXSeries(lex.GetString());
602 } else if (token == "\\shape") {
604 font.setLyXShape(lex.GetString());
605 } else if (token == "\\size") {
607 font.setLyXSize(lex.GetString());
608 } else if (token == "\\latex") {
610 string tok = lex.GetString();
611 // This is dirty, but gone with LyX3. (Asger)
612 if (tok == "no_latex")
613 font.setLatex(LyXFont::OFF);
614 else if (tok == "latex")
615 font.setLatex(LyXFont::ON);
616 else if (tok == "default")
617 font.setLatex(LyXFont::INHERIT);
619 lex.printError("Unknown LaTeX font flag "
621 } else if (token == "\\direction") {
623 string tok = lex.GetString();
625 font.setDirection(LyXFont::LTR_DIR);
626 else if (tok == "rtl")
627 font.setDirection(LyXFont::RTL_DIR);
628 else if (tok == "default")
629 font.setDirection(LyXFont::INHERIT_DIR);
631 lex.printError("Unknown font flag "
633 } else if (token == "\\emph") {
635 font.setEmph(font.setLyXMisc(lex.GetString()));
636 } else if (token == "\\bar") {
638 string tok = lex.GetString();
639 // This is dirty, but gone with LyX3. (Asger)
641 font.setUnderbar(LyXFont::ON);
642 else if (tok == "no")
643 font.setUnderbar(LyXFont::OFF);
644 else if (tok == "default")
645 font.setUnderbar(LyXFont::INHERIT);
647 lex.printError("Unknown bar font flag "
649 } else if (token == "\\noun") {
651 font.setNoun(font.setLyXMisc(lex.GetString()));
652 } else if (token == "\\color") {
654 font.setLyXColor(lex.GetString());
655 } else if (token == "\\align") {
656 tmpret = lex.FindToken(string_align);
657 if (tmpret == -1) ++tmpret;
658 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
660 for (; tmpret > 0; --tmpret)
661 tmpret2 = tmpret2 * 2;
662 par->align = LyXAlignment(tmpret2);
664 } else if (token == "\\added_space_top") {
666 par->added_space_top = lex.GetString();
667 } else if (token == "\\added_space_bottom") {
669 par->added_space_bottom = lex.GetString();
670 } else if (token == "\\pextra_type") {
672 par->pextra_type = lex.GetInteger();
673 } else if (token == "\\pextra_width") {
675 par->pextra_width = lex.GetString();
676 } else if (token == "\\pextra_widthp") {
678 par->pextra_widthp = lex.GetString();
679 } else if (token == "\\pextra_alignment") {
681 par->pextra_alignment = lex.GetInteger();
682 } else if (token == "\\pextra_hfill") {
684 par->pextra_hfill = lex.GetInteger();
685 } else if (token == "\\pextra_start_minipage") {
687 par->pextra_start_minipage = lex.GetInteger();
688 } else if (token == "\\labelwidthstring") {
690 par->labelwidthstring = lex.GetString();
691 /* do not delete this token, it is still needed! */
692 } else if (token == "\\end_inset") {
693 /* simple ignore this. The insets do not have
695 // but insets should read it, it is a part of
696 //the inset isn't it? Lgb.
697 } else if (token == "\\begin_inset") {
699 tmptok = lex.GetString();
700 /* test the different insets */
701 if (tmptok == "Quotes") {
702 inset = new InsetQuotes;
704 par->InsertChar(pos, LyXParagraph::META_INSET);
705 par->InsertInset(pos, inset);
706 par->SetFont(pos, font);
708 } else if (tmptok == "\\i") {
709 inset = new InsetLatexAccent;
711 par->InsertChar(pos, LyXParagraph::META_INSET);
712 par->InsertInset(pos, inset);
713 par->SetFont(pos, font);
715 } else if (tmptok == "FormulaMacro") {
716 inset = new InsetFormulaMacro;
718 par->InsertChar(pos, LyXParagraph::META_INSET);
719 par->InsertInset(pos, inset);
720 par->SetFont(pos, font);
722 } else if (tmptok == "Formula") {
723 inset = new InsetFormula;
725 par->InsertChar(pos, LyXParagraph::META_INSET);
726 par->InsertInset(pos, inset);
727 par->SetFont(pos, font);
729 } else if (tmptok == "Figure") {
730 inset = new InsetFig(100, 100, this);
732 par->InsertChar(pos, LyXParagraph::META_INSET);
733 par->InsertInset(pos, inset);
734 par->SetFont(pos, font);
736 } else if (tmptok == "Info") {
737 inset = new InsetInfo;
739 par->InsertChar(pos, LyXParagraph::META_INSET);
740 par->InsertInset(pos, inset);
741 par->SetFont(pos, font);
743 } else if (tmptok == "Include") {
744 inset = new InsetInclude(string(), this);
746 par->InsertChar(pos, LyXParagraph::META_INSET);
747 par->InsertInset(pos, inset);
748 par->SetFont(pos, font);
750 } else if (tmptok == "ERT") {
751 inset = new InsetERT(this);
753 par->InsertChar(pos, LyXParagraph::META_INSET);
754 par->InsertInset(pos, inset);
755 par->SetFont(pos, font);
757 } else if (tmptok == "Text") {
758 inset = new InsetText(this);
760 par->InsertChar(pos, LyXParagraph::META_INSET);
761 par->InsertInset(pos, inset);
762 par->SetFont(pos, font);
764 } else if (tmptok == "LatexCommand") {
767 if (inscmd.getCmdName() == "cite") {
768 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
769 } else if (inscmd.getCmdName() == "bibitem") {
770 lex.printError("Wrong place for bibitem");
771 inset = inscmd.Clone();
772 } else if (inscmd.getCmdName() == "BibTeX") {
773 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
774 } else if (inscmd.getCmdName() == "index") {
775 inset = new InsetIndex(inscmd.getContents());
776 } else if (inscmd.getCmdName() == "include") {
777 inset = new InsetInclude(inscmd.getContents(), this);
778 } else if (inscmd.getCmdName() == "label") {
779 inset = new InsetLabel(inscmd.getCommand());
780 } else if (inscmd.getCmdName() == "url"
781 || inscmd.getCmdName() == "htmlurl") {
782 inset = new InsetUrl(inscmd.getCommand());
783 } else if (inscmd.getCmdName() == "ref"
784 || inscmd.getCmdName() == "pageref") {
785 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
786 inset = new InsetRef(inscmd, this);
788 #warning Verify that this else clause is still needed. (Lgb)
789 // This condition comes from a
790 // temporary solution to the latexdel
791 // ref inset that was transformed to
792 // an empty ref inset plus the body
793 // surronded by latexdel insets
795 string cont, opt, tmptmptok, cmdname;
797 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
802 tmptmptok = lex.GetString();
803 if(tmptmptok[0] == '\\') {
804 if( tmptmptok == "\\backslash")
814 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
819 tmptmptok = lex.GetString();
820 if(tmptmptok[0] == '\\') {
821 if( tmptmptok == "\\backslash")
831 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
837 cmdname = "\\" + inscmd.getCmdName();
838 cmdname += "[" + cont + "]";
839 cmdname += "{" + opt + "}";
840 inset = new InsetRef(cmdname, this);
842 } else if (inscmd.getCmdName() == "tableofcontents") {
843 inset = new InsetTOC(this);
844 } else if (inscmd.getCmdName() == "listoffigures") {
845 inset = new InsetLOF(this);
846 } else if (inscmd.getCmdName() == "listofalgorithms") {
847 inset = new InsetLOA(this);
848 } else if (inscmd.getCmdName() == "listoftables") {
849 inset = new InsetLOT(this);
850 } else if (inscmd.getCmdName() == "printindex") {
851 inset = new InsetPrintIndex(this);
852 } else if (inscmd.getCmdName() == "lyxparent") {
853 inset = new InsetParent(inscmd.getContents(), this);
857 par->InsertChar(pos, LyXParagraph::META_INSET);
858 par->InsertInset(pos, inset);
859 par->SetFont(pos, font);
863 } else if (token == "\\InsetQuotes") {
864 inset = new InsetQuotes;
866 par->InsertChar(pos, LyXParagraph::META_INSET);
867 par->InsertInset(pos, inset);
868 par->SetFont(pos, font);
870 } else if (token == "\\InsetFormula") {
871 inset = new InsetFormula;
873 par->InsertChar(pos, LyXParagraph::META_INSET);
874 par->InsertInset(pos, inset);
875 par->SetFont(pos, font);
877 } else if (token == "\\SpecialChar") {
878 inset = new InsetSpecialChar;
880 par->InsertChar(pos, LyXParagraph::META_INSET);
881 par->InsertInset(pos, inset);
882 par->SetFont(pos, font);
884 } else if (token == "\\Figure") {
885 inset = new InsetFig(100, 100, this);
887 par->InsertChar(pos, LyXParagraph::META_INSET);
888 par->InsertInset(pos, inset);
889 par->SetFont(pos, font);
891 } else if (token == "\\newline") {
892 par->InsertChar(pos, LyXParagraph::META_NEWLINE);
893 par->SetFont(pos, font);
895 } else if (token == "\\LyXTable") {
896 par->table = new LyXTable(lex);
897 } else if (token == "\\hfill") {
898 par->InsertChar(pos, LyXParagraph::META_HFILL);
899 par->SetFont(pos, font);
901 } else if (token == "\\protected_separator") {
902 par->InsertChar(pos, LyXParagraph::META_PROTECTED_SEPARATOR);
903 par->SetFont(pos, font);
905 } else if (token == "\\bibitem") { // ale970302
907 par->bibkey = new InsetBibKey;
908 par->bibkey->Read(lex);
909 }else if (token == "\\backslash") {
910 par->InsertChar(pos, '\\');
911 par->SetFont(pos, font);
913 }else if (token == "\\the_end") {
916 // This should be insurance for the future: (Asger)
917 lex.printError("Unknown token `$$Token'. "
918 "Inserting as text.");
919 int n = token.length();
920 for (int i = 0; i < n; ++i) {
921 par->InsertChar(pos, token[i]);
922 par->SetFont(pos, font);
931 paragraph = return_par;
937 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
943 token = lex.GetString();
944 if (token == "\\lyxformat") { // the first token _must_ be...
946 format = lex.GetFloat();
948 if (LYX_FORMAT - format > 0.05) {
949 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
952 if (format - LYX_FORMAT > 0.05) {
953 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
956 bool the_end = readLyXformat2(lex, par);
957 // Formats >= 2.13 support "\the_end" marker
964 WriteAlert(_("Warning!"),
965 _("Reading of document is not complete"),
966 _("Maybe the document is truncated"));
967 // We simulate a safe reading anyways to allow
968 // users to take the chance... (Asger)
972 WriteAlert(_("ERROR!"),
973 _("Old LyX file format found. "
974 "Use LyX 0.10.x to read this!"));
978 } else { // "\\lyxformat" not found
979 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
982 WriteAlert(_("ERROR!"), _("Unable to read file!"));
988 // Should probably be moved to somewhere else: BufferView? LyXView?
989 bool Buffer::save(bool makeBackup) const
991 // We don't need autosaves in the immediate future. (Asger)
992 resetAutosaveTimers();
996 string s = fileName() + '~';
997 // Rename is the wrong way of making a backup,
998 // this is the correct way.
999 /* truss cp fil fil2:
1000 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1001 stat("LyXVC.lyx", 0xEFFFF688) = 0
1002 open("LyXVC.lyx", O_RDONLY) = 3
1003 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1004 fstat(4, 0xEFFFF508) = 0
1005 fstat(3, 0xEFFFF508) = 0
1006 read(3, " # T h i s f i l e w".., 8192) = 5579
1007 write(4, " # T h i s f i l e w".., 5579) = 5579
1008 read(3, 0xEFFFD4A0, 8192) = 0
1011 chmod("LyXVC3.lyx", 0100644) = 0
1012 lseek(0, 0, SEEK_CUR) = 46440
1016 // Should proabaly have some more error checking here.
1017 // Should be cleaned up in 0.13, at least a bit.
1018 // Doing it this way, also makes the inodes stay the same.
1019 // This is still not a very good solution, in particular we
1020 // might loose the owner of the backup.
1021 FileInfo finfo(fileName());
1022 if (finfo.exist()) {
1023 mode_t fmode = finfo.getMode();
1024 struct utimbuf * times = new struct utimbuf;
1026 times->actime = finfo.getAccessTime();
1027 times->modtime = finfo.getModificationTime();
1028 ifstream ifs(fileName().c_str());
1029 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1034 ::chmod(s.c_str(), fmode);
1036 if (::utime(s.c_str(), times)) {
1037 lyxerr << "utime error." << endl;
1040 lyxerr << "LyX was not able to make "
1041 "backupcopy. Beware." << endl;
1047 if (writeFile(fileName(), false)) {
1050 // now delete the autosavefile
1051 string a = OnlyPath(fileName());
1053 a += OnlyFilename(fileName());
1055 FileInfo fileinfo(a);
1056 if (fileinfo.exist()) {
1057 if (::remove(a.c_str()) != 0) {
1058 WriteFSAlert(_("Could not delete "
1059 "auto-save file!"), a);
1063 // Saving failed, so backup is not backup
1065 string s = fileName() + '~';
1066 ::rename(s.c_str(), fileName().c_str());
1074 // Returns false if unsuccesful
1075 bool Buffer::writeFile(string const & fname, bool flag) const
1077 // if flag is false writeFile will not create any GUI
1078 // warnings, only cerr.
1079 // Needed for autosave in background or panic save (Matthias 120496)
1081 if (read_only && (fname == filename)) {
1082 // Here we should come with a question if we should
1083 // perform the write anyway.
1085 lyxerr << _("Error! Document is read-only: ")
1088 WriteAlert(_("Error! Document is read-only: "),
1093 FileInfo finfo(fname);
1094 if (finfo.exist() && !finfo.writable()) {
1095 // Here we should come with a question if we should
1096 // try to do the save anyway. (i.e. do a chmod first)
1098 lyxerr << _("Error! Cannot write file: ")
1101 WriteFSAlert(_("Error! Cannot write file: "),
1106 ofstream ofs(fname.c_str());
1109 lyxerr << _("Error! Cannot open file: ")
1112 WriteFSAlert(_("Error! Cannot open file: "),
1116 // The top of the file should not be written by params.
1118 // write out a comment in the top of the file
1119 ofs << '#' << LYX_DOCVERSION
1120 << " created this file. For more info see http://www.lyx.org/\n";
1121 ofs.setf(ios::showpoint|ios::fixed);
1123 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1125 // now write out the buffer paramters.
1126 params.writeFile(ofs);
1128 char footnoteflag = 0;
1131 // this will write out all the paragraphs
1132 // using recursive descent.
1133 paragraph->writeFile(ofs, params, footnoteflag, depth);
1135 // Write marker that shows file is complete
1136 ofs << "\n\\the_end" << endl;
1138 // how to check if close went ok?
1143 void Buffer::writeFileAscii(string const & fname, int linelen)
1145 LyXFont font1, font2;
1147 char c, footnoteflag = 0, depth = 0;
1149 LyXParagraph::size_type i;
1150 int j, h, ltype = 0, ltype_depth = 0,
1151 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1154 bool ref_printed = false;
1156 ofstream ofs(fname.c_str());
1158 WriteFSAlert(_("Error: Cannot write file:"), fname);
1162 string fname1 = TmpFileName();
1163 LyXParagraph * par = paragraph;
1167 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1169 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1171 /* begins a footnote environment ? */
1172 if (footnoteflag != par->footnoteflag) {
1173 footnoteflag = par->footnoteflag;
1175 j = strlen(string_footnotekinds[par->footnotekind])+4;
1176 if (currlinelen + j > linelen)
1179 << string_footnotekinds[par->footnotekind] << "] ";
1184 /* begins or ends a deeper area ?*/
1185 if (depth != par->depth) {
1186 if (par->depth > depth) {
1187 while (par->depth > depth) {
1192 while (par->depth < depth) {
1198 /* First write the layout */
1199 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1200 if (tmp == "Itemize") {
1202 ltype_depth = depth+1;
1203 } else if (tmp == "Enumerate") {
1205 ltype_depth = depth+1;
1206 } else if (strstr(tmp.c_str(), "ection")) {
1208 ltype_depth = depth+1;
1209 } else if (strstr(tmp.c_str(), "aragraph")) {
1211 ltype_depth = depth+1;
1212 } else if (tmp == "Description") {
1214 ltype_depth = depth+1;
1215 } else if (tmp == "Abstract") {
1218 } else if (tmp == "Bibliography") {
1226 /* maybe some vertical spaces */
1228 /* the labelwidthstring used in lists */
1232 /* some pagebreaks? */
1236 /* what about the alignment */
1239 /* dummy layout, that means a footnote ended */
1240 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1245 /* It might be a table */
1248 if (!lyxrc->ascii_roff_command.empty() &&
1249 lyxrc->ascii_roff_command != "none") {
1250 RoffAsciiTable(ofs, par);
1257 cells = par->table->columns;
1258 clen = new int [cells];
1259 memset(clen, 0, sizeof(int) * cells);
1260 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1261 c = par->GetChar(i);
1262 if (c == LyXParagraph::META_INSET) {
1263 if ((inset = par->GetInset(i))) {
1264 ofstream fs(fname1.c_str());
1266 WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1269 inset->Latex(fs, -1);
1270 h += fs.tellp() - 1;
1271 remove(fname1.c_str());
1273 } else if (c == LyXParagraph::META_NEWLINE) {
1277 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1285 font1 = LyXFont(LyXFont::ALL_INHERIT);
1287 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1288 if (!i && !footnoteflag && !noparbreak){
1290 for(j = 0; j < depth; ++j)
1292 currlinelen = depth * 2;
1294 case 0: /* Standard */
1295 case 4: /* (Sub)Paragraph */
1296 case 5: /* Description */
1298 case 6: /* Abstract */
1299 ofs << "Abstract\n\n";
1301 case 7: /* Bibliography */
1303 ofs << "References\n\n";
1308 ofs << par->labelstring << " ";
1311 if (ltype_depth > depth) {
1312 for(j = ltype_depth - 1; j > depth; --j)
1314 currlinelen += (ltype_depth-depth)*2;
1317 for(j = 0; j < cells; ++j) {
1319 for(h = 0; h < (clen[j] + 1);
1324 for(j = 0; j < depth; ++j)
1326 currlinelen = depth * 2;
1327 if (ltype_depth > depth) {
1328 for(j = ltype_depth;
1331 currlinelen += (ltype_depth-depth)*2;
1336 font2 = par->GetFontSettings(i);
1337 if (font1.latex() != font2.latex()) {
1338 if (font2.latex() == LyXFont::OFF)
1346 c = par->GetChar(i);
1350 case LyXParagraph::META_INSET:
1351 if ((inset = par->GetInset(i))) {
1353 inset->Latex(ofs, -1);
1354 currlinelen += (ofs.tellp() - fpos);
1355 actpos += (ofs.tellp() - fpos) - 1;
1358 case LyXParagraph::META_NEWLINE:
1360 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1361 for(j = actpos; j < clen[cell - 1]; ++j)
1364 for(j = 0; j < depth; ++j)
1366 currlinelen = depth*2;
1367 if (ltype_depth > depth) {
1368 for(j = ltype_depth; j > depth; --j)
1370 currlinelen += (ltype_depth-depth) * 2;
1372 for(j = 0; j < cells; ++j) {
1374 for(h = 0; h < (clen[j] + 1); ++h)
1378 for(j = 0; j < depth; ++j)
1380 currlinelen = depth * 2;
1381 if (ltype_depth > depth) {
1382 for(j = ltype_depth;
1385 currlinelen += (ltype_depth-depth)*2;
1391 j < clen[cell - 1]; ++j)
1397 currlinelen = actpos = 0;
1400 for(j = 0; j < depth; ++j)
1402 currlinelen = depth * 2;
1403 if (ltype_depth > depth) {
1404 for(j = ltype_depth;
1407 currlinelen += (ltype_depth - depth) * 2;
1411 case LyXParagraph::META_HFILL:
1414 case LyXParagraph::META_PROTECTED_SEPARATOR:
1421 if (currlinelen > linelen - 10
1422 && c == ' ' && i + 2 < par->size()) {
1424 for(j = 0; j < depth; ++j)
1426 currlinelen = depth * 2;
1427 if (ltype_depth > depth) {
1428 for(j = ltype_depth;
1431 currlinelen += (ltype_depth-depth)*2;
1433 } else if (c != '\0')
1436 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1442 for(j = actpos; j < clen[cell - 1]; ++j)
1445 for(j = 0; j < depth; ++j)
1447 currlinelen = depth * 2;
1448 if (ltype_depth > depth) {
1449 for(j = ltype_depth; j > depth; --j)
1451 currlinelen += (ltype_depth - depth) * 2;
1453 for(j = 0; j < cells; ++j) {
1455 for(h = 0; h < (clen[j] + 1); ++h)
1468 void Buffer::makeLaTeXFile(string const & fname,
1469 string const & original_path,
1470 bool nice, bool only_body)
1472 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1474 niceFile = nice; // this will be used by Insetincludes.
1476 tex_code_break_column = lyxrc->ascii_linelen;
1478 LyXTextClass const & tclass =
1479 textclasslist.TextClass(params.textclass);
1481 ofstream ofs(fname.c_str());
1483 WriteFSAlert(_("Error: Cannot open file: "), fname);
1487 // validate the buffer.
1488 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1489 LaTeXFeatures features(tclass.numLayouts());
1491 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1494 // The starting paragraph of the coming rows is the
1495 // first paragraph of the document. (Asger)
1496 texrow.start(paragraph, 0);
1500 if (!only_body && nice) {
1501 LFile += "%% " LYX_DOCVERSION " created this file. "
1502 "For more info, see http://www.lyx.org/.\n";
1503 LFile += "%% Do not edit unless you really know what you are doing.\n";
1507 lyxerr.debug() << "lyx header finished" << endl;
1508 // There are a few differences between nice LaTeX and usual files:
1509 // usual is \batchmode and has a
1510 // special input@path to allow the including of figures
1511 // with either \input or \includegraphics (what figinsets do).
1512 // batchmode is not set if there is a tex_code_break_column.
1513 // In this case somebody is interested in the generated LaTeX,
1514 // so this is OK. input@path is set when the actual parameter
1515 // original_path is set. This is done for usual tex-file, but not
1516 // for nice-latex-file. (Matthias 250696)
1519 // code for usual, NOT nice-latex-file
1520 LFile += "\\batchmode\n"; // changed
1521 // from \nonstopmode
1524 if (!original_path.empty()) {
1525 LFile += "\\makeatletter\n";
1527 LFile += "\\def\\input@path{{" + original_path
1530 LFile += "\\makeatother\n";
1534 LFile += "\\documentclass";
1536 string options; // the document class options.
1538 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1539 // only write if existing in list (and not default)
1540 options += params.fontsize;
1545 if (!params.use_geometry &&
1546 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1547 switch (params.papersize) {
1548 case BufferParams::PAPER_A4PAPER:
1549 options += "a4paper,";
1551 case BufferParams::PAPER_USLETTER:
1552 options += "letterpaper,";
1554 case BufferParams::PAPER_A5PAPER:
1555 options += "a5paper,";
1557 case BufferParams::PAPER_B5PAPER:
1558 options += "b5paper,";
1560 case BufferParams::PAPER_EXECUTIVEPAPER:
1561 options += "executivepaper,";
1563 case BufferParams::PAPER_LEGALPAPER:
1564 options += "legalpaper,";
1570 if (params.sides != tclass.sides()) {
1571 switch (params.sides) {
1572 case LyXTextClass::OneSide:
1573 options += "oneside,";
1575 case LyXTextClass::TwoSides:
1576 options += "twoside,";
1583 if (params.columns != tclass.columns()) {
1584 if (params.columns == 2)
1585 options += "twocolumn,";
1587 options += "onecolumn,";
1590 if (!params.use_geometry
1591 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1592 options += "landscape,";
1594 // language should be a parameter to \documentclass
1595 if (params.language != "default") {
1596 if (params.language == "hebrew")
1597 options += "english,";
1598 else if (lyxrc->rtl_support)
1599 options += "hebrew,";
1600 options += params.language + ',';
1601 } else if (lyxrc->rtl_support)
1602 options += "hebrew,english,";
1604 // the user-defined options
1605 if (!params.options.empty()) {
1606 options += params.options + ',';
1609 if (!options.empty()){
1610 options = strip(options, ',');
1617 LFile += textclasslist.LatexnameOfClass(params.textclass);
1620 // end of \documentclass defs
1622 // font selection must be done before loading fontenc.sty
1623 if (params.fonts != "default") {
1624 LFile += "\\usepackage{" + params.fonts + "}\n";
1627 // this one is not per buffer
1628 if (lyxrc->fontenc != "default") {
1629 LFile += "\\usepackage[" + lyxrc->fontenc
1633 if (params.inputenc != "default") {
1634 LFile += "\\usepackage[" + params.inputenc
1639 /* at the very beginning the text parameters */
1640 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1641 switch (params.paperpackage) {
1642 case BufferParams::PACKAGE_A4:
1643 LFile += "\\usepackage{a4}\n";
1646 case BufferParams::PACKAGE_A4WIDE:
1647 LFile += "\\usepackage{a4wide}\n";
1650 case BufferParams::PACKAGE_WIDEMARGINSA4:
1651 LFile += "\\usepackage[widemargins]{a4}\n";
1656 if (params.use_geometry) {
1657 LFile += "\\usepackage{geometry}\n";
1659 LFile += "\\geometry{verbose";
1660 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1661 LFile += ",landscape";
1662 switch (params.papersize2) {
1663 case BufferParams::VM_PAPER_CUSTOM:
1664 if (!params.paperwidth.empty())
1665 LFile += ",paperwidth="
1666 + params.paperwidth;
1667 if (!params.paperheight.empty())
1668 LFile += ",paperheight="
1669 + params.paperheight;
1671 case BufferParams::VM_PAPER_USLETTER:
1672 LFile += ",letterpaper";
1674 case BufferParams::VM_PAPER_USLEGAL:
1675 LFile += ",legalpaper";
1677 case BufferParams::VM_PAPER_USEXECUTIVE:
1678 LFile += ",executivepaper";
1680 case BufferParams::VM_PAPER_A3:
1681 LFile += ",a3paper";
1683 case BufferParams::VM_PAPER_A4:
1684 LFile += ",a4paper";
1686 case BufferParams::VM_PAPER_A5:
1687 LFile += ",a5paper";
1689 case BufferParams::VM_PAPER_B3:
1690 LFile += ",b3paper";
1692 case BufferParams::VM_PAPER_B4:
1693 LFile += ",b4paper";
1695 case BufferParams::VM_PAPER_B5:
1696 LFile += ",b5paper";
1699 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1700 switch (lyxrc->default_papersize) {
1701 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1702 case BufferParams::PAPER_USLETTER:
1703 LFile += ",letterpaper";
1705 case BufferParams::PAPER_LEGALPAPER:
1706 LFile += ",legalpaper";
1708 case BufferParams::PAPER_EXECUTIVEPAPER:
1709 LFile += ",executivepaper";
1711 case BufferParams::PAPER_A3PAPER:
1712 LFile += ",a3paper";
1714 case BufferParams::PAPER_A4PAPER:
1715 LFile += ",a4paper";
1717 case BufferParams::PAPER_A5PAPER:
1718 LFile += ",a5paper";
1720 case BufferParams::PAPER_B5PAPER:
1721 LFile += ",b5paper";
1725 if (!params.topmargin.empty())
1726 LFile += ",tmargin=" + params.topmargin;
1727 if (!params.bottommargin.empty())
1728 LFile += ",bmargin=" + params.bottommargin;
1729 if (!params.leftmargin.empty())
1730 LFile += ",lmargin=" + params.leftmargin;
1731 if (!params.rightmargin.empty())
1732 LFile += ",rmargin=" + params.rightmargin;
1733 if (!params.headheight.empty())
1734 LFile += ",headheight=" + params.headheight;
1735 if (!params.headsep.empty())
1736 LFile += ",headsep=" + params.headsep;
1737 if (!params.footskip.empty())
1738 LFile += ",footskip=" + params.footskip;
1742 if (params.use_amsmath
1743 && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1744 LFile += "\\usepackage{amsmath}\n";
1747 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1748 if (params.pagestyle == "fancy") {
1749 LFile += "\\usepackage{fancyhdr}\n";
1752 LFile += "\\pagestyle{" + params.pagestyle + "}\n";
1756 // We try to load babel late, in case it interferes
1757 // with other packages.
1758 if (params.language != "default" || lyxrc->rtl_support ) {
1759 LFile += "\\usepackage{babel}\n";
1763 if (params.secnumdepth != tclass.secnumdepth()) {
1764 LFile += "\\setcounter{secnumdepth}{";
1765 LFile += tostr(params.secnumdepth);
1769 if (params.tocdepth != tclass.tocdepth()) {
1770 LFile += "\\setcounter{tocdepth}{";
1771 LFile += tostr(params.tocdepth);
1776 if (params.paragraph_separation) {
1777 switch (params.defskip.kind()) {
1778 case VSpace::SMALLSKIP:
1779 LFile += "\\setlength\\parskip{\\smallskipamount}\n";
1781 case VSpace::MEDSKIP:
1782 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1784 case VSpace::BIGSKIP:
1785 LFile += "\\setlength\\parskip{\\bigskipamount}\n";
1787 case VSpace::LENGTH:
1788 LFile += "\\setlength\\parskip{"
1789 + params.defskip.length().asLatexString()
1792 default: // should never happen // Then delete it.
1793 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1798 LFile += "\\setlength\\parindent{0pt}\n";
1802 // Write out what we've generated so far...and reset LFile
1806 // Now insert the LyX specific LaTeX commands...
1807 string preamble, tmppreamble;
1809 // The optional packages;
1810 preamble = features.getPackages(params);
1812 // this might be useful...
1813 preamble += "\n\\makeatletter\n\n";
1815 // Some macros LyX will need
1816 tmppreamble = features.getMacros(params);
1818 if (!tmppreamble.empty()) {
1819 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1820 "LyX specific LaTeX commands.\n"
1821 + tmppreamble + '\n';
1824 // the text class specific preamble
1825 tmppreamble = features.getTClassPreamble(params);
1826 if (!tmppreamble.empty()) {
1827 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1828 "Textclass specific LaTeX commands.\n"
1829 + tmppreamble + '\n';
1832 /* the user-defined preamble */
1833 if (!params.preamble.empty()) {
1834 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1835 "User specified LaTeX commands.\n"
1836 + params.preamble + '\n';
1839 preamble += "\\makeatother\n\n";
1841 // Itemize bullet settings need to be last in case the user
1842 // defines their own bullets that use a package included
1843 // in the user-defined preamble -- ARRae
1844 // Actually it has to be done much later than that
1845 // since some packages like frenchb make modifications
1846 // at \begin{document} time -- JMarc
1848 for (int i = 0; i < 4; ++i) {
1849 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1850 if (bullets_def.empty())
1851 bullets_def="\\AtBeginDocument{\n";
1852 bullets_def += " \\renewcommand{\\labelitemi";
1854 // `i' is one less than the item to modify
1861 bullets_def += "ii";
1867 bullets_def += "}{" +
1868 params.user_defined_bullets[i].getText()
1873 if (!bullets_def.empty())
1874 preamble += bullets_def + "}\n\n";
1876 for (int j = countChar(preamble, '\n'); j-- ;) {
1883 LFile += "\\begin{document}\n\n";
1887 lyxerr.debug() << "preamble finished, now the body." << endl;
1889 bool was_title = false;
1890 bool already_title = false;
1896 LyXParagraph * par = paragraph;
1902 lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
1904 LyXLayout const & layout = textclasslist.Style(params.textclass,
1907 if (layout.intitle) {
1908 if (already_title) {
1909 lyxerr <<"Error in MakeLatexFile: You"
1910 " should not mix title layouts"
1911 " with normal ones." << endl;
1914 } else if (was_title && !already_title) {
1915 LFile += "\\maketitle\n";
1917 already_title = true;
1920 // We are at depth 0 so we can just use
1921 // ordinary \footnote{} generation
1922 // flag this with ftcount
1924 if (layout.isEnvironment()
1925 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
1926 par = par->TeXEnvironment(LFile, texrow,
1927 ftnote, ft_texrow, ftcount);
1929 par = par->TeXOnePar(LFile, texrow,
1930 ftnote, ft_texrow, ftcount);
1933 // Write out what we've generated...and reset LFile
1936 LFile += "\\addtocounter{footnote}{-";
1937 LFile += tostr(ftcount - 1);
1941 texrow += ft_texrow;
1946 if (loop_count == 2) {
1947 // fwrite()ing every second time through the loop
1948 // gains a few extra % of speed; going higher than
1949 // 2 will slow things down again. I'll look at
1950 // LFile.length() in a future revision. ARRae
1957 // It might be that we only have a title in this document
1958 if (was_title && !already_title) {
1959 LFile += "\\maketitle\n";
1964 LFile += "\\end{document}\n";
1967 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1969 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1973 // Just to be sure. (Asger)
1976 // Write out what we've generated...and reset LFile
1980 // tex_code_break_column's value is used to decide
1981 // if we are in batchmode or not (within mathed_write()
1982 // in math_write.C) so we must set it to a non-zero
1983 // value when we leave otherwise we save incorrect .lyx files.
1984 tex_code_break_column = lyxrc->ascii_linelen;
1986 // How to check if the close went ok when using fstreams
1988 lyxerr.debug() << "Finished making latex file." << endl;
1992 bool Buffer::isLatex() const
1994 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
1998 bool Buffer::isLinuxDoc() const
2000 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2004 bool Buffer::isLiterate() const
2006 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2010 bool Buffer::isDocBook() const
2012 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2016 bool Buffer::isSGML() const
2018 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2019 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2023 void Buffer::sgmlOpenTag(ostream & os, int depth,
2024 string const & latexname) const
2026 os << string(depth, ' ') << "<" << latexname << ">\n";
2030 void Buffer::sgmlCloseTag(ostream & os, int depth,
2031 string const & latexname) const
2033 os << string(depth, ' ') << "</" << latexname << ">\n";
2037 void Buffer::makeLinuxDocFile(string const & fname, int column)
2039 LyXParagraph * par = paragraph;
2041 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2042 string environment_stack[10];
2045 int depth = 0; /* paragraph depth */
2047 ofstream ofs(fname.c_str());
2050 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2054 tex_code_break_column = column;
2057 if (params.preamble.empty()) {
2058 ofs << "<!doctype linuxdoc system>\n\n";
2061 ofs << "<!doctype linuxdoc system \n [ "
2062 << params.preamble << " \n]>\n\n";
2065 ofs << "<!-- " << LYX_DOCVERSION
2066 << " created this file. For more info see http://www.lyx.org/"
2069 if(params.options.empty())
2070 sgmlOpenTag(ofs, 0, top_element);
2072 string top = top_element;
2074 top += params.options;
2075 sgmlOpenTag(ofs, 0, top);
2079 int desc_on = 0; /* description mode*/
2080 LyXLayout const & style =
2081 textclasslist.Style(users->buffer()->params.textclass,
2083 par->AutoDeleteInsets();
2085 /* treat <toc> as a special case for compatibility with old code */
2086 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2087 Inset * inset = par->GetInset(0);
2088 char lyx_code = inset->LyxCode();
2089 if (lyx_code == Inset::TOC_CODE){
2090 string temp = "toc";
2091 sgmlOpenTag(ofs, depth, temp);
2094 linuxDocHandleFootnote(ofs, par, depth);
2099 // environment tag closing
2100 for( ; depth > par->depth; --depth) {
2101 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2102 environment_stack[depth].clear();
2105 // write opening SGML tags
2106 switch(style.latextype) {
2107 case LATEX_PARAGRAPH:
2108 if(depth == par->depth
2109 && !environment_stack[depth].empty()) {
2110 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2111 environment_stack[depth].clear();
2117 sgmlOpenTag(ofs, depth, style.latexname());
2122 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2124 if (!environment_stack[depth].empty()){
2125 sgmlCloseTag(ofs, depth,
2126 environment_stack[depth]);
2130 environment_stack[depth].clear();
2131 sgmlOpenTag(ofs, depth, style.latexname());
2134 case LATEX_ENVIRONMENT:
2135 case LATEX_ITEM_ENVIRONMENT:
2136 if(depth == par->depth
2137 && environment_stack[depth] != style.latexname()
2138 && !environment_stack[depth].empty()) {
2140 sgmlCloseTag(ofs, depth,
2141 environment_stack[depth]);
2142 environment_stack[depth].clear();
2144 if (depth < par->depth) {
2146 environment_stack[depth].clear();
2148 if (environment_stack[depth] != style.latexname()) {
2151 sgmlOpenTag(ofs, depth, temp);
2153 environment_stack[depth] = style.latexname();
2154 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2156 if(style.latextype == LATEX_ENVIRONMENT) break;
2158 desc_on = (style.labeltype == LABEL_MANUAL);
2165 sgmlOpenTag(ofs, depth + 1, item_name);
2168 sgmlOpenTag(ofs, depth, style.latexname());
2173 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2176 linuxDocHandleFootnote(ofs, par, depth);
2178 while(par && par->IsDummy());
2181 /* write closing SGML tags */
2182 switch(style.latextype) {
2184 case LATEX_ENVIRONMENT:
2185 case LATEX_ITEM_ENVIRONMENT:
2188 sgmlCloseTag(ofs, depth, style.latexname());
2193 /* Close open tags */
2194 for(; depth > 0; --depth)
2195 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2197 if(!environment_stack[depth].empty())
2198 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2201 sgmlCloseTag(ofs, 0, top_element);
2204 // How to check for successful close
2208 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2211 string tag = "footnote";
2213 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2214 sgmlOpenTag(os, depth + 1, tag);
2215 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2216 sgmlCloseTag(os, depth + 1, tag);
2222 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2223 int const depth, int desc_on,
2224 LyXParagraph * & par)
2226 LyXParagraph * tpar = par;
2227 string tmp_par, extra_par;
2228 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2229 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2233 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2234 "Caption").second) {
2235 sgmlOpenTag(os, depth + 1, inner_tag);
2236 SimpleDocBookOnePar(tmp_par, extra_par, tpar,
2237 desc_on, depth + 2);
2238 tmp_par = strip(tmp_par);
2239 tmp_par = frontStrip(tmp_par);
2241 sgmlCloseTag(os, depth+1, inner_tag);
2242 if(!extra_par.empty())
2248 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2251 string tag, inner_tag;
2252 string tmp_par, extra_par;
2253 bool inner_span = false;
2256 // This is not how I like to see enums. They should not be anonymous
2257 // and variables of its type should not be declared right after the
2258 // last brace. (Lgb)
2265 } last = NO_ONE, present = FOOTNOTE_LIKE;
2267 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2268 if(last == present) {
2270 if(!tmp_par.empty()) {
2273 sgmlCloseTag(os, depth+1, inner_tag);
2274 sgmlOpenTag(os, depth+1, inner_tag);
2281 if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2282 if(!extra_par.empty()) os << extra_par;
2283 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2286 switch (par->footnotekind) {
2287 case LyXParagraph::FOOTNOTE:
2288 case LyXParagraph::ALGORITHM:
2291 present = FOOTNOTE_LIKE;
2294 case LyXParagraph::MARGIN:
2297 present = MARGIN_LIKE;
2300 case LyXParagraph::FIG:
2301 case LyXParagraph::WIDE_FIG:
2303 inner_tag = "title";
2307 case LyXParagraph::TAB:
2308 case LyXParagraph::WIDE_TAB:
2310 inner_tag = "title";
2315 sgmlOpenTag(os, depth, tag);
2316 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2317 DocBookHandleCaption(os, inner_tag, depth,
2321 sgmlOpenTag(os, depth + 1, inner_tag);
2324 // ignore all caption here, we processed them above!!!
2325 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2326 "Caption").second) {
2327 SimpleDocBookOnePar(tmp_par, extra_par, par,
2328 desc_on, depth + 2);
2330 tmp_par = frontStrip(strip(tmp_par));
2336 if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2337 if(!extra_par.empty()) os << extra_par;
2338 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2342 /* push a tag in a style stack */
2343 void Buffer::push_tag(ostream & os, char const * tag,
2344 int & pos, char stack[5][3])
2346 /* pop all previous tags */
2347 for (int j = pos; j >= 0; --j)
2348 os << "</" << stack[j] << ">";
2351 sprintf(stack[++pos], "%s", tag);
2354 for (int i = 0; i <= pos; ++i)
2355 os << "<" << stack[i] << ">";
2358 void Buffer::pop_tag(ostream & os, char const * tag,
2359 int & pos, char stack[5][3])
2363 // pop all tags till specified one
2364 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2365 os << "</" << stack[j] << ">";
2368 os << "</" << tag << ">";
2370 // push all tags, but the specified one
2371 for (j = j + 1; j <= pos; ++j) {
2372 os << "<" << stack[j] << ">";
2373 strcpy(stack[j-1], stack[j]);
2379 /* handle internal paragraph parsing -- layout already processed */
2381 // checks, if newcol chars should be put into this line
2382 // writes newline, if necessary.
2384 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2385 const unsigned int newcol)
2388 if (colcount > lyxrc->ascii_linelen) {
2390 colcount = newcol; // assume write after this call
2395 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2396 int desc_on, int const /*depth*/)
2398 LyXFont font1, font2;
2401 LyXParagraph::size_type main_body;
2403 LyXLayout const & style = textclasslist.Style(params.textclass,
2406 char family_type = 0; // family font flag
2407 bool is_bold = false; // series font flag
2408 char shape_type = 0; // shape font flag
2409 bool is_em = false; // emphasis (italic) font flag
2411 int stack_num = -1; // style stack position
2412 char stack[5][3]; // style stack
2413 unsigned int char_line_count = 5; // Heuristic choice ;-)
2415 if (style.labeltype != LABEL_MANUAL)
2418 main_body = par->BeginningOfMainBody();
2420 /* gets paragraph main font */
2422 font1 = style.labelfont;
2427 /* parsing main loop */
2428 for (LyXParagraph::size_type i = 0;
2429 i < par->size(); ++i) {
2431 /* handle quote tag */
2432 if (i == main_body && !par->IsDummy()) {
2437 font2 = par->getFont(i);
2439 if (font1.family() != font2.family()) {
2440 switch(family_type) {
2442 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2443 push_tag(os, "tt", stack_num, stack);
2446 else if (font2.family() == LyXFont::SANS_FAMILY) {
2447 push_tag(os, "sf", stack_num, stack);
2452 pop_tag(os, "tt", stack_num, stack);
2453 if (font2.family() == LyXFont::SANS_FAMILY) {
2454 push_tag(os, "sf", stack_num, stack);
2462 pop_tag(os, "sf", stack_num, stack);
2463 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2464 push_tag(os, "tt", stack_num, stack);
2473 /* handle bold face */
2474 if (font1.series() != font2.series()) {
2475 if (font2.series() == LyXFont::BOLD_SERIES) {
2476 push_tag(os, "bf", stack_num, stack);
2480 pop_tag(os, "bf", stack_num, stack);
2485 /* handle italic and slanted fonts */
2486 if (font1.shape() != font2.shape()) {
2487 switch(shape_type) {
2489 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2490 push_tag(os, "it", stack_num, stack);
2493 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2494 push_tag(os, "sl", stack_num, stack);
2499 pop_tag(os, "it", stack_num, stack);
2500 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2501 push_tag(os, "sl", stack_num, stack);
2509 pop_tag(os, "sl", stack_num, stack);
2510 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2511 push_tag(os, "it", stack_num, stack);
2519 /* handle <em> tag */
2520 if (font1.emph() != font2.emph()) {
2521 if (font2.emph() == LyXFont::ON) {
2522 push_tag(os, "em", stack_num, stack);
2525 pop_tag(os, "em", stack_num, stack);
2530 c = par->GetChar(i);
2532 if (font2.latex() == LyXFont::ON) {
2533 // "TeX"-Mode on == > SGML-Mode on.
2535 os << c; // see LaTeX-Generation...
2537 } else if (c == LyXParagraph::META_INSET) {
2538 inset = par->GetInset(i);
2540 inset->Linuxdoc(tmp_out);
2545 if (par->linuxDocConvertChar(c, sgml_string)
2546 && !style.free_spacing) { // in freespacing
2548 // non-breaking characters
2552 linux_doc_line_break(os, char_line_count, 6);
2557 linux_doc_line_break(os, char_line_count, 1);
2563 char_line_count += sgml_string.length();
2569 /* needed if there is an optional argument but no contents */
2570 if (main_body > 0 && main_body == par->size()) {
2574 /* pop all defined Styles */
2575 for (j = stack_num; j >= 0; --j) {
2576 linux_doc_line_break(os,
2578 3 + strlen(stack[j]));
2579 os << "</" << stack[j] << ">";
2582 /* resets description flag correctly */
2585 /* <tag> not closed... */
2586 linux_doc_line_break(os, char_line_count, 6);
2590 /* fprintf(file, "</p>");*/
2596 /* print an error message */
2597 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2598 char const * message)
2600 InsetError * new_inset;
2602 /* insert an error marker in text */
2603 new_inset = new InsetError(message);
2604 par->InsertChar(pos, LyXParagraph::META_INSET);
2605 par->InsertInset(pos, new_inset);
2608 // This constant defines the maximum number of
2609 // environment layouts that can be nesteded.
2610 // The same applies for command layouts.
2611 // These values should be more than enough.
2612 // José Matos (1999/07/22)
2614 enum { MAX_NEST_LEVEL = 25};
2616 void Buffer::makeDocBookFile(string const & fname, int column)
2618 LyXParagraph * par = paragraph;
2620 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2621 string environment_stack[MAX_NEST_LEVEL];
2622 string environment_inner[MAX_NEST_LEVEL];
2623 string command_stack[MAX_NEST_LEVEL];
2624 bool command_flag= false;
2625 int command_depth= 0, command_base= 0, cmd_depth= 0;
2627 string item_name, command_name;
2628 string c_depth, c_params, tmps;
2630 int depth= 0; /* paragraph depth */
2632 tex_code_break_column = column;
2634 ofstream ofs(fname.c_str());
2636 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2642 ofs << "<!doctype " << top_element
2643 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2645 if (params.preamble.empty())
2648 ofs << "\n [ " << params.preamble << " \n]>\n\n";
2650 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2651 << "\n See http://www.lyx.org/ for more information -->\n";
2653 if(params.options.empty())
2654 sgmlOpenTag(ofs, 0, top_element);
2656 string top = top_element;
2658 top += params.options;
2659 sgmlOpenTag(ofs, 0, top);
2663 int desc_on= 0; /* description mode*/
2664 LyXLayout const & style = textclasslist.Style(users->buffer()->params.textclass,
2666 par->AutoDeleteInsets();
2668 /* environment tag closing */
2669 for( ; depth > par->depth; --depth) {
2670 if(environment_inner[depth] != "!-- --") {
2671 item_name= "listitem";
2672 sgmlCloseTag(ofs, command_depth + depth,
2674 if( environment_inner[depth] == "varlistentry")
2675 sgmlCloseTag(ofs, depth+command_depth,
2676 environment_inner[depth]);
2678 sgmlCloseTag(ofs, depth + command_depth,
2679 environment_stack[depth]);
2680 environment_stack[depth].clear();
2681 environment_inner[depth].clear();
2684 if(depth == par->depth
2685 && environment_stack[depth] != style.latexname()
2686 && !environment_stack[depth].empty()) {
2687 if(environment_inner[depth] != "!-- --") {
2688 item_name= "listitem";
2689 sgmlCloseTag(ofs, command_depth+depth,
2691 if( environment_inner[depth] == "varlistentry")
2693 depth + command_depth,
2694 environment_inner[depth]);
2697 sgmlCloseTag(ofs, depth + command_depth,
2698 environment_stack[depth]);
2700 environment_stack[depth].clear();
2701 environment_inner[depth].clear();
2704 // Write opening SGML tags.
2705 switch(style.latextype) {
2706 case LATEX_PARAGRAPH:
2707 if(style.latexname() != "dummy")
2708 sgmlOpenTag(ofs, depth+command_depth,
2714 LinuxDocError(par, 0,
2715 _("Error : Wrong depth for "
2716 "LatexType Command.\n"));
2718 command_name = style.latexname();
2720 tmps = style.latexparam();
2721 c_params = split(tmps, c_depth,'|');
2723 cmd_depth= atoi(c_depth.c_str());
2726 if(cmd_depth<command_base) {
2727 for(int j = command_depth;
2728 j >= command_base; --j)
2729 if(!command_stack[j].empty())
2730 sgmlCloseTag(ofs, j, command_stack[j]);
2731 command_depth= command_base= cmd_depth;
2733 else if(cmd_depth <= command_depth) {
2734 for(int j = command_depth;
2735 j >= cmd_depth; --j)
2737 if(!command_stack[j].empty())
2738 sgmlCloseTag(ofs, j, command_stack[j]);
2739 command_depth= cmd_depth;
2742 command_depth= cmd_depth;
2745 command_depth = command_base = cmd_depth;
2746 command_flag = true;
2748 command_stack[command_depth]= command_name;
2750 // treat label as a special case for
2751 // more WYSIWYM handling.
2752 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2753 Inset * inset = par->GetInset(0);
2754 char lyx_code = inset->LyxCode();
2755 if (lyx_code == Inset::LABEL_CODE){
2756 command_name += " id=\"";
2757 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2758 command_name += "\"";
2763 sgmlOpenTag(ofs, depth+command_depth, command_name);
2764 item_name = "title";
2765 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2768 case LATEX_ENVIRONMENT:
2769 case LATEX_ITEM_ENVIRONMENT:
2770 if (depth < par->depth) {
2772 environment_stack[depth].clear();
2775 if (environment_stack[depth] != style.latexname()) {
2776 environment_stack[depth] = style.latexname();
2777 environment_inner[depth] = "!-- --";
2778 sgmlOpenTag(ofs, depth + command_depth,
2779 environment_stack[depth]);
2781 if(environment_inner[depth] != "!-- --") {
2782 item_name= "listitem";
2784 command_depth + depth,
2786 if (environment_inner[depth] == "varlistentry")
2788 depth + command_depth,
2789 environment_inner[depth]);
2793 if(style.latextype == LATEX_ENVIRONMENT) {
2794 if(!style.latexparam().empty())
2795 sgmlOpenTag(ofs, depth + command_depth,
2796 style.latexparam());
2800 desc_on = (style.labeltype == LABEL_MANUAL);
2803 environment_inner[depth]= "varlistentry";
2805 environment_inner[depth]= "listitem";
2807 sgmlOpenTag(ofs, depth + 1 + command_depth,
2808 environment_inner[depth]);
2812 sgmlOpenTag(ofs, depth + 1 + command_depth,
2817 sgmlOpenTag(ofs, depth + 1 + command_depth,
2822 sgmlOpenTag(ofs, depth + command_depth,
2828 string tmp_par, extra_par;
2830 SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
2831 depth + 1 + command_depth);
2835 DocBookHandleFootnote(ofs, par,
2836 depth + 1 + command_depth);
2838 while(par && par->IsDummy());
2841 /* write closing SGML tags */
2842 switch(style.latextype) {
2845 sgmlCloseTag(ofs, depth + command_depth, end_tag);
2847 case LATEX_ENVIRONMENT:
2848 if(!style.latexparam().empty())
2849 sgmlCloseTag(ofs, depth + command_depth,
2850 style.latexparam());
2852 case LATEX_ITEM_ENVIRONMENT:
2853 if(desc_on == 1) break;
2855 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2857 case LATEX_PARAGRAPH:
2858 if(style.latexname() != "dummy")
2859 sgmlCloseTag(ofs, depth + command_depth,
2863 sgmlCloseTag(ofs, depth + command_depth,
2870 for(; depth >= 0; --depth) {
2871 if(!environment_stack[depth].empty()) {
2872 if(environment_inner[depth] != "!-- --") {
2873 item_name= "listitem";
2874 sgmlCloseTag(ofs, command_depth + depth,
2876 if( environment_inner[depth] == "varlistentry")
2877 sgmlCloseTag(ofs, depth + command_depth,
2878 environment_inner[depth]);
2881 sgmlCloseTag(ofs, depth + command_depth,
2882 environment_stack[depth]);
2886 for(int j = command_depth; j >= command_base; --j)
2887 if(!command_stack[j].empty())
2888 sgmlCloseTag(ofs, j, command_stack[j]);
2891 sgmlCloseTag(ofs, 0, top_element);
2894 // How to check for successful close
2898 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
2899 LyXParagraph * par, int & desc_on,
2903 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
2906 LyXFont font1, font2;
2909 LyXParagraph::size_type main_body;
2911 string emph= "emphasis";
2912 bool emph_flag= false;
2913 int char_line_count= 0;
2915 LyXLayout const & style = textclasslist.Style(params.textclass,
2918 if (style.labeltype != LABEL_MANUAL)
2921 main_body = par->BeginningOfMainBody();
2923 /* gets paragraph main font */
2925 font1 = style.labelfont;
2929 char_line_count = depth;
2930 if(!style.free_spacing)
2931 for (j = 0; j < depth; ++j)
2934 /* parsing main loop */
2935 for (LyXParagraph::size_type i = 0;
2936 i < par->size(); ++i) {
2937 font2 = par->getFont(i);
2939 /* handle <emphasis> tag */
2940 if (font1.emph() != font2.emph() && i) {
2941 if (font2.emph() == LyXFont::ON) {
2942 file += "<emphasis>";
2945 file += "</emphasis>";
2950 c = par->GetChar(i);
2952 if (c == LyXParagraph::META_INSET) {
2953 inset = par->GetInset(i);
2955 inset->DocBook(tmp_out);
2957 // This code needs some explanation:
2958 // Two insets are treated specially
2959 // label if it is the first element in a command paragraph
2961 // graphics inside tables or figure floats can't go on
2962 // title (the equivalente in latex for this case is caption
2963 // and title should come first
2966 if(desc_on!= 3 || i!= 0) {
2967 if(!tmp_out.empty() && tmp_out[0] == '@') {
2969 extra += frontStrip(tmp_out, '@');
2971 file += frontStrip(tmp_out, '@');
2976 } else if (font2.latex() == LyXFont::ON) {
2977 // "TeX"-Mode on ==> SGML-Mode on.
2984 if (par->linuxDocConvertChar(c, sgml_string)
2985 && !style.free_spacing) { // in freespacing
2987 // non-breaking characters
2992 file += "</term><listitem><para>";
3000 file += sgml_string;
3006 /* needed if there is an optional argument but no contents */
3007 if (main_body > 0 && main_body == par->size()) {
3011 file += "</emphasis>";
3014 /* resets description flag correctly */
3017 /* <term> not closed... */
3025 int Buffer::runLaTeX()
3027 if (!users->text) return 0;
3031 // get LaTeX-Filename
3032 string name = getLatexName();
3034 string path = OnlyPath(filename);
3036 string org_path = path;
3037 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3041 Path p(path); // path to LaTeX file
3042 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3044 // Remove all error insets
3045 bool a = users->removeAutoInsets();
3047 // Always generate the LaTeX file
3048 makeLaTeXFile(name, org_path, false);
3051 // do the LaTex run(s)
3053 string latex_command = lyxrc->pdf_mode ?
3054 lyxrc->pdflatex_command : lyxrc->latex_command;
3055 LaTeX latex(latex_command, name, filepath);
3056 int res = latex.run(terr,
3057 users->owner()->getMiniBuffer()); // running latex
3059 // check return value from latex.run().
3060 if ((res & LaTeX::NO_LOGFILE)) {
3061 WriteAlert(_("LaTeX did not work!"),
3062 _("Missing log file:"), name);
3063 } else if ((res & LaTeX::ERRORS)) {
3064 users->owner()->getMiniBuffer()->Set(_("Done"));
3065 // Insert all errors as errors boxes
3066 users->insertErrors(terr);
3068 // Dvi should also be kept dirty if the latex run
3069 // ends up with errors. However it should be possible
3070 // to view a dirty dvi too.
3072 //no errors or any other things to think about so:
3073 users->owner()->getMiniBuffer()->Set(_("Done"));
3077 // if we removed error insets before we ran LaTeX or if we inserted
3078 // error insets after we ran LaTeX this must be run:
3079 if (a || (res & LaTeX::ERRORS)){
3082 users->updateScrollbar();
3086 return latex.getNumErrors();
3090 int Buffer::runLiterate()
3092 if (!users->text) return 0;
3096 // get LaTeX-Filename
3097 string name = getLatexName();
3098 // get Literate-Filename
3099 string lit_name = ChangeExtension (getLatexName(),
3100 lyxrc->literate_extension, true);
3102 string path = OnlyPath(filename);
3104 string org_path = path;
3105 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3109 Path p(path); // path to Literate file
3110 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3112 // Remove all error insets
3113 bool a = users->removeAutoInsets();
3115 // generate the Literate file if necessary
3116 if (!isDviClean() || a) {
3117 makeLaTeXFile(lit_name, org_path, false);
3121 string latex_command = lyxrc->pdf_mode ?
3122 lyxrc->pdflatex_command : lyxrc->latex_command;
3123 Literate literate(latex_command, name, filepath,
3125 lyxrc->literate_command, lyxrc->literate_error_filter,
3126 lyxrc->build_command, lyxrc->build_error_filter);
3128 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3130 // check return value from literate.weave().
3131 if ((res & Literate::NO_LOGFILE)) {
3132 WriteAlert(_("Literate command did not work!"),
3133 _("Missing log file:"), name);
3134 } else if ((res & Literate::ERRORS)) {
3135 users->owner()->getMiniBuffer()->Set(_("Done"));
3136 // Insert all errors as errors boxes
3137 users->insertErrors(terr);
3139 // Dvi should also be kept dirty if the latex run
3140 // ends up with errors. However it should be possible
3141 // to view a dirty dvi too.
3143 //no errors or any other things to think about so:
3144 users->owner()->getMiniBuffer()->Set(_("Done"));
3148 // if we removed error insets before we ran LaTeX or if we inserted
3149 // error insets after we ran LaTeX this must be run:
3150 if (a || (res & Literate::ERRORS)){
3153 users->updateScrollbar();
3157 return literate.getNumErrors();
3161 int Buffer::buildProgram()
3163 if (!users->text) return 0;
3167 // get LaTeX-Filename
3168 string name = getLatexName();
3169 // get Literate-Filename
3170 string lit_name = ChangeExtension(getLatexName(),
3171 lyxrc->literate_extension, true);
3173 string path = OnlyPath(filename);
3175 string org_path = path;
3176 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3180 Path p(path); // path to Literate file
3181 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3183 // Remove all error insets
3184 bool a = users->removeAutoInsets();
3186 // generate the LaTeX file if necessary
3187 if (!isNwClean() || a) {
3188 makeLaTeXFile(lit_name, org_path, false);
3192 string latex_command = lyxrc->pdf_mode ?
3193 lyxrc->pdflatex_command : lyxrc->latex_command;
3194 Literate literate(latex_command, name, filepath,
3196 lyxrc->literate_command, lyxrc->literate_error_filter,
3197 lyxrc->build_command, lyxrc->build_error_filter);
3199 int res = literate.build(terr, users->owner()->getMiniBuffer());
3201 // check return value from literate.build().
3202 if ((res & Literate::NO_LOGFILE)) {
3203 WriteAlert(_("Build did not work!"),
3204 _("Missing log file:"), name);
3205 } else if ((res & Literate::ERRORS)) {
3206 users->owner()->getMiniBuffer()->Set(_("Done"));
3207 // Insert all errors as errors boxes
3208 users->insertErrors(terr);
3210 // Literate files should also be kept dirty if the literate
3211 // command run ends up with errors.
3213 //no errors or any other things to think about so:
3214 users->owner()->getMiniBuffer()->Set(_("Done"));
3218 // if we removed error insets before we ran Literate/Build or if we inserted
3219 // error insets after we ran Literate/Build this must be run:
3220 if (a || (res & Literate::ERRORS)){
3223 users->updateScrollbar();
3227 return literate.getNumErrors();
3231 // This should be enabled when the Chktex class is implemented. (Asger)
3232 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3233 // Other flags: -wall -v0 -x
3234 int Buffer::runChktex()
3236 if (!users->text) return 0;
3240 // get LaTeX-Filename
3241 string name = getLatexName();
3242 string path = OnlyPath(filename);
3244 string org_path = path;
3245 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3249 Path p(path); // path to LaTeX file
3250 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3252 // Remove all error insets
3253 bool a = users->removeAutoInsets();
3255 // Generate the LaTeX file if neccessary
3256 if (!isDviClean() || a) {
3257 makeLaTeXFile(name, org_path, false);
3262 Chktex chktex(lyxrc->chktex_command, name, filepath);
3263 int res = chktex.run(terr); // run chktex
3266 WriteAlert(_("chktex did not work!"),
3267 _("Could not run with file:"), name);
3268 } else if (res > 0) {
3269 // Insert all errors as errors boxes
3270 users->insertErrors(terr);
3273 // if we removed error insets before we ran chktex or if we inserted
3274 // error insets after we ran chktex, this must be run:
3278 users->updateScrollbar();
3286 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
3288 LyXFont font1(LyXFont::ALL_INHERIT);
3291 LyXParagraph::size_type i;
3295 string fname1 = TmpFileName(string(), "RAT1");
3296 string fname2 = TmpFileName(string(), "RAT2");
3298 ofstream ofs(fname1.c_str());
3300 WriteAlert(_("LYX_ERROR:"),
3301 _("Cannot open temporary file:"), fname1);
3304 par->table->RoffEndOfCell(ofs, -1);
3305 for (i = 0; i < par->size(); ++i) {
3306 c = par->GetChar(i);
3307 if (par->table->IsContRow(cell)) {
3308 if (c == LyXParagraph::META_NEWLINE)
3312 font2 = par->GetFontSettings(i);
3313 if (font1.latex() != font2.latex()) {
3314 if (font2.latex() != LyXFont::OFF)
3318 case LyXParagraph::META_INSET:
3319 if ((inset = par->GetInset(i))) {
3320 fstream fs(fname2.c_str(), ios::in|ios::out);
3322 WriteAlert(_("LYX_ERROR:"),
3323 _("Cannot open temporary file:"), fname2);
3325 remove(fname1.c_str());
3328 inset->Latex(fs, -1);
3341 case LyXParagraph::META_NEWLINE:
3342 if (par->table->CellHasContRow(cell)>= 0)
3343 par->RoffContTableRows(ofs, i+1, cell);
3344 par->table->RoffEndOfCell(ofs, cell);
3347 case LyXParagraph::META_HFILL:
3349 case LyXParagraph::META_PROTECTED_SEPARATOR:
3359 << "RoffAsciiTable:"
3360 " NULL char in structure." << endl;
3364 par->table->RoffEndOfCell(ofs, cell);
3366 string cmd = lyxrc->ascii_roff_command + " >" + fname2;
3367 cmd = subst(cmd, "$$FName", fname1);
3368 Systemcalls one(Systemcalls::System, cmd);
3369 if (!(lyxerr.debugging(Debug::ROFF))) {
3370 remove(fname1.c_str());
3372 ifstream ifs(fname2.c_str());
3374 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3377 // now output the produced file
3381 WriteAlert(_("Error!"),
3382 _("Error executing *roff command on table"));
3383 // overread leading blank lines
3384 while(!ifs && (c == '\n'))
3387 for(j = 0; j < par->depth; ++j)
3389 while(!ifs && (c != '\n')) {
3394 // overread trailing blank lines
3395 while(!ifs && (c == '\n'))
3399 remove(fname2.c_str());
3403 /// changed Heinrich Bauer, 23/03/98
3404 bool Buffer::isDviClean() const
3406 if (lyxrc->use_tempdir)
3407 return dvi_clean_tmpd;
3409 return dvi_clean_orgd;
3413 /// changed Heinrich Bauer, 23/03/98
3414 void Buffer::markDviClean()
3416 if (lyxrc->use_tempdir)
3417 dvi_clean_tmpd = true;
3419 dvi_clean_orgd = true;
3423 /// changed Heinrich Bauer, 23/03/98
3424 void Buffer::markDviDirty()
3426 if (lyxrc->use_tempdir)
3427 dvi_clean_tmpd = false;
3429 dvi_clean_orgd = false;
3433 void Buffer::validate(LaTeXFeatures & features) const
3435 LyXParagraph * par = paragraph;
3436 LyXTextClass const & tclass =
3437 textclasslist.TextClass(params.textclass);
3439 // AMS Style is at document level
3441 features.amsstyle = (params.use_amsmath ||
3442 tclass.provides(LyXTextClass::amsmath));
3445 // We don't use "lyxerr.debug" because of speed. (Asger)
3446 if (lyxerr.debugging(Debug::LATEX))
3447 lyxerr << "Paragraph: " << par << endl;
3449 // Now just follow the list of paragraphs and run
3450 // validate on each of them.
3451 par->validate(features);
3453 // and then the next paragraph
3457 // the bullet shapes are buffer level not paragraph level
3458 // so they are tested here
3459 for (int i = 0; i < 4; ++i) {
3460 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3461 int font = params.user_defined_bullets[i].getFont();
3464 .user_defined_bullets[i]
3471 features.latexsym = true;
3475 features.amssymb = true;
3477 else if ((font >= 2 && font <= 5)) {
3478 features.pifont = true;
3483 if (lyxerr.debugging(Debug::LATEX)) {
3484 features.showStruct(params);
3489 void Buffer::setPaperStuff()
3491 params.papersize = BufferParams::PAPER_DEFAULT;
3492 char c1 = params.paperpackage;
3493 if (c1 == BufferParams::PACKAGE_NONE) {
3494 char c2 = params.papersize2;
3495 if (c2 == BufferParams::VM_PAPER_USLETTER)
3496 params.papersize = BufferParams::PAPER_USLETTER;
3497 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3498 params.papersize = BufferParams::PAPER_LEGALPAPER;
3499 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3500 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3501 else if (c2 == BufferParams::VM_PAPER_A3)
3502 params.papersize = BufferParams::PAPER_A3PAPER;
3503 else if (c2 == BufferParams::VM_PAPER_A4)
3504 params.papersize = BufferParams::PAPER_A4PAPER;
3505 else if (c2 == BufferParams::VM_PAPER_A5)
3506 params.papersize = BufferParams::PAPER_A5PAPER;
3507 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3508 (c2 == BufferParams::VM_PAPER_B5))
3509 params.papersize = BufferParams::PAPER_B5PAPER;
3510 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3511 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3512 params.papersize = BufferParams::PAPER_A4PAPER;
3516 // This function should be in Buffer because it's a buffer's property (ale)
3517 string Buffer::getIncludeonlyList(char delim)
3520 LyXParagraph * par = paragraph;
3521 LyXParagraph::size_type pos;
3525 while ((inset = par->ReturnNextInsetPointer(pos))){
3526 if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3527 InsetInclude * insetinc =
3528 static_cast<InsetInclude*>(inset);
3529 if (insetinc->isInclude()
3530 && insetinc->isNoLoad()) {
3533 lst += ChangeExtension(insetinc->getContents(), string(), true);
3540 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3545 // This is also a buffer property (ale)
3546 string Buffer::getReferenceList(char delim)
3548 /// if this is a child document and the parent is already loaded
3549 /// Use the parent's list instead [ale990407]
3550 if (!params.parentname.empty()
3551 && bufferlist.exists(params.parentname)) {
3552 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3554 return tmp->getReferenceList(delim);
3557 LyXParagraph * par = paragraph;
3558 LyXParagraph::size_type pos;
3563 while ((inset = par->ReturnNextInsetPointer(pos))){
3564 for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
3567 lst += inset->getLabel(i);
3573 lyxerr.debug() << "References(" << lst << ")" << endl;
3578 // This is also a buffer property (ale)
3579 string Buffer::getBibkeyList(char delim)
3581 /// if this is a child document and the parent is already loaded
3582 /// Use the parent's list instead [ale990412]
3583 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3584 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3586 return tmp->getBibkeyList(delim);
3590 LyXParagraph * par = paragraph;
3593 if (!bibkeys.empty())
3595 bibkeys += par->bibkey->getContents();
3600 // Might be either using bibtex or a child has bibliography
3601 if (bibkeys.empty()) {
3605 LyXParagraph::size_type pos = -1;
3607 // Search for Bibtex or Include inset
3608 while ((inset = par->ReturnNextInsetPointer(pos))) {
3609 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3610 if (!bibkeys.empty())
3612 bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
3613 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3614 string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
3616 if (!bibkeys.empty())
3627 lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3632 bool Buffer::isDepClean(string const & name) const
3634 DEPCLEAN * item = dep_clean;
3635 while (item && item->master != name)
3637 if (!item) return true;
3642 void Buffer::markDepClean(string const & name)
3645 dep_clean = new DEPCLEAN;
3646 dep_clean->clean = true;
3647 dep_clean->master = name;
3648 dep_clean->next = 0;
3650 DEPCLEAN* item = dep_clean;
3651 while (item && item->master != name)
3656 item = new DEPCLEAN;
3658 item->master = name;
3665 void Buffer::Dispatch(string const & command)
3667 // Split command string into command and argument
3668 string cmd, line = frontStrip(command);
3669 string arg = strip(frontStrip(split(line, cmd, ' ')));
3671 Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3675 void Buffer::Dispatch(int action, string const & argument)
3679 MenuExport(this, argument);
3683 lyxerr << "A truly unknown func!" << endl;