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 "support/filetools.h"
80 #include "support/path.h"
86 #include "LaTeXFeatures.h"
87 #include "support/syscall.h"
88 #include "support/lyxlib.h"
89 #include "support/FileInfo.h"
93 // Uncomment this line to enable a workaround for the weird behaviour
94 // of the cursor between a displayed inset and last character
95 // at the upper line. (Alejandro 20.9.96)
96 // #define BREAK_BEFORE_INSET
98 /* Lars, when changing this file sometime in the future to a list,
99 * please check out the figinsets-sideeffects described at the
100 * beginning of figinset.C Matthias (04.07.1996)
104 // all these externs should eventually be removed.
105 extern BufferList bufferlist;
107 extern void MenuExport(Buffer *, string const &);
108 extern LyXAction lyxaction;
111 static const float LYX_FORMAT = 2.15;
113 extern int tex_code_break_column;
115 extern void FreeUpdateTimer();
118 Buffer::Buffer(string const & file, LyXRC * lyxrc, bool ronly)
120 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
122 filepath = OnlyPath(file);
126 dvi_clean_orgd = false; // Heinrich Bauer, 23/03/98
127 dvi_clean_tmpd = false; // Heinrich Bauer, 23/03/98
132 if (read_only || (lyxrc && lyxrc->use_tempdir)) {
133 tmppath = CreateBufferTmpDir();
134 } else tmppath.clear();
140 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
141 // here the buffer should take care that it is
142 // saved properly, before it goes into the void.
144 // make sure that views using this buffer
149 if (!tmppath.empty()) {
150 DestroyBufferTmpDir(tmppath);
153 LyXParagraph * par = paragraph;
154 LyXParagraph * tmppar;
164 bool Buffer::saveParamsAsDefaults()
166 string fname = AddName(AddPath(user_lyxdir, "templates/"),
168 Buffer defaults = Buffer(fname);
170 // Use the current buffer's parameters as default
171 defaults.params = params;
173 // add an empty paragraph. Is this enough?
174 defaults.paragraph = new LyXParagraph;
176 return defaults.writeFile(defaults.filename, false);
180 /// Update window titles of all users
181 // Should work on a list
182 void Buffer::updateTitles() const
184 if (users) users->owner()->updateWindowTitle();
188 /// Reset autosave timer of all users
189 // Should work on a list
190 void Buffer::resetAutosaveTimers() const
192 if (users) users->owner()->resetAutosaveTimer();
196 void Buffer::fileName(string const & newfile)
198 filename = MakeAbsPath(newfile);
199 filepath = OnlyPath(filename);
200 setReadonly(IsFileWriteable(filename) == 0);
205 // candidate for move to BufferView
206 // (at least some parts in the beginning of the func)
209 // changed to be public and have one parameter
210 // if par = 0 normal behavior
211 // else insert behavior
212 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
213 #define USE_PARSE_FUNCTION 1
214 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 the_end_read = parseSingleLyXformat2Token(lex, par, return_par,
271 paragraph = return_par;
277 bool Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
278 LyXParagraph *& return_par,
279 const string & token, int & pos,
280 char & depth, LyXFont & font,
281 LyXParagraph::footnote_flag & footnoteflag,
282 LyXParagraph::footnote_kind & footnotekind)
287 bool the_end_read = false;
289 if (token[0] != '\\') {
290 int n = token.length();
291 for (int i = 0; i < n; ++i) {
292 par->InsertChar(pos, token[i]);
293 par->SetFont(pos, font);
296 } else if (token == "\\i") {
297 inset = new InsetLatexAccent;
299 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());
431 } else if (token == "\\no_isolatin1") { // obsolete
433 } else if (token == "\\no_babel") { // obsolete
435 } else if (token == "\\no_epsfig") { // obsolete
437 } else if (token == "\\epsfig") { // obsolete
438 // Indeed it is obsolete, but we HAVE to be backwards
439 // compatible until 0.14, because otherwise all figures
440 // in existing documents are irretrivably lost. (Asger)
441 params.readGraphicsDriver(lex);
442 } else if (token == "\\quotes_language") {
443 tmpret = lex.FindToken(string_quotes_language);
444 if (tmpret == -1) ++tmpret;
445 if (tmpret != LYX_LAYOUT_DEFAULT) {
446 InsetQuotes::quote_language tmpl =
447 InsetQuotes::EnglishQ;
450 tmpl = InsetQuotes::EnglishQ;
453 tmpl = InsetQuotes::SwedishQ;
456 tmpl = InsetQuotes::GermanQ;
459 tmpl = InsetQuotes::PolishQ;
462 tmpl = InsetQuotes::FrenchQ;
465 tmpl = InsetQuotes::DanishQ;
468 params.quotes_language = tmpl;
470 } else if (token == "\\quotes_times") {
472 switch(lex.GetInteger()) {
474 params.quotes_times = InsetQuotes::SingleQ;
477 params.quotes_times = InsetQuotes::DoubleQ;
480 } else if (token == "\\papersize") {
481 tmpret = lex.FindToken(string_papersize);
485 params.papersize2 = tmpret;
486 } else if (token == "\\paperpackage") {
487 tmpret = lex.FindToken(string_paperpackages);
490 params.paperpackage = BufferParams::PACKAGE_NONE;
492 params.paperpackage = tmpret;
493 } else if (token == "\\use_geometry") {
495 params.use_geometry = lex.GetInteger();
496 } else if (token == "\\use_amsmath") {
498 params.use_amsmath = lex.GetInteger();
499 } else if (token == "\\paperorientation") {
500 tmpret = lex.FindToken(string_orientation);
501 if (tmpret == -1) ++tmpret;
502 if (tmpret != LYX_LAYOUT_DEFAULT)
503 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
504 } else if (token == "\\paperwidth") {
506 params.paperwidth = lex.GetString();
507 } else if (token == "\\paperheight") {
509 params.paperheight = lex.GetString();
510 } else if (token == "\\leftmargin") {
512 params.leftmargin = lex.GetString();
513 } else if (token == "\\topmargin") {
515 params.topmargin = lex.GetString();
516 } else if (token == "\\rightmargin") {
518 params.rightmargin = lex.GetString();
519 } else if (token == "\\bottommargin") {
521 params.bottommargin = lex.GetString();
522 } else if (token == "\\headheight") {
524 params.headheight = lex.GetString();
525 } else if (token == "\\headsep") {
527 params.headsep = lex.GetString();
528 } else if (token == "\\footskip") {
530 params.footskip = lex.GetString();
531 } else if (token == "\\paperfontsize") {
533 params.fontsize = strip(lex.GetString());
534 } else if (token == "\\papercolumns") {
536 params.columns = lex.GetInteger();
537 } else if (token == "\\papersides") {
539 switch(lex.GetInteger()) {
541 case 1: params.sides = LyXTextClass::OneSide; break;
542 case 2: params.sides = LyXTextClass::TwoSides; break;
544 } else if (token == "\\paperpagestyle") {
546 params.pagestyle = strip(lex.GetString());
547 } else if (token == "\\bullet") {
549 int index = lex.GetInteger();
551 int temp_int = lex.GetInteger();
552 params.user_defined_bullets[index].setFont(temp_int);
553 params.temp_bullets[index].setFont(temp_int);
555 temp_int = lex.GetInteger();
556 params.user_defined_bullets[index].setCharacter(temp_int);
557 params.temp_bullets[index].setCharacter(temp_int);
559 temp_int = lex.GetInteger();
560 params.user_defined_bullets[index].setSize(temp_int);
561 params.temp_bullets[index].setSize(temp_int);
563 string temp_str = lex.GetString();
564 if (temp_str != "\\end_bullet") {
565 // this element isn't really necessary for
566 // parsing but is easier for humans
567 // to understand bullets. Put it back and
568 // set a debug message?
569 lex.printError("\\end_bullet expected, got" + temp_str);
570 //how can I put it back?
572 } else if (token == "\\bulletLaTeX") {
574 int index = lex.GetInteger();
576 string temp_str = lex.GetString(), sum_str;
577 while (temp_str != "\\end_bullet") {
578 // this loop structure is needed when user
579 // enters an empty string since the first
580 // thing returned will be the \\end_bullet
582 // if the LaTeX entry has spaces. Each element
583 // therefore needs to be read in turn
586 temp_str = lex.GetString();
588 params.user_defined_bullets[index].setText(sum_str);
589 params.temp_bullets[index].setText(sum_str);
590 } else if (token == "\\secnumdepth") {
592 params.secnumdepth = lex.GetInteger();
593 } else if (token == "\\tocdepth") {
595 params.tocdepth = lex.GetInteger();
596 } else if (token == "\\baselinestretch") { // obsolete
597 lex.nextToken(); // should not be used directly
599 // Will probably keep a kind of support just for
601 params.spacing.set(Spacing::Other, lex.GetFloat());
602 } else if (token == "\\spacing") {
604 string tmp = strip(lex.GetString());
605 if (tmp == "single") {
606 params.spacing.set(Spacing::Single);
607 } else if (tmp == "onehalf") {
608 params.spacing.set(Spacing::Onehalf);
609 } else if (tmp == "double") {
610 params.spacing.set(Spacing::Double);
611 } else if (tmp == "other") {
613 params.spacing.set(Spacing::Other,
616 lex.printError("Unknown spacing token: '$$Token'");
618 } else if (token == "\\float_placement") {
620 params.float_placement = lex.GetString();
621 } else if (token == "\\cursor") { // obsolete
622 // this is obsolete, so we just skip it.
624 } else if (token == "\\family") {
626 font.setLyXFamily(lex.GetString());
627 } else if (token == "\\series") {
629 font.setLyXSeries(lex.GetString());
630 } else if (token == "\\shape") {
632 font.setLyXShape(lex.GetString());
633 } else if (token == "\\size") {
635 font.setLyXSize(lex.GetString());
636 } else if (token == "\\latex") {
638 string tok = lex.GetString();
639 // This is dirty, but gone with LyX3. (Asger)
640 if (tok == "no_latex")
641 font.setLatex(LyXFont::OFF);
642 else if (tok == "latex")
643 font.setLatex(LyXFont::ON);
644 else if (tok == "default")
645 font.setLatex(LyXFont::INHERIT);
647 lex.printError("Unknown LaTeX font flag "
649 } else if (token == "\\direction") {
651 string tok = lex.GetString();
653 font.setDirection(LyXFont::LTR_DIR);
654 else if (tok == "rtl")
655 font.setDirection(LyXFont::RTL_DIR);
656 else if (tok == "default")
657 font.setDirection(LyXFont::INHERIT_DIR);
659 lex.printError("Unknown font flag "
661 } else if (token == "\\emph") {
663 font.setEmph(font.setLyXMisc(lex.GetString()));
664 } else if (token == "\\bar") {
666 string tok = lex.GetString();
667 // This is dirty, but gone with LyX3. (Asger)
669 font.setUnderbar(LyXFont::ON);
670 else if (tok == "no")
671 font.setUnderbar(LyXFont::OFF);
672 else if (tok == "default")
673 font.setUnderbar(LyXFont::INHERIT);
675 lex.printError("Unknown bar font flag "
677 } else if (token == "\\noun") {
679 font.setNoun(font.setLyXMisc(lex.GetString()));
680 } else if (token == "\\color") {
682 font.setLyXColor(lex.GetString());
683 } else if (token == "\\align") {
684 tmpret = lex.FindToken(string_align);
685 if (tmpret == -1) ++tmpret;
686 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
688 for (; tmpret > 0; --tmpret)
689 tmpret2 = tmpret2 * 2;
690 par->align = LyXAlignment(tmpret2);
692 } else if (token == "\\added_space_top") {
694 par->added_space_top = lex.GetString();
695 } else if (token == "\\added_space_bottom") {
697 par->added_space_bottom = lex.GetString();
698 } else if (token == "\\pextra_type") {
700 par->pextra_type = lex.GetInteger();
701 } else if (token == "\\pextra_width") {
703 par->pextra_width = lex.GetString();
704 } else if (token == "\\pextra_widthp") {
706 par->pextra_widthp = lex.GetString();
707 } else if (token == "\\pextra_alignment") {
709 par->pextra_alignment = lex.GetInteger();
710 } else if (token == "\\pextra_hfill") {
712 par->pextra_hfill = lex.GetInteger();
713 } else if (token == "\\pextra_start_minipage") {
715 par->pextra_start_minipage = lex.GetInteger();
716 } else if (token == "\\labelwidthstring") {
718 par->labelwidthstring = lex.GetString();
719 /* do not delete this token, it is still needed! */
720 } else if (token == "\\end_inset") {
721 /* simple ignore this. The insets do not have
723 // but insets should read it, it is a part of
724 //the inset isn't it? Lgb.
725 } else if (token == "\\begin_inset") {
727 tmptok = lex.GetString();
728 /* test the different insets */
729 if (tmptok == "Quotes") {
730 inset = new InsetQuotes;
732 par->InsertChar(pos, LyXParagraph::META_INSET);
733 par->InsertInset(pos, inset);
734 par->SetFont(pos, font);
736 } else if (tmptok == "\\i") {
737 inset = new InsetLatexAccent;
739 par->InsertChar(pos, LyXParagraph::META_INSET);
740 par->InsertInset(pos, inset);
741 par->SetFont(pos, font);
743 } else if (tmptok == "FormulaMacro") {
744 inset = new InsetFormulaMacro;
746 par->InsertChar(pos, LyXParagraph::META_INSET);
747 par->InsertInset(pos, inset);
748 par->SetFont(pos, font);
750 } else if (tmptok == "Formula") {
751 inset = new InsetFormula;
753 par->InsertChar(pos, LyXParagraph::META_INSET);
754 par->InsertInset(pos, inset);
755 par->SetFont(pos, font);
757 } else if (tmptok == "Figure") {
758 inset = new InsetFig(100, 100, this);
760 par->InsertChar(pos, LyXParagraph::META_INSET);
761 par->InsertInset(pos, inset);
762 par->SetFont(pos, font);
764 } else if (tmptok == "Info") {
765 inset = new InsetInfo;
767 par->InsertChar(pos, LyXParagraph::META_INSET);
768 par->InsertInset(pos, inset);
769 par->SetFont(pos, font);
771 } else if (tmptok == "Include") {
772 inset = new InsetInclude(string(), this);
774 par->InsertChar(pos, LyXParagraph::META_INSET);
775 par->InsertInset(pos, inset);
776 par->SetFont(pos, font);
778 } else if (tmptok == "ERT") {
779 inset = new InsetERT(this);
781 par->InsertChar(pos, LyXParagraph::META_INSET);
782 par->InsertInset(pos, inset);
783 par->SetFont(pos, font);
785 } else if (tmptok == "Text") {
786 inset = new InsetText(this);
788 par->InsertChar(pos, LyXParagraph::META_INSET);
789 par->InsertInset(pos, inset);
790 par->SetFont(pos, font);
792 } else if (tmptok == "GRAPHICS") {
793 inset = new InsetGraphics;
795 par->InsertChar(pos, LyXParagraph::META_INSET);
796 par->InsertInset(pos, inset);
797 par->SetFont(pos, font);
798 } else if (tmptok == "LatexCommand") {
801 if (inscmd.getCmdName() == "cite") {
802 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
803 } else if (inscmd.getCmdName() == "bibitem") {
804 lex.printError("Wrong place for bibitem");
805 inset = inscmd.Clone();
806 } else if (inscmd.getCmdName() == "BibTeX") {
807 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
808 } else if (inscmd.getCmdName() == "index") {
809 inset = new InsetIndex(inscmd.getContents());
810 } else if (inscmd.getCmdName() == "include") {
811 inset = new InsetInclude(inscmd.getContents(), this);
812 } else if (inscmd.getCmdName() == "label") {
813 inset = new InsetLabel(inscmd.getCommand());
814 } else if (inscmd.getCmdName() == "url"
815 || inscmd.getCmdName() == "htmlurl") {
816 inset = new InsetUrl(inscmd.getCommand());
817 } else if (inscmd.getCmdName() == "ref"
818 || inscmd.getCmdName() == "pageref") {
819 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
820 inset = new InsetRef(inscmd, this);
822 #warning Verify that this else clause is still needed. (Lgb)
824 // This condition comes from a
825 // temporary solution to the latexdel
826 // ref inset that was transformed to
827 // an empty ref inset plus the body
828 // surronded by latexdel insets
830 string cont, opt, tmptmptok, cmdname;
832 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
837 tmptmptok = lex.GetString();
838 if(tmptmptok[0] == '\\') {
839 if( tmptmptok == "\\backslash")
849 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
854 tmptmptok = lex.GetString();
855 if(tmptmptok[0] == '\\') {
856 if( tmptmptok == "\\backslash")
866 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
872 cmdname = "\\" + inscmd.getCmdName();
873 cmdname += "[" + cont + "]";
874 cmdname += "{" + opt + "}";
875 inset = new InsetRef(cmdname, this);
878 } else if (inscmd.getCmdName() == "tableofcontents") {
879 inset = new InsetTOC(this);
880 } else if (inscmd.getCmdName() == "listoffigures") {
881 inset = new InsetLOF(this);
882 } else if (inscmd.getCmdName() == "listofalgorithms") {
883 inset = new InsetLOA(this);
884 } else if (inscmd.getCmdName() == "listoftables") {
885 inset = new InsetLOT(this);
886 } else if (inscmd.getCmdName() == "printindex") {
887 inset = new InsetPrintIndex(this);
888 } else if (inscmd.getCmdName() == "lyxparent") {
889 inset = new InsetParent(inscmd.getContents(), this);
893 par->InsertChar(pos, LyXParagraph::META_INSET);
894 par->InsertInset(pos, inset);
895 par->SetFont(pos, font);
899 } else if (token == "\\InsetQuotes") {
900 inset = new InsetQuotes;
902 par->InsertChar(pos, LyXParagraph::META_INSET);
903 par->InsertInset(pos, inset);
904 par->SetFont(pos, font);
906 } else if (token == "\\InsetFormula") {
907 inset = new InsetFormula;
909 par->InsertChar(pos, LyXParagraph::META_INSET);
910 par->InsertInset(pos, inset);
911 par->SetFont(pos, font);
913 } else if (token == "\\SpecialChar") {
914 inset = new InsetSpecialChar;
916 par->InsertChar(pos, LyXParagraph::META_INSET);
917 par->InsertInset(pos, inset);
918 par->SetFont(pos, font);
920 } else if (token == "\\Figure") {
921 inset = new InsetFig(100, 100, this);
923 par->InsertChar(pos, LyXParagraph::META_INSET);
924 par->InsertInset(pos, inset);
925 par->SetFont(pos, font);
927 } else if (token == "\\newline") { // soon obsolete
929 par->InsertChar(pos, LyXParagraph::META_NEWLINE);
930 par->SetFont(pos, font);
932 inset = new InsetSpecialChar(InsetSpecialChar::NEWLINE);
933 par->InsertChar(pos, LyXParagraph::META_INSET);
934 par->InsertInset(pos, inset);
935 par->SetFont(pos, font);
938 } else if (token == "\\LyXTable") {
939 par->table = new LyXTable(lex);
940 } else if (token == "\\hfill") {
941 par->InsertChar(pos, LyXParagraph::META_HFILL);
942 par->SetFont(pos, font);
944 } else if (token == "\\protected_separator") { // obsolete
946 inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
947 par->InsertChar(pos, LyXParagraph::META_INSET);
948 par->InsertInset(pos, inset);
949 par->SetFont(pos, font);
951 par->InsertChar(pos, LyXParagraph::META_PROTECTED_SEPARATOR);
952 par->SetFont(pos, font);
955 } else if (token == "\\bibitem") { // ale970302
957 par->bibkey = new InsetBibKey;
958 par->bibkey->Read(lex);
959 }else if (token == "\\backslash") {
960 par->InsertChar(pos, '\\');
961 par->SetFont(pos, font);
963 }else if (token == "\\the_end") {
966 // This should be insurance for the future: (Asger)
967 lex.printError("Unknown token `$$Token'. "
968 "Inserting as text.");
969 int n = token.length();
970 for (int i = 0; i < n; ++i) {
971 par->InsertChar(pos, token[i]);
972 par->SetFont(pos, font);
979 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
985 token = lex.GetString();
986 if (token == "\\lyxformat") { // the first token _must_ be...
988 format = lex.GetFloat();
990 if (LYX_FORMAT - format > 0.05) {
991 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
994 if (format - LYX_FORMAT > 0.05) {
995 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
998 bool the_end = readLyXformat2(lex, par);
999 // Formats >= 2.13 support "\the_end" marker
1006 WriteAlert(_("Warning!"),
1007 _("Reading of document is not complete"),
1008 _("Maybe the document is truncated"));
1009 // We simulate a safe reading anyways to allow
1010 // users to take the chance... (Asger)
1014 WriteAlert(_("ERROR!"),
1015 _("Old LyX file format found. "
1016 "Use LyX 0.10.x to read this!"));
1020 } else { // "\\lyxformat" not found
1021 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1024 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1030 // Should probably be moved to somewhere else: BufferView? LyXView?
1031 bool Buffer::save(bool makeBackup) const
1033 // We don't need autosaves in the immediate future. (Asger)
1034 resetAutosaveTimers();
1038 string s = fileName() + '~';
1039 // Rename is the wrong way of making a backup,
1040 // this is the correct way.
1041 /* truss cp fil fil2:
1042 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
1043 stat("LyXVC.lyx", 0xEFFFF688) = 0
1044 open("LyXVC.lyx", O_RDONLY) = 3
1045 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1046 fstat(4, 0xEFFFF508) = 0
1047 fstat(3, 0xEFFFF508) = 0
1048 read(3, " # T h i s f i l e w".., 8192) = 5579
1049 write(4, " # T h i s f i l e w".., 5579) = 5579
1050 read(3, 0xEFFFD4A0, 8192) = 0
1053 chmod("LyXVC3.lyx", 0100644) = 0
1054 lseek(0, 0, SEEK_CUR) = 46440
1058 // Should proabaly have some more error checking here.
1059 // Should be cleaned up in 0.13, at least a bit.
1060 // Doing it this way, also makes the inodes stay the same.
1061 // This is still not a very good solution, in particular we
1062 // might loose the owner of the backup.
1063 FileInfo finfo(fileName());
1064 if (finfo.exist()) {
1065 mode_t fmode = finfo.getMode();
1066 struct utimbuf * times = new struct utimbuf;
1068 times->actime = finfo.getAccessTime();
1069 times->modtime = finfo.getModificationTime();
1070 ifstream ifs(fileName().c_str());
1071 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1076 ::chmod(s.c_str(), fmode);
1078 if (::utime(s.c_str(), times)) {
1079 lyxerr << "utime error." << endl;
1082 lyxerr << "LyX was not able to make "
1083 "backupcopy. Beware." << endl;
1089 if (writeFile(fileName(), false)) {
1092 // now delete the autosavefile
1093 string a = OnlyPath(fileName());
1095 a += OnlyFilename(fileName());
1097 FileInfo fileinfo(a);
1098 if (fileinfo.exist()) {
1099 if (::remove(a.c_str()) != 0) {
1100 WriteFSAlert(_("Could not delete "
1101 "auto-save file!"), a);
1105 // Saving failed, so backup is not backup
1107 string s = fileName() + '~';
1108 ::rename(s.c_str(), fileName().c_str());
1116 // Returns false if unsuccesful
1117 bool Buffer::writeFile(string const & fname, bool flag) const
1119 // if flag is false writeFile will not create any GUI
1120 // warnings, only cerr.
1121 // Needed for autosave in background or panic save (Matthias 120496)
1123 if (read_only && (fname == filename)) {
1124 // Here we should come with a question if we should
1125 // perform the write anyway.
1127 lyxerr << _("Error! Document is read-only: ")
1130 WriteAlert(_("Error! Document is read-only: "),
1135 FileInfo finfo(fname);
1136 if (finfo.exist() && !finfo.writable()) {
1137 // Here we should come with a question if we should
1138 // try to do the save anyway. (i.e. do a chmod first)
1140 lyxerr << _("Error! Cannot write file: ")
1143 WriteFSAlert(_("Error! Cannot write file: "),
1148 ofstream ofs(fname.c_str());
1151 lyxerr << _("Error! Cannot open file: ")
1154 WriteFSAlert(_("Error! Cannot open file: "),
1158 // The top of the file should not be written by params.
1160 // write out a comment in the top of the file
1161 ofs << '#' << LYX_DOCVERSION
1162 << " created this file. For more info see http://www.lyx.org/\n";
1163 ofs.setf(ios::showpoint|ios::fixed);
1165 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1167 // now write out the buffer paramters.
1168 params.writeFile(ofs);
1170 char footnoteflag = 0;
1173 // this will write out all the paragraphs
1174 // using recursive descent.
1175 paragraph->writeFile(ofs, params, footnoteflag, depth);
1177 // Write marker that shows file is complete
1178 ofs << "\n\\the_end" << endl;
1180 // how to check if close went ok?
1185 void Buffer::writeFileAscii(string const & fname, int linelen)
1187 LyXFont font1, font2;
1189 char c, footnoteflag = 0, depth = 0;
1191 LyXParagraph::size_type i;
1192 int j, h, ltype = 0, ltype_depth = 0,
1193 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1196 bool ref_printed = false;
1198 ofstream ofs(fname.c_str());
1200 WriteFSAlert(_("Error: Cannot write file:"), fname);
1204 string fname1 = TmpFileName();
1205 LyXParagraph * par = paragraph;
1209 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1211 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1213 /* begins a footnote environment ? */
1214 if (footnoteflag != par->footnoteflag) {
1215 footnoteflag = par->footnoteflag;
1217 j = strlen(string_footnotekinds[par->footnotekind])+4;
1218 if (currlinelen + j > linelen)
1221 << string_footnotekinds[par->footnotekind] << "] ";
1226 /* begins or ends a deeper area ?*/
1227 if (depth != par->depth) {
1228 if (par->depth > depth) {
1229 while (par->depth > depth) {
1234 while (par->depth < depth) {
1240 /* First write the layout */
1241 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1242 if (tmp == "Itemize") {
1244 ltype_depth = depth+1;
1245 } else if (tmp == "Enumerate") {
1247 ltype_depth = depth+1;
1248 } else if (strstr(tmp.c_str(), "ection")) {
1250 ltype_depth = depth+1;
1251 } else if (strstr(tmp.c_str(), "aragraph")) {
1253 ltype_depth = depth+1;
1254 } else if (tmp == "Description") {
1256 ltype_depth = depth+1;
1257 } else if (tmp == "Abstract") {
1260 } else if (tmp == "Bibliography") {
1268 /* maybe some vertical spaces */
1270 /* the labelwidthstring used in lists */
1274 /* some pagebreaks? */
1278 /* what about the alignment */
1281 /* dummy layout, that means a footnote ended */
1282 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1287 /* It might be a table */
1290 if (!lyxrc->ascii_roff_command.empty() &&
1291 lyxrc->ascii_roff_command != "none") {
1292 RoffAsciiTable(ofs, par);
1299 cells = par->table->columns;
1300 clen = new int [cells];
1301 memset(clen, 0, sizeof(int) * cells);
1302 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1303 c = par->GetChar(i);
1304 if (c == LyXParagraph::META_INSET) {
1305 if ((inset = par->GetInset(i))) {
1309 inset->Latex(ost, -1);
1310 h += ost.str().length();
1313 inset->Latex(ost, -1);
1315 char * tmp = ost.str();
1321 ofstream fs(fname1.c_str());
1323 WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1326 inset->Latex(fs, -1);
1327 h += fs.tellp() - 1;
1328 ::remove(fname1.c_str());
1331 } else if (c == LyXParagraph::META_NEWLINE) {
1335 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1343 font1 = LyXFont(LyXFont::ALL_INHERIT);
1345 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1346 if (!i && !footnoteflag && !noparbreak){
1348 for(j = 0; j < depth; ++j)
1350 currlinelen = depth * 2;
1352 case 0: /* Standard */
1353 case 4: /* (Sub)Paragraph */
1354 case 5: /* Description */
1356 case 6: /* Abstract */
1357 ofs << "Abstract\n\n";
1359 case 7: /* Bibliography */
1361 ofs << "References\n\n";
1366 ofs << par->labelstring << " ";
1369 if (ltype_depth > depth) {
1370 for(j = ltype_depth - 1; j > depth; --j)
1372 currlinelen += (ltype_depth-depth)*2;
1375 for(j = 0; j < cells; ++j) {
1377 for(h = 0; h < (clen[j] + 1);
1382 for(j = 0; j < depth; ++j)
1384 currlinelen = depth * 2;
1385 if (ltype_depth > depth) {
1386 for(j = ltype_depth;
1389 currlinelen += (ltype_depth-depth)*2;
1394 font2 = par->GetFontSettings(i);
1395 if (font1.latex() != font2.latex()) {
1396 if (font2.latex() == LyXFont::OFF)
1404 c = par->GetChar(i);
1408 case LyXParagraph::META_INSET:
1409 if ((inset = par->GetInset(i))) {
1411 inset->Latex(ofs, -1);
1412 currlinelen += (ofs.tellp() - fpos);
1413 actpos += (ofs.tellp() - fpos) - 1;
1416 case LyXParagraph::META_NEWLINE:
1418 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1419 for(j = actpos; j < clen[cell - 1]; ++j)
1422 for(j = 0; j < depth; ++j)
1424 currlinelen = depth*2;
1425 if (ltype_depth > depth) {
1426 for(j = ltype_depth; j > depth; --j)
1428 currlinelen += (ltype_depth-depth) * 2;
1430 for(j = 0; j < cells; ++j) {
1432 for(h = 0; h < (clen[j] + 1); ++h)
1436 for(j = 0; j < depth; ++j)
1438 currlinelen = depth * 2;
1439 if (ltype_depth > depth) {
1440 for(j = ltype_depth;
1443 currlinelen += (ltype_depth-depth)*2;
1449 j < clen[cell - 1]; ++j)
1455 currlinelen = actpos = 0;
1458 for(j = 0; j < depth; ++j)
1460 currlinelen = depth * 2;
1461 if (ltype_depth > depth) {
1462 for(j = ltype_depth;
1465 currlinelen += (ltype_depth - depth) * 2;
1469 case LyXParagraph::META_HFILL:
1473 case LyXParagraph::META_PROTECTED_SEPARATOR:
1481 if (currlinelen > linelen - 10
1482 && c == ' ' && i + 2 < par->size()) {
1484 for(j = 0; j < depth; ++j)
1486 currlinelen = depth * 2;
1487 if (ltype_depth > depth) {
1488 for(j = ltype_depth;
1491 currlinelen += (ltype_depth-depth)*2;
1493 } else if (c != '\0')
1496 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1502 for(j = actpos; j < clen[cell - 1]; ++j)
1505 for(j = 0; j < depth; ++j)
1507 currlinelen = depth * 2;
1508 if (ltype_depth > depth) {
1509 for(j = ltype_depth; j > depth; --j)
1511 currlinelen += (ltype_depth - depth) * 2;
1513 for(j = 0; j < cells; ++j) {
1515 for(h = 0; h < (clen[j] + 1); ++h)
1528 void Buffer::makeLaTeXFile(string const & fname,
1529 string const & original_path,
1530 bool nice, bool only_body)
1532 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1534 niceFile = nice; // this will be used by Insetincludes.
1536 tex_code_break_column = lyxrc->ascii_linelen;
1538 LyXTextClass const & tclass =
1539 textclasslist.TextClass(params.textclass);
1541 ofstream ofs(fname.c_str());
1543 WriteFSAlert(_("Error: Cannot open file: "), fname);
1547 // validate the buffer.
1548 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1549 LaTeXFeatures features(tclass.numLayouts());
1551 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1554 // The starting paragraph of the coming rows is the
1555 // first paragraph of the document. (Asger)
1556 texrow.start(paragraph, 0);
1560 if (!only_body && nice) {
1561 LFile += "%% " LYX_DOCVERSION " created this file. "
1562 "For more info, see http://www.lyx.org/.\n";
1563 LFile += "%% Do not edit unless you really know what you are doing.\n";
1567 lyxerr.debug() << "lyx header finished" << endl;
1568 // There are a few differences between nice LaTeX and usual files:
1569 // usual is \batchmode and has a
1570 // special input@path to allow the including of figures
1571 // with either \input or \includegraphics (what figinsets do).
1572 // batchmode is not set if there is a tex_code_break_column.
1573 // In this case somebody is interested in the generated LaTeX,
1574 // so this is OK. input@path is set when the actual parameter
1575 // original_path is set. This is done for usual tex-file, but not
1576 // for nice-latex-file. (Matthias 250696)
1579 // code for usual, NOT nice-latex-file
1580 LFile += "\\batchmode\n"; // changed
1581 // from \nonstopmode
1584 if (!original_path.empty()) {
1585 LFile += "\\makeatletter\n";
1587 LFile += "\\def\\input@path{{" + original_path
1590 LFile += "\\makeatother\n";
1594 LFile += "\\documentclass";
1596 string options; // the document class options.
1598 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1599 // only write if existing in list (and not default)
1600 options += params.fontsize;
1605 if (!params.use_geometry &&
1606 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1607 switch (params.papersize) {
1608 case BufferParams::PAPER_A4PAPER:
1609 options += "a4paper,";
1611 case BufferParams::PAPER_USLETTER:
1612 options += "letterpaper,";
1614 case BufferParams::PAPER_A5PAPER:
1615 options += "a5paper,";
1617 case BufferParams::PAPER_B5PAPER:
1618 options += "b5paper,";
1620 case BufferParams::PAPER_EXECUTIVEPAPER:
1621 options += "executivepaper,";
1623 case BufferParams::PAPER_LEGALPAPER:
1624 options += "legalpaper,";
1630 if (params.sides != tclass.sides()) {
1631 switch (params.sides) {
1632 case LyXTextClass::OneSide:
1633 options += "oneside,";
1635 case LyXTextClass::TwoSides:
1636 options += "twoside,";
1643 if (params.columns != tclass.columns()) {
1644 if (params.columns == 2)
1645 options += "twocolumn,";
1647 options += "onecolumn,";
1650 if (!params.use_geometry
1651 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1652 options += "landscape,";
1654 // language should be a parameter to \documentclass
1655 if (params.language != "default") {
1656 if (params.language == "hebrew")
1657 options += "english,";
1658 else if (lyxrc->rtl_support)
1659 options += "hebrew,";
1660 options += params.language + ',';
1661 } else if (lyxrc->rtl_support)
1662 options += "hebrew,english,";
1664 // the user-defined options
1665 if (!params.options.empty()) {
1666 options += params.options + ',';
1669 if (!options.empty()){
1670 options = strip(options, ',');
1677 LFile += textclasslist.LatexnameOfClass(params.textclass);
1680 // end of \documentclass defs
1682 // font selection must be done before loading fontenc.sty
1683 if (params.fonts != "default") {
1684 LFile += "\\usepackage{" + params.fonts + "}\n";
1687 // this one is not per buffer
1688 if (lyxrc->fontenc != "default") {
1689 LFile += "\\usepackage[" + lyxrc->fontenc
1693 if (params.inputenc != "default") {
1694 LFile += "\\usepackage[" + params.inputenc
1699 /* at the very beginning the text parameters */
1700 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1701 switch (params.paperpackage) {
1702 case BufferParams::PACKAGE_A4:
1703 LFile += "\\usepackage{a4}\n";
1706 case BufferParams::PACKAGE_A4WIDE:
1707 LFile += "\\usepackage{a4wide}\n";
1710 case BufferParams::PACKAGE_WIDEMARGINSA4:
1711 LFile += "\\usepackage[widemargins]{a4}\n";
1716 if (params.use_geometry) {
1717 LFile += "\\usepackage{geometry}\n";
1719 LFile += "\\geometry{verbose";
1720 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1721 LFile += ",landscape";
1722 switch (params.papersize2) {
1723 case BufferParams::VM_PAPER_CUSTOM:
1724 if (!params.paperwidth.empty())
1725 LFile += ",paperwidth="
1726 + params.paperwidth;
1727 if (!params.paperheight.empty())
1728 LFile += ",paperheight="
1729 + params.paperheight;
1731 case BufferParams::VM_PAPER_USLETTER:
1732 LFile += ",letterpaper";
1734 case BufferParams::VM_PAPER_USLEGAL:
1735 LFile += ",legalpaper";
1737 case BufferParams::VM_PAPER_USEXECUTIVE:
1738 LFile += ",executivepaper";
1740 case BufferParams::VM_PAPER_A3:
1741 LFile += ",a3paper";
1743 case BufferParams::VM_PAPER_A4:
1744 LFile += ",a4paper";
1746 case BufferParams::VM_PAPER_A5:
1747 LFile += ",a5paper";
1749 case BufferParams::VM_PAPER_B3:
1750 LFile += ",b3paper";
1752 case BufferParams::VM_PAPER_B4:
1753 LFile += ",b4paper";
1755 case BufferParams::VM_PAPER_B5:
1756 LFile += ",b5paper";
1759 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1760 switch (lyxrc->default_papersize) {
1761 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1762 case BufferParams::PAPER_USLETTER:
1763 LFile += ",letterpaper";
1765 case BufferParams::PAPER_LEGALPAPER:
1766 LFile += ",legalpaper";
1768 case BufferParams::PAPER_EXECUTIVEPAPER:
1769 LFile += ",executivepaper";
1771 case BufferParams::PAPER_A3PAPER:
1772 LFile += ",a3paper";
1774 case BufferParams::PAPER_A4PAPER:
1775 LFile += ",a4paper";
1777 case BufferParams::PAPER_A5PAPER:
1778 LFile += ",a5paper";
1780 case BufferParams::PAPER_B5PAPER:
1781 LFile += ",b5paper";
1785 if (!params.topmargin.empty())
1786 LFile += ",tmargin=" + params.topmargin;
1787 if (!params.bottommargin.empty())
1788 LFile += ",bmargin=" + params.bottommargin;
1789 if (!params.leftmargin.empty())
1790 LFile += ",lmargin=" + params.leftmargin;
1791 if (!params.rightmargin.empty())
1792 LFile += ",rmargin=" + params.rightmargin;
1793 if (!params.headheight.empty())
1794 LFile += ",headheight=" + params.headheight;
1795 if (!params.headsep.empty())
1796 LFile += ",headsep=" + params.headsep;
1797 if (!params.footskip.empty())
1798 LFile += ",footskip=" + params.footskip;
1802 if (params.use_amsmath
1803 && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1804 LFile += "\\usepackage{amsmath}\n";
1807 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1808 if (params.pagestyle == "fancy") {
1809 LFile += "\\usepackage{fancyhdr}\n";
1812 LFile += "\\pagestyle{" + params.pagestyle + "}\n";
1816 // We try to load babel late, in case it interferes
1817 // with other packages.
1818 if (params.language != "default" || lyxrc->rtl_support ) {
1819 LFile += "\\usepackage{babel}\n";
1823 if (params.secnumdepth != tclass.secnumdepth()) {
1824 LFile += "\\setcounter{secnumdepth}{";
1825 LFile += tostr(params.secnumdepth);
1829 if (params.tocdepth != tclass.tocdepth()) {
1830 LFile += "\\setcounter{tocdepth}{";
1831 LFile += tostr(params.tocdepth);
1836 if (params.paragraph_separation) {
1837 switch (params.defskip.kind()) {
1838 case VSpace::SMALLSKIP:
1839 LFile += "\\setlength\\parskip{\\smallskipamount}\n";
1841 case VSpace::MEDSKIP:
1842 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1844 case VSpace::BIGSKIP:
1845 LFile += "\\setlength\\parskip{\\bigskipamount}\n";
1847 case VSpace::LENGTH:
1848 LFile += "\\setlength\\parskip{"
1849 + params.defskip.length().asLatexString()
1852 default: // should never happen // Then delete it.
1853 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1858 LFile += "\\setlength\\parindent{0pt}\n";
1862 // Write out what we've generated so far...and reset LFile
1866 // Now insert the LyX specific LaTeX commands...
1867 string preamble, tmppreamble;
1869 // The optional packages;
1870 preamble = features.getPackages(params);
1872 // this might be useful...
1873 preamble += "\n\\makeatletter\n\n";
1875 // Some macros LyX will need
1876 tmppreamble = features.getMacros(params);
1878 if (!tmppreamble.empty()) {
1879 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1880 "LyX specific LaTeX commands.\n"
1881 + tmppreamble + '\n';
1884 // the text class specific preamble
1885 tmppreamble = features.getTClassPreamble(params);
1886 if (!tmppreamble.empty()) {
1887 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1888 "Textclass specific LaTeX commands.\n"
1889 + tmppreamble + '\n';
1892 /* the user-defined preamble */
1893 if (!params.preamble.empty()) {
1894 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1895 "User specified LaTeX commands.\n"
1896 + params.preamble + '\n';
1899 preamble += "\\makeatother\n\n";
1901 // Itemize bullet settings need to be last in case the user
1902 // defines their own bullets that use a package included
1903 // in the user-defined preamble -- ARRae
1904 // Actually it has to be done much later than that
1905 // since some packages like frenchb make modifications
1906 // at \begin{document} time -- JMarc
1908 for (int i = 0; i < 4; ++i) {
1909 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1910 if (bullets_def.empty())
1911 bullets_def="\\AtBeginDocument{\n";
1912 bullets_def += " \\renewcommand{\\labelitemi";
1914 // `i' is one less than the item to modify
1921 bullets_def += "ii";
1927 bullets_def += "}{" +
1928 params.user_defined_bullets[i].getText()
1933 if (!bullets_def.empty())
1934 preamble += bullets_def + "}\n\n";
1936 for (int j = countChar(preamble, '\n'); j-- ;) {
1943 LFile += "\\begin{document}\n\n";
1947 lyxerr.debug() << "preamble finished, now the body." << endl;
1949 bool was_title = false;
1950 bool already_title = false;
1956 LyXParagraph * par = paragraph;
1962 lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
1964 LyXLayout const & layout =
1965 textclasslist.Style(params.textclass,
1968 if (layout.intitle) {
1969 if (already_title) {
1970 lyxerr <<"Error in MakeLatexFile: You"
1971 " should not mix title layouts"
1972 " with normal ones." << endl;
1975 } else if (was_title && !already_title) {
1976 LFile += "\\maketitle\n";
1978 already_title = true;
1981 // We are at depth 0 so we can just use
1982 // ordinary \footnote{} generation
1983 // flag this with ftcount
1985 if (layout.isEnvironment()
1986 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
1987 par = par->TeXEnvironment(LFile, texrow,
1988 ftnote, ft_texrow, ftcount);
1990 par = par->TeXOnePar(LFile, texrow,
1991 ftnote, ft_texrow, ftcount);
1994 // Write out what we've generated...and reset LFile
1997 LFile += "\\addtocounter{footnote}{-";
1998 LFile += tostr(ftcount - 1);
2002 texrow += ft_texrow;
2007 if (loop_count == 2) {
2008 // fwrite()ing every second time through the loop
2009 // gains a few extra % of speed; going higher than
2010 // 2 will slow things down again. I'll look at
2011 // LFile.length() in a future revision. ARRae
2018 // It might be that we only have a title in this document
2019 if (was_title && !already_title) {
2020 LFile += "\\maketitle\n";
2025 LFile += "\\end{document}\n";
2028 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2030 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2034 // Just to be sure. (Asger)
2037 // Write out what we've generated...and reset LFile
2041 // tex_code_break_column's value is used to decide
2042 // if we are in batchmode or not (within mathed_write()
2043 // in math_write.C) so we must set it to a non-zero
2044 // value when we leave otherwise we save incorrect .lyx files.
2045 tex_code_break_column = lyxrc->ascii_linelen;
2047 // How to check if the close went ok when using fstreams
2049 lyxerr.debug() << "Finished making latex file." << endl;
2053 bool Buffer::isLatex() const
2055 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2059 bool Buffer::isLinuxDoc() const
2061 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2065 bool Buffer::isLiterate() const
2067 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2071 bool Buffer::isDocBook() const
2073 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2077 bool Buffer::isSGML() const
2079 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2080 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2084 void Buffer::sgmlOpenTag(ostream & os, int depth,
2085 string const & latexname) const
2087 os << string(depth, ' ') << "<" << latexname << ">\n";
2091 void Buffer::sgmlCloseTag(ostream & os, int depth,
2092 string const & latexname) const
2094 os << string(depth, ' ') << "</" << latexname << ">\n";
2098 void Buffer::makeLinuxDocFile(string const & fname, int column)
2100 LyXParagraph * par = paragraph;
2102 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2103 string environment_stack[10];
2106 int depth = 0; /* paragraph depth */
2108 ofstream ofs(fname.c_str());
2111 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2115 tex_code_break_column = column;
2118 if (params.preamble.empty()) {
2119 ofs << "<!doctype linuxdoc system>\n\n";
2122 ofs << "<!doctype linuxdoc system \n [ "
2123 << params.preamble << " \n]>\n\n";
2126 ofs << "<!-- " << LYX_DOCVERSION
2127 << " created this file. For more info see http://www.lyx.org/"
2130 if(params.options.empty())
2131 sgmlOpenTag(ofs, 0, top_element);
2133 string top = top_element;
2135 top += params.options;
2136 sgmlOpenTag(ofs, 0, top);
2140 int desc_on = 0; /* description mode*/
2141 LyXLayout const & style =
2142 textclasslist.Style(users->buffer()->params.textclass,
2144 par->AutoDeleteInsets();
2146 /* treat <toc> as a special case for compatibility with old code */
2147 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2148 Inset * inset = par->GetInset(0);
2149 char lyx_code = inset->LyxCode();
2150 if (lyx_code == Inset::TOC_CODE){
2151 string temp = "toc";
2152 sgmlOpenTag(ofs, depth, temp);
2155 linuxDocHandleFootnote(ofs, par, depth);
2160 // environment tag closing
2161 for( ; depth > par->depth; --depth) {
2162 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2163 environment_stack[depth].clear();
2166 // write opening SGML tags
2167 switch(style.latextype) {
2168 case LATEX_PARAGRAPH:
2169 if(depth == par->depth
2170 && !environment_stack[depth].empty()) {
2171 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2172 environment_stack[depth].clear();
2178 sgmlOpenTag(ofs, depth, style.latexname());
2183 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2185 if (!environment_stack[depth].empty()){
2186 sgmlCloseTag(ofs, depth,
2187 environment_stack[depth]);
2191 environment_stack[depth].clear();
2192 sgmlOpenTag(ofs, depth, style.latexname());
2195 case LATEX_ENVIRONMENT:
2196 case LATEX_ITEM_ENVIRONMENT:
2197 if(depth == par->depth
2198 && environment_stack[depth] != style.latexname()
2199 && !environment_stack[depth].empty()) {
2201 sgmlCloseTag(ofs, depth,
2202 environment_stack[depth]);
2203 environment_stack[depth].clear();
2205 if (depth < par->depth) {
2207 environment_stack[depth].clear();
2209 if (environment_stack[depth] != style.latexname()) {
2212 sgmlOpenTag(ofs, depth, temp);
2214 environment_stack[depth] = style.latexname();
2215 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2217 if(style.latextype == LATEX_ENVIRONMENT) break;
2219 desc_on = (style.labeltype == LABEL_MANUAL);
2226 sgmlOpenTag(ofs, depth + 1, item_name);
2229 sgmlOpenTag(ofs, depth, style.latexname());
2234 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2237 linuxDocHandleFootnote(ofs, par, depth);
2239 while(par && par->IsDummy());
2242 /* write closing SGML tags */
2243 switch(style.latextype) {
2245 case LATEX_ENVIRONMENT:
2246 case LATEX_ITEM_ENVIRONMENT:
2249 sgmlCloseTag(ofs, depth, style.latexname());
2254 /* Close open tags */
2255 for(; depth > 0; --depth)
2256 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2258 if(!environment_stack[depth].empty())
2259 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2262 sgmlCloseTag(ofs, 0, top_element);
2265 // How to check for successful close
2269 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2272 string tag = "footnote";
2274 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2275 sgmlOpenTag(os, depth + 1, tag);
2276 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2277 sgmlCloseTag(os, depth + 1, tag);
2283 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2284 int const depth, int desc_on,
2285 LyXParagraph * & par)
2287 LyXParagraph * tpar = par;
2288 string tmp_par, extra_par;
2289 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2290 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2294 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2295 "Caption").second) {
2296 sgmlOpenTag(os, depth + 1, inner_tag);
2297 SimpleDocBookOnePar(tmp_par, extra_par, tpar,
2298 desc_on, depth + 2);
2299 tmp_par = strip(tmp_par);
2300 tmp_par = frontStrip(tmp_par);
2302 sgmlCloseTag(os, depth+1, inner_tag);
2303 if(!extra_par.empty())
2309 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2312 string tag, inner_tag;
2313 string tmp_par, extra_par;
2314 bool inner_span = false;
2317 // This is not how I like to see enums. They should not be anonymous
2318 // and variables of its type should not be declared right after the
2319 // last brace. (Lgb)
2326 } last = NO_ONE, present = FOOTNOTE_LIKE;
2328 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2329 if(last == present) {
2331 if(!tmp_par.empty()) {
2334 sgmlCloseTag(os, depth+1, inner_tag);
2335 sgmlOpenTag(os, depth+1, inner_tag);
2342 if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2343 if(!extra_par.empty()) os << extra_par;
2344 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2347 switch (par->footnotekind) {
2348 case LyXParagraph::FOOTNOTE:
2349 case LyXParagraph::ALGORITHM:
2352 present = FOOTNOTE_LIKE;
2355 case LyXParagraph::MARGIN:
2358 present = MARGIN_LIKE;
2361 case LyXParagraph::FIG:
2362 case LyXParagraph::WIDE_FIG:
2364 inner_tag = "title";
2368 case LyXParagraph::TAB:
2369 case LyXParagraph::WIDE_TAB:
2371 inner_tag = "title";
2376 sgmlOpenTag(os, depth, tag);
2377 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2378 DocBookHandleCaption(os, inner_tag, depth,
2382 sgmlOpenTag(os, depth + 1, inner_tag);
2385 // ignore all caption here, we processed them above!!!
2386 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2387 "Caption").second) {
2388 SimpleDocBookOnePar(tmp_par, extra_par, par,
2389 desc_on, depth + 2);
2391 tmp_par = frontStrip(strip(tmp_par));
2397 if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2398 if(!extra_par.empty()) os << extra_par;
2399 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2403 /* push a tag in a style stack */
2404 void Buffer::push_tag(ostream & os, char const * tag,
2405 int & pos, char stack[5][3])
2407 /* pop all previous tags */
2408 for (int j = pos; j >= 0; --j)
2409 os << "</" << stack[j] << ">";
2412 sprintf(stack[++pos], "%s", tag);
2415 for (int i = 0; i <= pos; ++i)
2416 os << "<" << stack[i] << ">";
2419 void Buffer::pop_tag(ostream & os, char const * tag,
2420 int & pos, char stack[5][3])
2424 // pop all tags till specified one
2425 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2426 os << "</" << stack[j] << ">";
2429 os << "</" << tag << ">";
2431 // push all tags, but the specified one
2432 for (j = j + 1; j <= pos; ++j) {
2433 os << "<" << stack[j] << ">";
2434 strcpy(stack[j-1], stack[j]);
2440 /* handle internal paragraph parsing -- layout already processed */
2442 // checks, if newcol chars should be put into this line
2443 // writes newline, if necessary.
2445 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2446 const unsigned int newcol)
2449 if (colcount > lyxrc->ascii_linelen) {
2451 colcount = newcol; // assume write after this call
2456 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2457 int desc_on, int const /*depth*/)
2459 LyXFont font1, font2;
2462 LyXParagraph::size_type main_body;
2464 LyXLayout const & style = textclasslist.Style(params.textclass,
2467 char family_type = 0; // family font flag
2468 bool is_bold = false; // series font flag
2469 char shape_type = 0; // shape font flag
2470 bool is_em = false; // emphasis (italic) font flag
2472 int stack_num = -1; // style stack position
2473 char stack[5][3]; // style stack
2474 unsigned int char_line_count = 5; // Heuristic choice ;-)
2476 if (style.labeltype != LABEL_MANUAL)
2479 main_body = par->BeginningOfMainBody();
2481 /* gets paragraph main font */
2483 font1 = style.labelfont;
2488 /* parsing main loop */
2489 for (LyXParagraph::size_type i = 0;
2490 i < par->size(); ++i) {
2492 /* handle quote tag */
2493 if (i == main_body && !par->IsDummy()) {
2498 font2 = par->getFont(i);
2500 if (font1.family() != font2.family()) {
2501 switch(family_type) {
2503 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2504 push_tag(os, "tt", stack_num, stack);
2507 else if (font2.family() == LyXFont::SANS_FAMILY) {
2508 push_tag(os, "sf", stack_num, stack);
2513 pop_tag(os, "tt", stack_num, stack);
2514 if (font2.family() == LyXFont::SANS_FAMILY) {
2515 push_tag(os, "sf", stack_num, stack);
2523 pop_tag(os, "sf", stack_num, stack);
2524 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2525 push_tag(os, "tt", stack_num, stack);
2534 /* handle bold face */
2535 if (font1.series() != font2.series()) {
2536 if (font2.series() == LyXFont::BOLD_SERIES) {
2537 push_tag(os, "bf", stack_num, stack);
2541 pop_tag(os, "bf", stack_num, stack);
2546 /* handle italic and slanted fonts */
2547 if (font1.shape() != font2.shape()) {
2548 switch(shape_type) {
2550 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2551 push_tag(os, "it", stack_num, stack);
2554 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2555 push_tag(os, "sl", stack_num, stack);
2560 pop_tag(os, "it", stack_num, stack);
2561 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2562 push_tag(os, "sl", stack_num, stack);
2570 pop_tag(os, "sl", stack_num, stack);
2571 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2572 push_tag(os, "it", stack_num, stack);
2580 /* handle <em> tag */
2581 if (font1.emph() != font2.emph()) {
2582 if (font2.emph() == LyXFont::ON) {
2583 push_tag(os, "em", stack_num, stack);
2586 pop_tag(os, "em", stack_num, stack);
2591 c = par->GetChar(i);
2593 if (font2.latex() == LyXFont::ON) {
2594 // "TeX"-Mode on == > SGML-Mode on.
2596 os << c; // see LaTeX-Generation...
2598 } else if (c == LyXParagraph::META_INSET) {
2599 inset = par->GetInset(i);
2601 inset->Linuxdoc(tmp_out);
2606 if (par->linuxDocConvertChar(c, sgml_string)
2607 && !style.free_spacing) { // in freespacing
2609 // non-breaking characters
2613 linux_doc_line_break(os, char_line_count, 6);
2618 linux_doc_line_break(os, char_line_count, 1);
2624 char_line_count += sgml_string.length();
2630 /* needed if there is an optional argument but no contents */
2631 if (main_body > 0 && main_body == par->size()) {
2635 /* pop all defined Styles */
2636 for (j = stack_num; j >= 0; --j) {
2637 linux_doc_line_break(os,
2639 3 + strlen(stack[j]));
2640 os << "</" << stack[j] << ">";
2643 /* resets description flag correctly */
2646 /* <tag> not closed... */
2647 linux_doc_line_break(os, char_line_count, 6);
2651 /* fprintf(file, "</p>");*/
2657 /* print an error message */
2658 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2659 char const * message)
2661 InsetError * new_inset;
2663 /* insert an error marker in text */
2664 new_inset = new InsetError(message);
2665 par->InsertChar(pos, LyXParagraph::META_INSET);
2666 par->InsertInset(pos, new_inset);
2669 // This constant defines the maximum number of
2670 // environment layouts that can be nesteded.
2671 // The same applies for command layouts.
2672 // These values should be more than enough.
2673 // José Matos (1999/07/22)
2675 enum { MAX_NEST_LEVEL = 25};
2677 void Buffer::makeDocBookFile(string const & fname, int column)
2679 LyXParagraph * par = paragraph;
2681 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2682 string environment_stack[MAX_NEST_LEVEL];
2683 string environment_inner[MAX_NEST_LEVEL];
2684 string command_stack[MAX_NEST_LEVEL];
2685 bool command_flag= false;
2686 int command_depth= 0, command_base= 0, cmd_depth= 0;
2688 string item_name, command_name;
2689 string c_depth, c_params, tmps;
2691 int depth= 0; /* paragraph depth */
2693 tex_code_break_column = column;
2695 ofstream ofs(fname.c_str());
2697 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2703 ofs << "<!doctype " << top_element
2704 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2706 if (params.preamble.empty())
2709 ofs << "\n [ " << params.preamble << " \n]>\n\n";
2711 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2712 << "\n See http://www.lyx.org/ for more information -->\n";
2714 if(params.options.empty())
2715 sgmlOpenTag(ofs, 0, top_element);
2717 string top = top_element;
2719 top += params.options;
2720 sgmlOpenTag(ofs, 0, top);
2724 int desc_on = 0; /* description mode*/
2725 LyXLayout const & style =
2726 textclasslist.Style(users->buffer()->params.textclass,
2728 par->AutoDeleteInsets();
2730 /* environment tag closing */
2731 for( ; depth > par->depth; --depth) {
2732 if(environment_inner[depth] != "!-- --") {
2733 item_name= "listitem";
2734 sgmlCloseTag(ofs, command_depth + depth,
2736 if( environment_inner[depth] == "varlistentry")
2737 sgmlCloseTag(ofs, depth+command_depth,
2738 environment_inner[depth]);
2740 sgmlCloseTag(ofs, depth + command_depth,
2741 environment_stack[depth]);
2742 environment_stack[depth].clear();
2743 environment_inner[depth].clear();
2746 if(depth == par->depth
2747 && environment_stack[depth] != style.latexname()
2748 && !environment_stack[depth].empty()) {
2749 if(environment_inner[depth] != "!-- --") {
2750 item_name= "listitem";
2751 sgmlCloseTag(ofs, command_depth+depth,
2753 if( environment_inner[depth] == "varlistentry")
2755 depth + command_depth,
2756 environment_inner[depth]);
2759 sgmlCloseTag(ofs, depth + command_depth,
2760 environment_stack[depth]);
2762 environment_stack[depth].clear();
2763 environment_inner[depth].clear();
2766 // Write opening SGML tags.
2767 switch(style.latextype) {
2768 case LATEX_PARAGRAPH:
2769 if(style.latexname() != "dummy")
2770 sgmlOpenTag(ofs, depth+command_depth,
2776 LinuxDocError(par, 0,
2777 _("Error : Wrong depth for "
2778 "LatexType Command.\n"));
2780 command_name = style.latexname();
2782 tmps = style.latexparam();
2783 c_params = split(tmps, c_depth,'|');
2785 cmd_depth= atoi(c_depth.c_str());
2788 if(cmd_depth<command_base) {
2789 for(int j = command_depth;
2790 j >= command_base; --j)
2791 if(!command_stack[j].empty())
2792 sgmlCloseTag(ofs, j, command_stack[j]);
2793 command_depth= command_base= cmd_depth;
2795 else if(cmd_depth <= command_depth) {
2796 for(int j = command_depth;
2797 j >= cmd_depth; --j)
2799 if(!command_stack[j].empty())
2800 sgmlCloseTag(ofs, j, command_stack[j]);
2801 command_depth= cmd_depth;
2804 command_depth= cmd_depth;
2807 command_depth = command_base = cmd_depth;
2808 command_flag = true;
2810 command_stack[command_depth]= command_name;
2812 // treat label as a special case for
2813 // more WYSIWYM handling.
2814 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2815 Inset * inset = par->GetInset(0);
2816 char lyx_code = inset->LyxCode();
2817 if (lyx_code == Inset::LABEL_CODE){
2818 command_name += " id=\"";
2819 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2820 command_name += "\"";
2825 sgmlOpenTag(ofs, depth+command_depth, command_name);
2826 item_name = "title";
2827 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2830 case LATEX_ENVIRONMENT:
2831 case LATEX_ITEM_ENVIRONMENT:
2832 if (depth < par->depth) {
2834 environment_stack[depth].clear();
2837 if (environment_stack[depth] != style.latexname()) {
2838 environment_stack[depth] = style.latexname();
2839 environment_inner[depth] = "!-- --";
2840 sgmlOpenTag(ofs, depth + command_depth,
2841 environment_stack[depth]);
2843 if(environment_inner[depth] != "!-- --") {
2844 item_name= "listitem";
2846 command_depth + depth,
2848 if (environment_inner[depth] == "varlistentry")
2850 depth + command_depth,
2851 environment_inner[depth]);
2855 if(style.latextype == LATEX_ENVIRONMENT) {
2856 if(!style.latexparam().empty())
2857 sgmlOpenTag(ofs, depth + command_depth,
2858 style.latexparam());
2862 desc_on = (style.labeltype == LABEL_MANUAL);
2865 environment_inner[depth]= "varlistentry";
2867 environment_inner[depth]= "listitem";
2869 sgmlOpenTag(ofs, depth + 1 + command_depth,
2870 environment_inner[depth]);
2874 sgmlOpenTag(ofs, depth + 1 + command_depth,
2879 sgmlOpenTag(ofs, depth + 1 + command_depth,
2884 sgmlOpenTag(ofs, depth + command_depth,
2890 string tmp_par, extra_par;
2892 SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
2893 depth + 1 + command_depth);
2897 DocBookHandleFootnote(ofs, par,
2898 depth + 1 + command_depth);
2900 while(par && par->IsDummy());
2903 /* write closing SGML tags */
2904 switch(style.latextype) {
2907 sgmlCloseTag(ofs, depth + command_depth, end_tag);
2909 case LATEX_ENVIRONMENT:
2910 if(!style.latexparam().empty())
2911 sgmlCloseTag(ofs, depth + command_depth,
2912 style.latexparam());
2914 case LATEX_ITEM_ENVIRONMENT:
2915 if(desc_on == 1) break;
2917 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2919 case LATEX_PARAGRAPH:
2920 if(style.latexname() != "dummy")
2921 sgmlCloseTag(ofs, depth + command_depth,
2925 sgmlCloseTag(ofs, depth + command_depth,
2932 for(; depth >= 0; --depth) {
2933 if(!environment_stack[depth].empty()) {
2934 if(environment_inner[depth] != "!-- --") {
2935 item_name= "listitem";
2936 sgmlCloseTag(ofs, command_depth + depth,
2938 if( environment_inner[depth] == "varlistentry")
2939 sgmlCloseTag(ofs, depth + command_depth,
2940 environment_inner[depth]);
2943 sgmlCloseTag(ofs, depth + command_depth,
2944 environment_stack[depth]);
2948 for(int j = command_depth; j >= command_base; --j)
2949 if(!command_stack[j].empty())
2950 sgmlCloseTag(ofs, j, command_stack[j]);
2953 sgmlCloseTag(ofs, 0, top_element);
2956 // How to check for successful close
2960 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
2961 LyXParagraph * par, int & desc_on,
2965 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
2968 LyXFont font1, font2;
2971 LyXParagraph::size_type main_body;
2973 string emph= "emphasis";
2974 bool emph_flag= false;
2975 int char_line_count= 0;
2977 LyXLayout const & style = textclasslist.Style(params.textclass,
2980 if (style.labeltype != LABEL_MANUAL)
2983 main_body = par->BeginningOfMainBody();
2985 /* gets paragraph main font */
2987 font1 = style.labelfont;
2991 char_line_count = depth;
2992 if(!style.free_spacing)
2993 for (j = 0; j < depth; ++j)
2996 /* parsing main loop */
2997 for (LyXParagraph::size_type i = 0;
2998 i < par->size(); ++i) {
2999 font2 = par->getFont(i);
3001 /* handle <emphasis> tag */
3002 if (font1.emph() != font2.emph() && i) {
3003 if (font2.emph() == LyXFont::ON) {
3004 file += "<emphasis>";
3007 file += "</emphasis>";
3012 c = par->GetChar(i);
3014 if (c == LyXParagraph::META_INSET) {
3015 inset = par->GetInset(i);
3017 inset->DocBook(tmp_out);
3019 // This code needs some explanation:
3020 // Two insets are treated specially
3021 // label if it is the first element in a command paragraph
3023 // graphics inside tables or figure floats can't go on
3024 // title (the equivalente in latex for this case is caption
3025 // and title should come first
3028 if(desc_on!= 3 || i!= 0) {
3029 if(!tmp_out.empty() && tmp_out[0] == '@') {
3031 extra += frontStrip(tmp_out, '@');
3033 file += frontStrip(tmp_out, '@');
3038 } else if (font2.latex() == LyXFont::ON) {
3039 // "TeX"-Mode on ==> SGML-Mode on.
3046 if (par->linuxDocConvertChar(c, sgml_string)
3047 && !style.free_spacing) { // in freespacing
3049 // non-breaking characters
3054 file += "</term><listitem><para>";
3062 file += sgml_string;
3068 /* needed if there is an optional argument but no contents */
3069 if (main_body > 0 && main_body == par->size()) {
3073 file += "</emphasis>";
3076 /* resets description flag correctly */
3079 /* <term> not closed... */
3087 int Buffer::runLaTeX()
3089 if (!users->text) return 0;
3093 // get LaTeX-Filename
3094 string name = getLatexName();
3096 string path = OnlyPath(filename);
3098 string org_path = path;
3099 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3103 Path p(path); // path to LaTeX file
3104 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3106 // Remove all error insets
3107 bool a = users->removeAutoInsets();
3109 // Always generate the LaTeX file
3110 makeLaTeXFile(name, org_path, false);
3113 // do the LaTex run(s)
3115 string latex_command = lyxrc->pdf_mode ?
3116 lyxrc->pdflatex_command : lyxrc->latex_command;
3117 LaTeX latex(latex_command, name, filepath);
3118 int res = latex.run(terr,
3119 users->owner()->getMiniBuffer()); // running latex
3121 // check return value from latex.run().
3122 if ((res & LaTeX::NO_LOGFILE)) {
3123 WriteAlert(_("LaTeX did not work!"),
3124 _("Missing log file:"), name);
3125 } else if ((res & LaTeX::ERRORS)) {
3126 users->owner()->getMiniBuffer()->Set(_("Done"));
3127 // Insert all errors as errors boxes
3128 users->insertErrors(terr);
3130 // Dvi should also be kept dirty if the latex run
3131 // ends up with errors. However it should be possible
3132 // to view a dirty dvi too.
3134 //no errors or any other things to think about so:
3135 users->owner()->getMiniBuffer()->Set(_("Done"));
3139 // if we removed error insets before we ran LaTeX or if we inserted
3140 // error insets after we ran LaTeX this must be run:
3141 if (a || (res & LaTeX::ERRORS)){
3144 users->updateScrollbar();
3148 return latex.getNumErrors();
3152 int Buffer::runLiterate()
3154 if (!users->text) return 0;
3158 // get LaTeX-Filename
3159 string name = getLatexName();
3160 // get Literate-Filename
3161 string lit_name = ChangeExtension (getLatexName(),
3162 lyxrc->literate_extension, true);
3164 string path = OnlyPath(filename);
3166 string org_path = path;
3167 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3171 Path p(path); // path to Literate file
3172 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3174 // Remove all error insets
3175 bool a = users->removeAutoInsets();
3177 // generate the Literate file if necessary
3178 if (!isDviClean() || a) {
3179 makeLaTeXFile(lit_name, org_path, false);
3183 string latex_command = lyxrc->pdf_mode ?
3184 lyxrc->pdflatex_command : lyxrc->latex_command;
3185 Literate literate(latex_command, name, filepath,
3187 lyxrc->literate_command, lyxrc->literate_error_filter,
3188 lyxrc->build_command, lyxrc->build_error_filter);
3190 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3192 // check return value from literate.weave().
3193 if ((res & Literate::NO_LOGFILE)) {
3194 WriteAlert(_("Literate command did not work!"),
3195 _("Missing log file:"), name);
3196 } else if ((res & Literate::ERRORS)) {
3197 users->owner()->getMiniBuffer()->Set(_("Done"));
3198 // Insert all errors as errors boxes
3199 users->insertErrors(terr);
3201 // Dvi should also be kept dirty if the latex run
3202 // ends up with errors. However it should be possible
3203 // to view a dirty dvi too.
3205 //no errors or any other things to think about so:
3206 users->owner()->getMiniBuffer()->Set(_("Done"));
3210 // if we removed error insets before we ran LaTeX or if we inserted
3211 // error insets after we ran LaTeX this must be run:
3212 if (a || (res & Literate::ERRORS)){
3215 users->updateScrollbar();
3219 return literate.getNumErrors();
3223 int Buffer::buildProgram()
3225 if (!users->text) return 0;
3229 // get LaTeX-Filename
3230 string name = getLatexName();
3231 // get Literate-Filename
3232 string lit_name = ChangeExtension(getLatexName(),
3233 lyxrc->literate_extension, true);
3235 string path = OnlyPath(filename);
3237 string org_path = path;
3238 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3242 Path p(path); // path to Literate file
3243 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3245 // Remove all error insets
3246 bool a = users->removeAutoInsets();
3248 // generate the LaTeX file if necessary
3249 if (!isNwClean() || a) {
3250 makeLaTeXFile(lit_name, org_path, false);
3254 string latex_command = lyxrc->pdf_mode ?
3255 lyxrc->pdflatex_command : lyxrc->latex_command;
3256 Literate literate(latex_command, name, filepath,
3258 lyxrc->literate_command, lyxrc->literate_error_filter,
3259 lyxrc->build_command, lyxrc->build_error_filter);
3261 int res = literate.build(terr, users->owner()->getMiniBuffer());
3263 // check return value from literate.build().
3264 if ((res & Literate::NO_LOGFILE)) {
3265 WriteAlert(_("Build did not work!"),
3266 _("Missing log file:"), name);
3267 } else if ((res & Literate::ERRORS)) {
3268 users->owner()->getMiniBuffer()->Set(_("Done"));
3269 // Insert all errors as errors boxes
3270 users->insertErrors(terr);
3272 // Literate files should also be kept dirty if the literate
3273 // command run ends up with errors.
3275 //no errors or any other things to think about so:
3276 users->owner()->getMiniBuffer()->Set(_("Done"));
3280 // if we removed error insets before we ran Literate/Build or if we inserted
3281 // error insets after we ran Literate/Build this must be run:
3282 if (a || (res & Literate::ERRORS)){
3285 users->updateScrollbar();
3289 return literate.getNumErrors();
3293 // This should be enabled when the Chktex class is implemented. (Asger)
3294 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3295 // Other flags: -wall -v0 -x
3296 int Buffer::runChktex()
3298 if (!users->text) return 0;
3302 // get LaTeX-Filename
3303 string name = getLatexName();
3304 string path = OnlyPath(filename);
3306 string org_path = path;
3307 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3311 Path p(path); // path to LaTeX file
3312 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3314 // Remove all error insets
3315 bool a = users->removeAutoInsets();
3317 // Generate the LaTeX file if neccessary
3318 if (!isDviClean() || a) {
3319 makeLaTeXFile(name, org_path, false);
3324 Chktex chktex(lyxrc->chktex_command, name, filepath);
3325 int res = chktex.run(terr); // run chktex
3328 WriteAlert(_("chktex did not work!"),
3329 _("Could not run with file:"), name);
3330 } else if (res > 0) {
3331 // Insert all errors as errors boxes
3332 users->insertErrors(terr);
3335 // if we removed error insets before we ran chktex or if we inserted
3336 // error insets after we ran chktex, this must be run:
3340 users->updateScrollbar();
3349 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
3351 LyXFont font1(LyXFont::ALL_INHERIT);
3354 LyXParagraph::size_type i;
3358 string fname1 = TmpFileName(string(), "RAT1");
3359 string fname2 = TmpFileName(string(), "RAT2");
3361 ofstream ofs(fname1.c_str());
3363 WriteAlert(_("LYX_ERROR:"),
3364 _("Cannot open temporary file:"), fname1);
3367 par->table->RoffEndOfCell(ofs, -1);
3368 for (i = 0; i < par->size(); ++i) {
3369 c = par->GetChar(i);
3370 if (par->table->IsContRow(cell)) {
3371 if (c == LyXParagraph::META_NEWLINE)
3375 font2 = par->GetFontSettings(i);
3376 if (font1.latex() != font2.latex()) {
3377 if (font2.latex() != LyXFont::OFF)
3381 case LyXParagraph::META_INSET:
3382 if ((inset = par->GetInset(i))) {
3385 stringstresm ss(ios::in | ios::out);
3386 inset->Latex(ss, -1);
3398 inset->Latex(ss, -1);
3411 fstream fs(fname2.c_str(), ios::in|ios::out);
3413 WriteAlert(_("LYX_ERROR:"),
3414 _("Cannot open temporary file:"), fname2);
3416 remove(fname1.c_str());
3419 inset->Latex(fs, -1);
3433 case LyXParagraph::META_NEWLINE:
3434 if (par->table->CellHasContRow(cell)>= 0)
3435 par->RoffContTableRows(ofs, i+1, cell);
3436 par->table->RoffEndOfCell(ofs, cell);
3439 case LyXParagraph::META_HFILL:
3442 case LyXParagraph::META_PROTECTED_SEPARATOR:
3453 << "RoffAsciiTable:"
3454 " NULL char in structure." << endl;
3458 par->table->RoffEndOfCell(ofs, cell);
3460 string cmd = lyxrc->ascii_roff_command + " >" + fname2;
3461 cmd = subst(cmd, "$$FName", fname1);
3462 Systemcalls one(Systemcalls::System, cmd);
3463 if (!(lyxerr.debugging(Debug::ROFF))) {
3464 remove(fname1.c_str());
3466 ifstream ifs(fname2.c_str());
3468 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3471 // now output the produced file
3475 WriteAlert(_("Error!"),
3476 _("Error executing *roff command on table"));
3477 // overread leading blank lines
3478 while(!ifs && (c == '\n'))
3481 for(j = 0; j < par->depth; ++j)
3483 while(!ifs && (c != '\n')) {
3488 // overread trailing blank lines
3489 while(!ifs && (c == '\n'))
3493 remove(fname2.c_str());
3498 /// changed Heinrich Bauer, 23/03/98
3499 bool Buffer::isDviClean() const
3501 if (lyxrc->use_tempdir)
3502 return dvi_clean_tmpd;
3504 return dvi_clean_orgd;
3508 /// changed Heinrich Bauer, 23/03/98
3509 void Buffer::markDviClean()
3511 if (lyxrc->use_tempdir)
3512 dvi_clean_tmpd = true;
3514 dvi_clean_orgd = true;
3518 /// changed Heinrich Bauer, 23/03/98
3519 void Buffer::markDviDirty()
3521 if (lyxrc->use_tempdir)
3522 dvi_clean_tmpd = false;
3524 dvi_clean_orgd = false;
3528 void Buffer::validate(LaTeXFeatures & features) const
3530 LyXParagraph * par = paragraph;
3531 LyXTextClass const & tclass =
3532 textclasslist.TextClass(params.textclass);
3534 // AMS Style is at document level
3536 features.amsstyle = (params.use_amsmath ||
3537 tclass.provides(LyXTextClass::amsmath));
3540 // We don't use "lyxerr.debug" because of speed. (Asger)
3541 if (lyxerr.debugging(Debug::LATEX))
3542 lyxerr << "Paragraph: " << par << endl;
3544 // Now just follow the list of paragraphs and run
3545 // validate on each of them.
3546 par->validate(features);
3548 // and then the next paragraph
3552 // the bullet shapes are buffer level not paragraph level
3553 // so they are tested here
3554 for (int i = 0; i < 4; ++i) {
3555 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3556 int font = params.user_defined_bullets[i].getFont();
3559 .user_defined_bullets[i]
3566 features.latexsym = true;
3570 features.amssymb = true;
3572 else if ((font >= 2 && font <= 5)) {
3573 features.pifont = true;
3578 if (lyxerr.debugging(Debug::LATEX)) {
3579 features.showStruct(params);
3584 void Buffer::setPaperStuff()
3586 params.papersize = BufferParams::PAPER_DEFAULT;
3587 char c1 = params.paperpackage;
3588 if (c1 == BufferParams::PACKAGE_NONE) {
3589 char c2 = params.papersize2;
3590 if (c2 == BufferParams::VM_PAPER_USLETTER)
3591 params.papersize = BufferParams::PAPER_USLETTER;
3592 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3593 params.papersize = BufferParams::PAPER_LEGALPAPER;
3594 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3595 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3596 else if (c2 == BufferParams::VM_PAPER_A3)
3597 params.papersize = BufferParams::PAPER_A3PAPER;
3598 else if (c2 == BufferParams::VM_PAPER_A4)
3599 params.papersize = BufferParams::PAPER_A4PAPER;
3600 else if (c2 == BufferParams::VM_PAPER_A5)
3601 params.papersize = BufferParams::PAPER_A5PAPER;
3602 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3603 (c2 == BufferParams::VM_PAPER_B5))
3604 params.papersize = BufferParams::PAPER_B5PAPER;
3605 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3606 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3607 params.papersize = BufferParams::PAPER_A4PAPER;
3611 // This function should be in Buffer because it's a buffer's property (ale)
3612 string Buffer::getIncludeonlyList(char delim)
3615 LyXParagraph * par = paragraph;
3616 LyXParagraph::size_type pos;
3620 while ((inset = par->ReturnNextInsetPointer(pos))){
3621 if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3622 InsetInclude * insetinc =
3623 static_cast<InsetInclude*>(inset);
3624 if (insetinc->isInclude()
3625 && insetinc->isNoLoad()) {
3628 lst += ChangeExtension(insetinc->getContents(), string(), true);
3635 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3640 // This is also a buffer property (ale)
3641 string Buffer::getReferenceList(char delim)
3643 /// if this is a child document and the parent is already loaded
3644 /// Use the parent's list instead [ale990407]
3645 if (!params.parentname.empty()
3646 && bufferlist.exists(params.parentname)) {
3647 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3649 return tmp->getReferenceList(delim);
3652 LyXParagraph * par = paragraph;
3653 LyXParagraph::size_type pos;
3658 while ((inset = par->ReturnNextInsetPointer(pos))){
3659 for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
3662 lst += inset->getLabel(i);
3668 lyxerr.debug() << "References(" << lst << ")" << endl;
3673 // This is also a buffer property (ale)
3674 string Buffer::getBibkeyList(char delim)
3676 /// if this is a child document and the parent is already loaded
3677 /// Use the parent's list instead [ale990412]
3678 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3679 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3681 return tmp->getBibkeyList(delim);
3685 LyXParagraph * par = paragraph;
3688 if (!bibkeys.empty())
3690 bibkeys += par->bibkey->getContents();
3695 // Might be either using bibtex or a child has bibliography
3696 if (bibkeys.empty()) {
3700 LyXParagraph::size_type pos = -1;
3702 // Search for Bibtex or Include inset
3703 while ((inset = par->ReturnNextInsetPointer(pos))) {
3704 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3705 if (!bibkeys.empty())
3707 bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
3708 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3709 string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
3711 if (!bibkeys.empty())
3722 lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3727 bool Buffer::isDepClean(string const & name) const
3729 DEPCLEAN * item = dep_clean;
3730 while (item && item->master != name)
3732 if (!item) return true;
3737 void Buffer::markDepClean(string const & name)
3740 dep_clean = new DEPCLEAN;
3741 dep_clean->clean = true;
3742 dep_clean->master = name;
3743 dep_clean->next = 0;
3745 DEPCLEAN* item = dep_clean;
3746 while (item && item->master != name)
3751 item = new DEPCLEAN;
3753 item->master = name;
3760 void Buffer::Dispatch(string const & command)
3762 // Split command string into command and argument
3763 string cmd, line = frontStrip(command);
3764 string arg = strip(frontStrip(split(line, cmd, ' ')));
3766 Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3770 void Buffer::Dispatch(int action, string const & argument)
3774 MenuExport(this, argument);
3778 lyxerr << "A truly unknown func!" << endl;