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 "support/filetools.h"
77 #include "support/path.h"
83 #include "LaTeXFeatures.h"
84 #include "support/syscall.h"
85 #include "support/lyxlib.h"
86 #include "support/FileInfo.h"
90 // Uncomment this line to enable a workaround for the weird behaviour
91 // of the cursor between a displayed inset and last character
92 // at the upper line. (Alejandro 20.9.96)
93 // #define BREAK_BEFORE_INSET
95 /* Lars, when changing this file sometime in the future to a list,
96 * please check out the figinsets-sideeffects described at the
97 * beginning of figinset.C Matthias (04.07.1996)
101 // all these externs should eventually be removed.
102 extern BufferList bufferlist;
104 extern void MenuExport(Buffer *, string const &);
105 extern LyXAction lyxaction;
108 static const float LYX_FORMAT = 2.15;
110 extern int tex_code_break_column;
112 extern void FreeUpdateTimer();
115 Buffer::Buffer(string const & file, LyXRC * lyxrc, bool ronly)
117 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
119 filepath = OnlyPath(file);
123 dvi_clean_orgd = false; // Heinrich Bauer, 23/03/98
124 dvi_clean_tmpd = false; // Heinrich Bauer, 23/03/98
129 if (read_only || (lyxrc && lyxrc->use_tempdir)) {
130 tmppath = CreateBufferTmpDir();
131 } else tmppath.clear();
137 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
138 // here the buffer should take care that it is
139 // saved properly, before it goes into the void.
141 // make sure that views using this buffer
146 if (!tmppath.empty()) {
147 DestroyBufferTmpDir(tmppath);
150 LyXParagraph * par = paragraph;
151 LyXParagraph * tmppar;
161 bool Buffer::saveParamsAsDefaults()
163 string fname = AddName(AddPath(user_lyxdir, "templates/"),
165 Buffer defaults = Buffer(fname);
167 // Use the current buffer's parameters as default
168 defaults.params = params;
170 // add an empty paragraph. Is this enough?
171 defaults.paragraph = new LyXParagraph;
173 return defaults.writeFile(defaults.filename, false);
177 /// Update window titles of all users
178 // Should work on a list
179 void Buffer::updateTitles() const
181 if (users) users->owner()->updateWindowTitle();
185 /// Reset autosave timer of all users
186 // Should work on a list
187 void Buffer::resetAutosaveTimers() const
189 if (users) users->owner()->resetAutosaveTimer();
193 void Buffer::fileName(string const & newfile)
195 filename = MakeAbsPath(newfile);
196 filepath = OnlyPath(filename);
197 setReadonly(IsFileWriteable(filename) == 0);
202 // candidate for move to BufferView
203 // (at least some parts in the beginning of the func)
206 // changed to be public and have one parameter
207 // if par = 0 normal behavior
208 // else insert behavior
209 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
210 bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
216 char depth = 0; // signed or unsigned?
217 LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
218 LyXParagraph::footnote_kind footnotekind = LyXParagraph::FOOTNOTE;
219 bool the_end_read = false;
221 LyXParagraph * return_par = 0;
222 LyXFont font(LyXFont::ALL_INHERIT);
224 // If we are inserting, we cheat and get a token in advance
225 bool has_token = false;
229 par = new LyXParagraph;
231 users->text->BreakParagraph();
232 return_par = users->text->FirstParagraph();
235 // We don't want to adopt the parameters from the
236 // document we insert, so we skip until the text begins:
239 pretoken = lex.GetString();
240 if (pretoken == "\\layout") {
252 pretoken = lex.GetString();
255 // Profiling show this should give a lot: (Asger)
256 string const token = pretoken;
260 else if (token[0] != '\\') {
261 int n = token.length();
262 for (int i = 0; i < n; ++i) {
263 par->InsertChar(pos, token[i]);
264 par->SetFont(pos, font);
267 } else if (token == "\\i") {
268 inset = new InsetLatexAccent;
270 par->InsertChar(pos, LyXParagraph::META_INSET);
272 par->InsertInset(pos, inset);
273 par->SetFont(pos, font);
275 } else if (token == "\\layout") {
279 par->text.resize(par->text.size());
280 par = new LyXParagraph(par);
284 string layoutname = lex.GetString();
285 pair<bool, LyXTextClass::LayoutList::size_type> pp
286 = textclasslist.NumberOfLayout(params.textclass,
289 par->layout = pp.second;
290 } else { // layout not found
291 // use default layout "Standard" (0)
294 // Test whether the layout is obsolete.
295 LyXLayout const & layout = textclasslist.Style(params.textclass,
297 if (!layout.obsoleted_by().empty())
299 textclasslist.NumberOfLayout(params.textclass,
300 layout.obsoleted_by()).second;
301 par->footnoteflag = footnoteflag;
302 par->footnotekind = footnotekind;
304 font = LyXFont(LyXFont::ALL_INHERIT);
305 } else if (token == "\\end_float") {
309 par->text.resize(par->text.size());
310 par = new LyXParagraph(par);
312 footnotekind = LyXParagraph::FOOTNOTE;
313 footnoteflag = LyXParagraph::NO_FOOTNOTE;
316 par->layout = LYX_DUMMY_LAYOUT;
317 font = LyXFont(LyXFont::ALL_INHERIT);
318 } else if (token == "\\begin_float") {
319 tmpret = lex.FindToken(string_footnotekinds);
320 if (tmpret == -1) ++tmpret;
321 if (tmpret != LYX_LAYOUT_DEFAULT)
322 footnotekind = static_cast<LyXParagraph::footnote_kind>(tmpret); // bad
323 if (footnotekind == LyXParagraph::FOOTNOTE
324 || footnotekind == LyXParagraph::MARGIN)
325 footnoteflag = LyXParagraph::CLOSED_FOOTNOTE;
327 footnoteflag = LyXParagraph::OPEN_FOOTNOTE;
328 } else if (token == "\\begin_deeper") {
330 } else if (token == "\\end_deeper") {
332 lex.printError("\\end_deeper: "
333 "depth is already null");
337 } else if (token == "\\begin_preamble") {
338 params.readPreamble(lex);
339 } else if (token == "\\textclass") {
341 pair<bool, LyXTextClassList::size_type> pp =
342 textclasslist.NumberOfClass(lex.GetString());
344 params.textclass = pp.second;
346 lex.printError("Unknown textclass `$$Token'");
347 params.textclass = 0;
349 if (!textclasslist.Load(params.textclass)) {
350 // if the textclass wasn't loaded properly
351 // we need to either substitute another
352 // or stop loading the file.
353 // I can substitute but I don't see how I can
354 // stop loading... ideas?? ARRae980418
355 WriteAlert(_("Textclass Loading Error!"),
356 string(_("Can't load textclass ")) +
357 textclasslist.NameOfClass(params.textclass),
358 _("-- substituting default"));
359 params.textclass = 0;
361 } else if (token == "\\options") {
363 params.options = lex.GetString();
364 } else if (token == "\\language") {
365 params.readLanguage(lex);
366 } else if (token == "\\fontencoding") {
368 } else if (token == "\\inputencoding") {
370 params.inputenc = lex.GetString();
371 } else if (token == "\\graphics") {
372 params.readGraphicsDriver(lex);
373 } else if (token == "\\fontscheme") {
375 params.fonts = lex.GetString();
376 } else if (token == "\\noindent") {
377 par->noindent = true;
378 } else if (token == "\\fill_top") {
379 par->added_space_top = VSpace(VSpace::VFILL);
380 } else if (token == "\\fill_bottom") {
381 par->added_space_bottom = VSpace(VSpace::VFILL);
382 } else if (token == "\\line_top") {
383 par->line_top = true;
384 } else if (token == "\\line_bottom") {
385 par->line_bottom = true;
386 } else if (token == "\\pagebreak_top") {
387 par->pagebreak_top = true;
388 } else if (token == "\\pagebreak_bottom") {
389 par->pagebreak_bottom = true;
390 } else if (token == "\\start_of_appendix") {
391 par->start_of_appendix = true;
392 } else if (token == "\\paragraph_separation") {
393 tmpret = lex.FindToken(string_paragraph_separation);
394 if (tmpret == -1) ++tmpret;
395 if (tmpret != LYX_LAYOUT_DEFAULT)
396 params.paragraph_separation =
397 static_cast<BufferParams::PARSEP>(tmpret);
398 } else if (token == "\\defskip") {
400 params.defskip = VSpace(lex.GetString());
401 } else if (token == "\\no_isolatin1") { // obsolete
403 } else if (token == "\\no_babel") { // obsolete
405 } else if (token == "\\no_epsfig") { // obsolete
407 } else if (token == "\\epsfig") { // obsolete
408 // Indeed it is obsolete, but we HAVE to be backwards
409 // compatible until 0.14, because otherwise all figures
410 // in existing documents are irretrivably lost. (Asger)
411 params.readGraphicsDriver(lex);
412 } else if (token == "\\quotes_language") {
413 tmpret = lex.FindToken(string_quotes_language);
414 if (tmpret == -1) ++tmpret;
415 if (tmpret != LYX_LAYOUT_DEFAULT) {
416 InsetQuotes::quote_language tmpl =
417 InsetQuotes::EnglishQ;
420 tmpl = InsetQuotes::EnglishQ;
423 tmpl = InsetQuotes::SwedishQ;
426 tmpl = InsetQuotes::GermanQ;
429 tmpl = InsetQuotes::PolishQ;
432 tmpl = InsetQuotes::FrenchQ;
435 tmpl = InsetQuotes::DanishQ;
438 params.quotes_language = tmpl;
440 } else if (token == "\\quotes_times") {
442 switch(lex.GetInteger()) {
444 params.quotes_times = InsetQuotes::SingleQ;
447 params.quotes_times = InsetQuotes::DoubleQ;
450 } else if (token == "\\papersize") {
451 tmpret = lex.FindToken(string_papersize);
455 params.papersize2 = tmpret;
456 } else if (token == "\\paperpackage") {
457 tmpret = lex.FindToken(string_paperpackages);
460 params.paperpackage = BufferParams::PACKAGE_NONE;
462 params.paperpackage = tmpret;
463 } else if (token == "\\use_geometry") {
465 params.use_geometry = lex.GetInteger();
466 } else if (token == "\\use_amsmath") {
468 params.use_amsmath = lex.GetInteger();
469 } else if (token == "\\paperorientation") {
470 tmpret = lex.FindToken(string_orientation);
471 if (tmpret == -1) ++tmpret;
472 if (tmpret != LYX_LAYOUT_DEFAULT)
473 params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
474 } else if (token == "\\paperwidth") {
476 params.paperwidth = lex.GetString();
477 } else if (token == "\\paperheight") {
479 params.paperheight = lex.GetString();
480 } else if (token == "\\leftmargin") {
482 params.leftmargin = lex.GetString();
483 } else if (token == "\\topmargin") {
485 params.topmargin = lex.GetString();
486 } else if (token == "\\rightmargin") {
488 params.rightmargin = lex.GetString();
489 } else if (token == "\\bottommargin") {
491 params.bottommargin = lex.GetString();
492 } else if (token == "\\headheight") {
494 params.headheight = lex.GetString();
495 } else if (token == "\\headsep") {
497 params.headsep = lex.GetString();
498 } else if (token == "\\footskip") {
500 params.footskip = lex.GetString();
501 } else if (token == "\\paperfontsize") {
503 params.fontsize = strip(lex.GetString());
504 } else if (token == "\\papercolumns") {
506 params.columns = lex.GetInteger();
507 } else if (token == "\\papersides") {
509 switch(lex.GetInteger()) {
511 case 1: params.sides = LyXTextClass::OneSide; break;
512 case 2: params.sides = LyXTextClass::TwoSides; break;
514 } else if (token == "\\paperpagestyle") {
516 params.pagestyle = strip(lex.GetString());
517 } else if (token == "\\bullet") {
519 int index = lex.GetInteger();
521 int temp_int = lex.GetInteger();
522 params.user_defined_bullets[index].setFont(temp_int);
523 params.temp_bullets[index].setFont(temp_int);
525 temp_int = lex.GetInteger();
526 params.user_defined_bullets[index].setCharacter(temp_int);
527 params.temp_bullets[index].setCharacter(temp_int);
529 temp_int = lex.GetInteger();
530 params.user_defined_bullets[index].setSize(temp_int);
531 params.temp_bullets[index].setSize(temp_int);
533 string temp_str = lex.GetString();
534 if (temp_str != "\\end_bullet") {
535 // this element isn't really necessary for
536 // parsing but is easier for humans
537 // to understand bullets. Put it back and
538 // set a debug message?
539 lex.printError("\\end_bullet expected, got" + temp_str);
540 //how can I put it back?
542 } else if (token == "\\bulletLaTeX") {
544 int index = lex.GetInteger();
546 string temp_str = lex.GetString(), sum_str;
547 while (temp_str != "\\end_bullet") {
548 // this loop structure is needed when user
549 // enters an empty string since the first
550 // thing returned will be the \\end_bullet
552 // if the LaTeX entry has spaces. Each element
553 // therefore needs to be read in turn
556 temp_str = lex.GetString();
558 params.user_defined_bullets[index].setText(sum_str);
559 params.temp_bullets[index].setText(sum_str);
560 } else if (token == "\\secnumdepth") {
562 params.secnumdepth = lex.GetInteger();
563 } else if (token == "\\tocdepth") {
565 params.tocdepth = lex.GetInteger();
566 } else if (token == "\\baselinestretch") { // obsolete
567 lex.nextToken(); // should not be used directly
569 // Will probably keep a kind of support just for
571 params.spacing.set(Spacing::Other, lex.GetFloat());
572 } else if (token == "\\spacing") {
574 string tmp = strip(lex.GetString());
575 if (tmp == "single") {
576 params.spacing.set(Spacing::Single);
577 } else if (tmp == "onehalf") {
578 params.spacing.set(Spacing::Onehalf);
579 } else if (tmp == "double") {
580 params.spacing.set(Spacing::Double);
581 } else if (tmp == "other") {
583 params.spacing.set(Spacing::Other,
586 lex.printError("Unknown spacing token: '$$Token'");
588 } else if (token == "\\float_placement") {
590 params.float_placement = lex.GetString();
591 } else if (token == "\\cursor") { // obsolete
592 // this is obsolete, so we just skip it.
594 } else if (token == "\\family") {
596 font.setLyXFamily(lex.GetString());
597 } else if (token == "\\series") {
599 font.setLyXSeries(lex.GetString());
600 } else if (token == "\\shape") {
602 font.setLyXShape(lex.GetString());
603 } else if (token == "\\size") {
605 font.setLyXSize(lex.GetString());
606 } else if (token == "\\latex") {
608 string tok = lex.GetString();
609 // This is dirty, but gone with LyX3. (Asger)
610 if (tok == "no_latex")
611 font.setLatex(LyXFont::OFF);
612 else if (tok == "latex")
613 font.setLatex(LyXFont::ON);
614 else if (tok == "default")
615 font.setLatex(LyXFont::INHERIT);
617 lex.printError("Unknown LaTeX font flag "
619 } else if (token == "\\direction") {
621 string tok = lex.GetString();
623 font.setDirection(LyXFont::LTR_DIR);
624 else if (tok == "rtl")
625 font.setDirection(LyXFont::RTL_DIR);
626 else if (tok == "default")
627 font.setDirection(LyXFont::INHERIT_DIR);
629 lex.printError("Unknown font flag "
631 } else if (token == "\\emph") {
633 font.setEmph(font.setLyXMisc(lex.GetString()));
634 } else if (token == "\\bar") {
636 string tok = lex.GetString();
637 // This is dirty, but gone with LyX3. (Asger)
639 font.setUnderbar(LyXFont::ON);
640 else if (tok == "no")
641 font.setUnderbar(LyXFont::OFF);
642 else if (tok == "default")
643 font.setUnderbar(LyXFont::INHERIT);
645 lex.printError("Unknown bar font flag "
647 } else if (token == "\\noun") {
649 font.setNoun(font.setLyXMisc(lex.GetString()));
650 } else if (token == "\\color") {
652 font.setLyXColor(lex.GetString());
653 } else if (token == "\\align") {
654 tmpret = lex.FindToken(string_align);
655 if (tmpret == -1) ++tmpret;
656 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
658 for (; tmpret > 0; --tmpret)
659 tmpret2 = tmpret2 * 2;
660 par->align = LyXAlignment(tmpret2);
662 } else if (token == "\\added_space_top") {
664 par->added_space_top = lex.GetString();
665 } else if (token == "\\added_space_bottom") {
667 par->added_space_bottom = lex.GetString();
668 } else if (token == "\\pextra_type") {
670 par->pextra_type = lex.GetInteger();
671 } else if (token == "\\pextra_width") {
673 par->pextra_width = lex.GetString();
674 } else if (token == "\\pextra_widthp") {
676 par->pextra_widthp = lex.GetString();
677 } else if (token == "\\pextra_alignment") {
679 par->pextra_alignment = lex.GetInteger();
680 } else if (token == "\\pextra_hfill") {
682 par->pextra_hfill = lex.GetInteger();
683 } else if (token == "\\pextra_start_minipage") {
685 par->pextra_start_minipage = lex.GetInteger();
686 } else if (token == "\\labelwidthstring") {
688 par->labelwidthstring = lex.GetString();
689 /* do not delete this token, it is still needed! */
690 } else if (token == "\\end_inset") {
691 /* simple ignore this. The insets do not have
693 // but insets should read it, it is a part of
694 //the inset isn't it? Lgb.
695 } else if (token == "\\begin_inset") {
697 tmptok = lex.GetString();
698 /* test the different insets */
699 if (tmptok == "Quotes") {
700 inset = new InsetQuotes;
702 par->InsertChar(pos, LyXParagraph::META_INSET);
703 par->InsertInset(pos, inset);
704 par->SetFont(pos, font);
706 } else if (tmptok == "\\i") {
707 inset = new InsetLatexAccent;
709 par->InsertChar(pos, LyXParagraph::META_INSET);
710 par->InsertInset(pos, inset);
711 par->SetFont(pos, font);
713 } else if (tmptok == "FormulaMacro") {
714 inset = new InsetFormulaMacro;
716 par->InsertChar(pos, LyXParagraph::META_INSET);
717 par->InsertInset(pos, inset);
718 par->SetFont(pos, font);
720 } else if (tmptok == "Formula") {
721 inset = new InsetFormula;
723 par->InsertChar(pos, LyXParagraph::META_INSET);
724 par->InsertInset(pos, inset);
725 par->SetFont(pos, font);
727 } else if (tmptok == "Figure") {
728 inset = new InsetFig(100, 100, this);
730 par->InsertChar(pos, LyXParagraph::META_INSET);
731 par->InsertInset(pos, inset);
732 par->SetFont(pos, font);
734 } else if (tmptok == "Info") {
735 inset = new InsetInfo;
737 par->InsertChar(pos, LyXParagraph::META_INSET);
738 par->InsertInset(pos, inset);
739 par->SetFont(pos, font);
741 } else if (tmptok == "Include") {
742 inset = new InsetInclude(string(), this);
744 par->InsertChar(pos, LyXParagraph::META_INSET);
745 par->InsertInset(pos, inset);
746 par->SetFont(pos, font);
748 } else if (tmptok == "LatexCommand") {
751 if (inscmd.getCmdName() == "cite") {
752 inset = new InsetCitation(inscmd.getContents(), inscmd.getOptions());
753 } else if (inscmd.getCmdName() == "bibitem") {
754 lex.printError("Wrong place for bibitem");
755 inset = inscmd.Clone();
756 } else if (inscmd.getCmdName() == "BibTeX") {
757 inset = new InsetBibtex(inscmd.getContents(), inscmd.getOptions(), this);
758 } else if (inscmd.getCmdName() == "index") {
759 inset = new InsetIndex(inscmd.getContents());
760 } else if (inscmd.getCmdName() == "include") {
761 inset = new InsetInclude(inscmd.getContents(), this);
762 } else if (inscmd.getCmdName() == "label") {
763 inset = new InsetLabel(inscmd.getCommand());
764 } else if (inscmd.getCmdName() == "url"
765 || inscmd.getCmdName() == "htmlurl") {
766 inset = new InsetUrl(inscmd.getCommand());
767 } else if (inscmd.getCmdName() == "ref"
768 || inscmd.getCmdName() == "pageref") {
769 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
770 inset = new InsetRef(inscmd, this);
772 #warning Verify that this else clause is still needed. (Lgb)
773 // This condition comes from a
774 // temporary solution to the latexdel
775 // ref inset that was transformed to
776 // an empty ref inset plus the body
777 // surronded by latexdel insets
779 string cont, opt, tmptmptok, cmdname;
781 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
786 tmptmptok = lex.GetString();
787 if(tmptmptok[0] == '\\') {
788 if( tmptmptok == "\\backslash")
798 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
803 tmptmptok = lex.GetString();
804 if(tmptmptok[0] == '\\') {
805 if( tmptmptok == "\\backslash")
815 while(lex.IsOK() && lex.GetString() != "\\end_inset" ) {
821 cmdname = "\\" + inscmd.getCmdName();
822 cmdname += "[" + cont + "]";
823 cmdname += "{" + opt + "}";
824 inset = new InsetRef(cmdname, this);
826 } else if (inscmd.getCmdName() == "tableofcontents") {
827 inset = new InsetTOC(this);
828 } else if (inscmd.getCmdName() == "listoffigures") {
829 inset = new InsetLOF(this);
830 } else if (inscmd.getCmdName() == "listofalgorithms") {
831 inset = new InsetLOA(this);
832 } else if (inscmd.getCmdName() == "listoftables") {
833 inset = new InsetLOT(this);
834 } else if (inscmd.getCmdName() == "printindex") {
835 inset = new InsetPrintIndex(this);
836 } else if (inscmd.getCmdName() == "lyxparent") {
837 inset = new InsetParent(inscmd.getContents(), this);
841 par->InsertChar(pos, LyXParagraph::META_INSET);
842 par->InsertInset(pos, inset);
843 par->SetFont(pos, font);
847 } else if (token == "\\InsetQuotes") {
848 inset = new InsetQuotes;
850 par->InsertChar(pos, LyXParagraph::META_INSET);
851 par->InsertInset(pos, inset);
852 par->SetFont(pos, font);
854 } else if (token == "\\InsetFormula") {
855 inset = new InsetFormula;
857 par->InsertChar(pos, LyXParagraph::META_INSET);
858 par->InsertInset(pos, inset);
859 par->SetFont(pos, font);
861 } else if (token == "\\SpecialChar") {
862 inset = new InsetSpecialChar;
864 par->InsertChar(pos, LyXParagraph::META_INSET);
865 par->InsertInset(pos, inset);
866 par->SetFont(pos, font);
868 } else if (token == "\\Figure") {
869 inset = new InsetFig(100, 100, this);
871 par->InsertChar(pos, LyXParagraph::META_INSET);
872 par->InsertInset(pos, inset);
873 par->SetFont(pos, font);
875 } else if (token == "\\newline") {
876 par->InsertChar(pos, LyXParagraph::META_NEWLINE);
877 par->SetFont(pos, font);
879 } else if (token == "\\LyXTable") {
880 par->table = new LyXTable(lex);
881 } else if (token == "\\hfill") {
882 par->InsertChar(pos, LyXParagraph::META_HFILL);
883 par->SetFont(pos, font);
885 } else if (token == "\\protected_separator") {
886 par->InsertChar(pos, LyXParagraph::META_PROTECTED_SEPARATOR);
887 par->SetFont(pos, font);
889 } else if (token == "\\bibitem") { // ale970302
891 par->bibkey = new InsetBibKey;
892 par->bibkey->Read(lex);
893 }else if (token == "\\backslash") {
894 par->InsertChar(pos, '\\');
895 par->SetFont(pos, font);
897 }else if (token == "\\the_end") {
900 // This should be insurance for the future: (Asger)
901 lex.printError("Unknown token `$$Token'. "
902 "Inserting as text.");
903 int n = token.length();
904 for (int i = 0; i < n; ++i) {
905 par->InsertChar(pos, token[i]);
906 par->SetFont(pos, font);
915 paragraph = return_par;
921 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
927 token = lex.GetString();
928 if (token == "\\lyxformat") { // the first token _must_ be...
930 format = lex.GetFloat();
932 if (LYX_FORMAT - format > 0.05) {
933 printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
936 if (format - LYX_FORMAT > 0.05) {
937 printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
940 bool the_end = readLyXformat2(lex, par);
941 // Formats >= 2.13 support "\the_end" marker
948 WriteAlert(_("Warning!"),
949 _("Reading of document is not complete"),
950 _("Maybe the document is truncated"));
951 // We simulate a safe reading anyways to allow
952 // users to take the chance... (Asger)
956 WriteAlert(_("ERROR!"),
957 _("Old LyX file format found. "
958 "Use LyX 0.10.x to read this!"));
962 } else { // "\\lyxformat" not found
963 WriteAlert(_("ERROR!"), _("Not a LyX file!"));
966 WriteAlert(_("ERROR!"), _("Unable to read file!"));
972 // Should probably be moved to somewhere else: BufferView? LyXView?
973 bool Buffer::save(bool makeBackup) const
975 // We don't need autosaves in the immediate future. (Asger)
976 resetAutosaveTimers();
980 string s = fileName() + '~';
981 // Rename is the wrong way of making a backup,
982 // this is the correct way.
983 /* truss cp fil fil2:
984 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
985 stat("LyXVC.lyx", 0xEFFFF688) = 0
986 open("LyXVC.lyx", O_RDONLY) = 3
987 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
988 fstat(4, 0xEFFFF508) = 0
989 fstat(3, 0xEFFFF508) = 0
990 read(3, " # T h i s f i l e w".., 8192) = 5579
991 write(4, " # T h i s f i l e w".., 5579) = 5579
992 read(3, 0xEFFFD4A0, 8192) = 0
995 chmod("LyXVC3.lyx", 0100644) = 0
996 lseek(0, 0, SEEK_CUR) = 46440
1000 // Should proabaly have some more error checking here.
1001 // Should be cleaned up in 0.13, at least a bit.
1002 // Doing it this way, also makes the inodes stay the same.
1003 // This is still not a very good solution, in particular we
1004 // might loose the owner of the backup.
1005 FileInfo finfo(fileName());
1006 if (finfo.exist()) {
1007 mode_t fmode = finfo.getMode();
1008 struct utimbuf * times = new struct utimbuf;
1010 times->actime = finfo.getAccessTime();
1011 times->modtime = finfo.getModificationTime();
1012 ifstream ifs(fileName().c_str());
1013 ofstream ofs(s.c_str(), ios::out|ios::trunc);
1018 ::chmod(s.c_str(), fmode);
1020 if (::utime(s.c_str(), times)) {
1021 lyxerr << "utime error." << endl;
1024 lyxerr << "LyX was not able to make "
1025 "backupcopy. Beware." << endl;
1031 if (writeFile(fileName(), false)) {
1034 // now delete the autosavefile
1035 string a = OnlyPath(fileName());
1037 a += OnlyFilename(fileName());
1039 FileInfo fileinfo(a);
1040 if (fileinfo.exist()) {
1041 if (::remove(a.c_str()) != 0) {
1042 WriteFSAlert(_("Could not delete "
1043 "auto-save file!"), a);
1047 // Saving failed, so backup is not backup
1049 string s = fileName() + '~';
1050 ::rename(s.c_str(), fileName().c_str());
1058 // Returns false if unsuccesful
1059 bool Buffer::writeFile(string const & fname, bool flag) const
1061 // if flag is false writeFile will not create any GUI
1062 // warnings, only cerr.
1063 // Needed for autosave in background or panic save (Matthias 120496)
1065 if (read_only && (fname == filename)) {
1066 // Here we should come with a question if we should
1067 // perform the write anyway.
1069 lyxerr << _("Error! Document is read-only: ")
1072 WriteAlert(_("Error! Document is read-only: "),
1077 FileInfo finfo(fname);
1078 if (finfo.exist() && !finfo.writable()) {
1079 // Here we should come with a question if we should
1080 // try to do the save anyway. (i.e. do a chmod first)
1082 lyxerr << _("Error! Cannot write file: ")
1085 WriteFSAlert(_("Error! Cannot write file: "),
1090 ofstream ofs(fname.c_str());
1093 lyxerr << _("Error! Cannot open file: ")
1096 WriteFSAlert(_("Error! Cannot open file: "),
1100 // The top of the file should not be written by params.
1102 // write out a comment in the top of the file
1103 ofs << '#' << LYX_DOCVERSION
1104 << " created this file. For more info see http://www.lyx.org/\n";
1105 ofs.setf(ios::showpoint|ios::fixed);
1107 ofs << "\\lyxformat " << setw(4) << LYX_FORMAT << "\n";
1109 // now write out the buffer paramters.
1110 params.writeFile(ofs);
1112 char footnoteflag = 0;
1115 // this will write out all the paragraphs
1116 // using recursive descent.
1117 paragraph->writeFile(ofs, params, footnoteflag, depth);
1119 // Write marker that shows file is complete
1120 ofs << "\n\\the_end" << endl;
1122 // how to check if close went ok?
1127 void Buffer::writeFileAscii(string const & fname, int linelen)
1129 LyXFont font1, font2;
1131 char c, footnoteflag = 0, depth = 0;
1133 LyXParagraph::size_type i;
1134 int j, h, ltype = 0, ltype_depth = 0,
1135 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1138 bool ref_printed = false;
1140 ofstream ofs(fname.c_str());
1142 WriteFSAlert(_("Error: Cannot write file:"), fname);
1146 string fname1 = TmpFileName();
1147 LyXParagraph * par = paragraph;
1151 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1153 par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1155 /* begins a footnote environment ? */
1156 if (footnoteflag != par->footnoteflag) {
1157 footnoteflag = par->footnoteflag;
1159 j = strlen(string_footnotekinds[par->footnotekind])+4;
1160 if (currlinelen + j > linelen)
1163 << string_footnotekinds[par->footnotekind] << "] ";
1168 /* begins or ends a deeper area ?*/
1169 if (depth != par->depth) {
1170 if (par->depth > depth) {
1171 while (par->depth > depth) {
1176 while (par->depth < depth) {
1182 /* First write the layout */
1183 tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1184 if (tmp == "Itemize") {
1186 ltype_depth = depth+1;
1187 } else if (tmp == "Enumerate") {
1189 ltype_depth = depth+1;
1190 } else if (strstr(tmp.c_str(), "ection")) {
1192 ltype_depth = depth+1;
1193 } else if (strstr(tmp.c_str(), "aragraph")) {
1195 ltype_depth = depth+1;
1196 } else if (tmp == "Description") {
1198 ltype_depth = depth+1;
1199 } else if (tmp == "Abstract") {
1202 } else if (tmp == "Bibliography") {
1210 /* maybe some vertical spaces */
1212 /* the labelwidthstring used in lists */
1216 /* some pagebreaks? */
1220 /* what about the alignment */
1223 /* dummy layout, that means a footnote ended */
1224 footnoteflag = LyXParagraph::NO_FOOTNOTE;
1229 /* It might be a table */
1232 if (!lyxrc->ascii_roff_command.empty() &&
1233 lyxrc->ascii_roff_command != "none") {
1234 RoffAsciiTable(ofs, par);
1241 cells = par->table->columns;
1242 clen = new int [cells];
1243 memset(clen, 0, sizeof(int) * cells);
1244 for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1245 c = par->GetChar(i);
1246 if (c == LyXParagraph::META_INSET) {
1247 if ((inset = par->GetInset(i))) {
1248 ofstream fs(fname1.c_str());
1250 WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1253 inset->Latex(fs, -1);
1254 h += fs.tellp() - 1;
1255 remove(fname1.c_str());
1257 } else if (c == LyXParagraph::META_NEWLINE) {
1261 j = (++j) % par->table->NumberOfCellsInRow(actcell);
1269 font1 = LyXFont(LyXFont::ALL_INHERIT);
1271 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1272 if (!i && !footnoteflag && !noparbreak){
1274 for(j = 0; j < depth; ++j)
1276 currlinelen = depth * 2;
1278 case 0: /* Standard */
1279 case 4: /* (Sub)Paragraph */
1280 case 5: /* Description */
1282 case 6: /* Abstract */
1283 ofs << "Abstract\n\n";
1285 case 7: /* Bibliography */
1287 ofs << "References\n\n";
1292 ofs << par->labelstring << " ";
1295 if (ltype_depth > depth) {
1296 for(j = ltype_depth - 1; j > depth; --j)
1298 currlinelen += (ltype_depth-depth)*2;
1301 for(j = 0; j < cells; ++j) {
1303 for(h = 0; h < (clen[j] + 1);
1308 for(j = 0; j < depth; ++j)
1310 currlinelen = depth * 2;
1311 if (ltype_depth > depth) {
1312 for(j = ltype_depth;
1315 currlinelen += (ltype_depth-depth)*2;
1320 font2 = par->GetFontSettings(i);
1321 if (font1.latex() != font2.latex()) {
1322 if (font2.latex() == LyXFont::OFF)
1330 c = par->GetChar(i);
1334 case LyXParagraph::META_INSET:
1335 if ((inset = par->GetInset(i))) {
1337 inset->Latex(ofs, -1);
1338 currlinelen += (ofs.tellp() - fpos);
1339 actpos += (ofs.tellp() - fpos) - 1;
1342 case LyXParagraph::META_NEWLINE:
1344 if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1345 for(j = actpos; j < clen[cell - 1]; ++j)
1348 for(j = 0; j < depth; ++j)
1350 currlinelen = depth*2;
1351 if (ltype_depth > depth) {
1352 for(j = ltype_depth; j > depth; --j)
1354 currlinelen += (ltype_depth-depth) * 2;
1356 for(j = 0; j < cells; ++j) {
1358 for(h = 0; h < (clen[j] + 1); ++h)
1362 for(j = 0; j < depth; ++j)
1364 currlinelen = depth * 2;
1365 if (ltype_depth > depth) {
1366 for(j = ltype_depth;
1369 currlinelen += (ltype_depth-depth)*2;
1375 j < clen[cell - 1]; ++j)
1381 currlinelen = actpos = 0;
1384 for(j = 0; j < depth; ++j)
1386 currlinelen = depth * 2;
1387 if (ltype_depth > depth) {
1388 for(j = ltype_depth;
1391 currlinelen += (ltype_depth - depth) * 2;
1395 case LyXParagraph::META_HFILL:
1398 case LyXParagraph::META_PROTECTED_SEPARATOR:
1405 if (currlinelen > linelen - 10
1406 && c == ' ' && i + 2 < par->size()) {
1408 for(j = 0; j < depth; ++j)
1410 currlinelen = depth * 2;
1411 if (ltype_depth > depth) {
1412 for(j = ltype_depth;
1415 currlinelen += (ltype_depth-depth)*2;
1417 } else if (c != '\0')
1420 lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1426 for(j = actpos; j < clen[cell - 1]; ++j)
1429 for(j = 0; j < depth; ++j)
1431 currlinelen = depth * 2;
1432 if (ltype_depth > depth) {
1433 for(j = ltype_depth; j > depth; --j)
1435 currlinelen += (ltype_depth - depth) * 2;
1437 for(j = 0; j < cells; ++j) {
1439 for(h = 0; h < (clen[j] + 1); ++h)
1452 void Buffer::makeLaTeXFile(string const & fname,
1453 string const & original_path,
1454 bool nice, bool only_body)
1456 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1458 niceFile = nice; // this will be used by Insetincludes.
1460 tex_code_break_column = lyxrc->ascii_linelen;
1462 LyXTextClass const & tclass =
1463 textclasslist.TextClass(params.textclass);
1465 ofstream ofs(fname.c_str());
1467 WriteFSAlert(_("Error: Cannot open file: "), fname);
1471 // validate the buffer.
1472 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1473 LaTeXFeatures features(tclass.numLayouts());
1475 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1478 // The starting paragraph of the coming rows is the
1479 // first paragraph of the document. (Asger)
1480 texrow.start(paragraph, 0);
1484 if (!only_body && nice) {
1485 LFile += "%% " LYX_DOCVERSION " created this file. "
1486 "For more info, see http://www.lyx.org/.\n";
1487 LFile += "%% Do not edit unless you really know what you are doing.\n";
1491 lyxerr.debug() << "lyx header finished" << endl;
1492 // There are a few differences between nice LaTeX and usual files:
1493 // usual is \batchmode and has a
1494 // special input@path to allow the including of figures
1495 // with either \input or \includegraphics (what figinsets do).
1496 // batchmode is not set if there is a tex_code_break_column.
1497 // In this case somebody is interested in the generated LaTeX,
1498 // so this is OK. input@path is set when the actual parameter
1499 // original_path is set. This is done for usual tex-file, but not
1500 // for nice-latex-file. (Matthias 250696)
1503 // code for usual, NOT nice-latex-file
1504 LFile += "\\batchmode\n"; // changed
1505 // from \nonstopmode
1508 if (!original_path.empty()) {
1509 LFile += "\\makeatletter\n";
1511 LFile += "\\def\\input@path{{" + original_path
1514 LFile += "\\makeatother\n";
1518 LFile += "\\documentclass";
1520 string options; // the document class options.
1522 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1523 // only write if existing in list (and not default)
1524 options += params.fontsize;
1529 if (!params.use_geometry &&
1530 (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1531 switch (params.papersize) {
1532 case BufferParams::PAPER_A4PAPER:
1533 options += "a4paper,";
1535 case BufferParams::PAPER_USLETTER:
1536 options += "letterpaper,";
1538 case BufferParams::PAPER_A5PAPER:
1539 options += "a5paper,";
1541 case BufferParams::PAPER_B5PAPER:
1542 options += "b5paper,";
1544 case BufferParams::PAPER_EXECUTIVEPAPER:
1545 options += "executivepaper,";
1547 case BufferParams::PAPER_LEGALPAPER:
1548 options += "legalpaper,";
1554 if (params.sides != tclass.sides()) {
1555 switch (params.sides) {
1556 case LyXTextClass::OneSide:
1557 options += "oneside,";
1559 case LyXTextClass::TwoSides:
1560 options += "twoside,";
1567 if (params.columns != tclass.columns()) {
1568 if (params.columns == 2)
1569 options += "twocolumn,";
1571 options += "onecolumn,";
1574 if (!params.use_geometry
1575 && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1576 options += "landscape,";
1578 // language should be a parameter to \documentclass
1579 if (params.language != "default") {
1580 if (params.language == "hebrew")
1581 options += "english,";
1582 else if (lyxrc->rtl_support)
1583 options += "hebrew,";
1584 options += params.language + ',';
1585 } else if (lyxrc->rtl_support)
1586 options += "hebrew,english,";
1588 // the user-defined options
1589 if (!params.options.empty()) {
1590 options += params.options + ',';
1593 if (!options.empty()){
1594 options = strip(options, ',');
1601 LFile += textclasslist.LatexnameOfClass(params.textclass);
1604 // end of \documentclass defs
1606 // font selection must be done before loading fontenc.sty
1607 if (params.fonts != "default") {
1608 LFile += "\\usepackage{" + params.fonts + "}\n";
1611 // this one is not per buffer
1612 if (lyxrc->fontenc != "default") {
1613 LFile += "\\usepackage[" + lyxrc->fontenc
1617 if (params.inputenc != "default") {
1618 LFile += "\\usepackage[" + params.inputenc
1623 /* at the very beginning the text parameters */
1624 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1625 switch (params.paperpackage) {
1626 case BufferParams::PACKAGE_A4:
1627 LFile += "\\usepackage{a4}\n";
1630 case BufferParams::PACKAGE_A4WIDE:
1631 LFile += "\\usepackage{a4wide}\n";
1634 case BufferParams::PACKAGE_WIDEMARGINSA4:
1635 LFile += "\\usepackage[widemargins]{a4}\n";
1640 if (params.use_geometry) {
1641 LFile += "\\usepackage{geometry}\n";
1643 LFile += "\\geometry{verbose";
1644 if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1645 LFile += ",landscape";
1646 switch (params.papersize2) {
1647 case BufferParams::VM_PAPER_CUSTOM:
1648 if (!params.paperwidth.empty())
1649 LFile += ",paperwidth="
1650 + params.paperwidth;
1651 if (!params.paperheight.empty())
1652 LFile += ",paperheight="
1653 + params.paperheight;
1655 case BufferParams::VM_PAPER_USLETTER:
1656 LFile += ",letterpaper";
1658 case BufferParams::VM_PAPER_USLEGAL:
1659 LFile += ",legalpaper";
1661 case BufferParams::VM_PAPER_USEXECUTIVE:
1662 LFile += ",executivepaper";
1664 case BufferParams::VM_PAPER_A3:
1665 LFile += ",a3paper";
1667 case BufferParams::VM_PAPER_A4:
1668 LFile += ",a4paper";
1670 case BufferParams::VM_PAPER_A5:
1671 LFile += ",a5paper";
1673 case BufferParams::VM_PAPER_B3:
1674 LFile += ",b3paper";
1676 case BufferParams::VM_PAPER_B4:
1677 LFile += ",b4paper";
1679 case BufferParams::VM_PAPER_B5:
1680 LFile += ",b5paper";
1683 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1684 switch (lyxrc->default_papersize) {
1685 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1686 case BufferParams::PAPER_USLETTER:
1687 LFile += ",letterpaper";
1689 case BufferParams::PAPER_LEGALPAPER:
1690 LFile += ",legalpaper";
1692 case BufferParams::PAPER_EXECUTIVEPAPER:
1693 LFile += ",executivepaper";
1695 case BufferParams::PAPER_A3PAPER:
1696 LFile += ",a3paper";
1698 case BufferParams::PAPER_A4PAPER:
1699 LFile += ",a4paper";
1701 case BufferParams::PAPER_A5PAPER:
1702 LFile += ",a5paper";
1704 case BufferParams::PAPER_B5PAPER:
1705 LFile += ",b5paper";
1709 if (!params.topmargin.empty())
1710 LFile += ",tmargin=" + params.topmargin;
1711 if (!params.bottommargin.empty())
1712 LFile += ",bmargin=" + params.bottommargin;
1713 if (!params.leftmargin.empty())
1714 LFile += ",lmargin=" + params.leftmargin;
1715 if (!params.rightmargin.empty())
1716 LFile += ",rmargin=" + params.rightmargin;
1717 if (!params.headheight.empty())
1718 LFile += ",headheight=" + params.headheight;
1719 if (!params.headsep.empty())
1720 LFile += ",headsep=" + params.headsep;
1721 if (!params.footskip.empty())
1722 LFile += ",footskip=" + params.footskip;
1726 if (params.use_amsmath
1727 && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1728 LFile += "\\usepackage{amsmath}\n";
1731 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1732 if (params.pagestyle == "fancy") {
1733 LFile += "\\usepackage{fancyhdr}\n";
1736 LFile += "\\pagestyle{" + params.pagestyle + "}\n";
1740 // We try to load babel late, in case it interferes
1741 // with other packages.
1742 if (params.language != "default" || lyxrc->rtl_support ) {
1743 LFile += "\\usepackage{babel}\n";
1747 if (params.secnumdepth != tclass.secnumdepth()) {
1748 LFile += "\\setcounter{secnumdepth}{";
1749 LFile += tostr(params.secnumdepth);
1753 if (params.tocdepth != tclass.tocdepth()) {
1754 LFile += "\\setcounter{tocdepth}{";
1755 LFile += tostr(params.tocdepth);
1760 if (params.paragraph_separation) {
1761 switch (params.defskip.kind()) {
1762 case VSpace::SMALLSKIP:
1763 LFile += "\\setlength\\parskip{\\smallskipamount}\n";
1765 case VSpace::MEDSKIP:
1766 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1768 case VSpace::BIGSKIP:
1769 LFile += "\\setlength\\parskip{\\bigskipamount}\n";
1771 case VSpace::LENGTH:
1772 LFile += "\\setlength\\parskip{"
1773 + params.defskip.length().asLatexString()
1776 default: // should never happen // Then delete it.
1777 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1782 LFile += "\\setlength\\parindent{0pt}\n";
1786 // Write out what we've generated so far...and reset LFile
1790 // Now insert the LyX specific LaTeX commands...
1791 string preamble, tmppreamble;
1793 // The optional packages;
1794 preamble = features.getPackages(params);
1796 // this might be useful...
1797 preamble += "\n\\makeatletter\n\n";
1799 // Some macros LyX will need
1800 tmppreamble = features.getMacros(params);
1802 if (!tmppreamble.empty()) {
1803 preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1804 "LyX specific LaTeX commands.\n"
1805 + tmppreamble + '\n';
1808 // the text class specific preamble
1809 tmppreamble = features.getTClassPreamble(params);
1810 if (!tmppreamble.empty()) {
1811 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1812 "Textclass specific LaTeX commands.\n"
1813 + tmppreamble + '\n';
1816 /* the user-defined preamble */
1817 if (!params.preamble.empty()) {
1818 preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1819 "User specified LaTeX commands.\n"
1820 + params.preamble + '\n';
1823 preamble += "\\makeatother\n\n";
1825 // Itemize bullet settings need to be last in case the user
1826 // defines their own bullets that use a package included
1827 // in the user-defined preamble -- ARRae
1828 // Actually it has to be done much later than that
1829 // since some packages like frenchb make modifications
1830 // at \begin{document} time -- JMarc
1832 for (int i = 0; i < 4; ++i) {
1833 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1834 if (bullets_def.empty())
1835 bullets_def="\\AtBeginDocument{\n";
1836 bullets_def += " \\renewcommand{\\labelitemi";
1838 // `i' is one less than the item to modify
1845 bullets_def += "ii";
1851 bullets_def += "}{" +
1852 params.user_defined_bullets[i].getText()
1857 if (!bullets_def.empty())
1858 preamble += bullets_def + "}\n\n";
1860 for (int j = countChar(preamble, '\n'); j-- ;) {
1867 LFile += "\\begin{document}\n\n";
1871 lyxerr.debug() << "preamble finished, now the body." << endl;
1873 bool was_title = false;
1874 bool already_title = false;
1880 LyXParagraph * par = paragraph;
1886 lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
1888 LyXLayout const & layout = textclasslist.Style(params.textclass,
1891 if (layout.intitle) {
1892 if (already_title) {
1893 lyxerr <<"Error in MakeLatexFile: You"
1894 " should not mix title layouts"
1895 " with normal ones." << endl;
1898 } else if (was_title && !already_title) {
1899 LFile += "\\maketitle\n";
1901 already_title = true;
1904 // We are at depth 0 so we can just use
1905 // ordinary \footnote{} generation
1906 // flag this with ftcount
1908 if (layout.isEnvironment()
1909 || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
1910 par = par->TeXEnvironment(LFile, texrow,
1911 ftnote, ft_texrow, ftcount);
1913 par = par->TeXOnePar(LFile, texrow,
1914 ftnote, ft_texrow, ftcount);
1917 // Write out what we've generated...and reset LFile
1920 LFile += "\\addtocounter{footnote}{-";
1921 LFile += tostr(ftcount - 1);
1925 texrow += ft_texrow;
1930 if (loop_count == 2) {
1931 // fwrite()ing every second time through the loop
1932 // gains a few extra % of speed; going higher than
1933 // 2 will slow things down again. I'll look at
1934 // LFile.length() in a future revision. ARRae
1941 // It might be that we only have a title in this document
1942 if (was_title && !already_title) {
1943 LFile += "\\maketitle\n";
1948 LFile += "\\end{document}\n";
1951 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1953 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1957 // Just to be sure. (Asger)
1960 // Write out what we've generated...and reset LFile
1964 // tex_code_break_column's value is used to decide
1965 // if we are in batchmode or not (within mathed_write()
1966 // in math_write.C) so we must set it to a non-zero
1967 // value when we leave otherwise we save incorrect .lyx files.
1968 tex_code_break_column = lyxrc->ascii_linelen;
1970 // How to check if the close went ok when using fstreams
1972 lyxerr.debug() << "Finished making latex file." << endl;
1976 bool Buffer::isLatex() const
1978 return textclasslist.TextClass(params.textclass).outputType() == LATEX;
1982 bool Buffer::isLinuxDoc() const
1984 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
1988 bool Buffer::isLiterate() const
1990 return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
1994 bool Buffer::isDocBook() const
1996 return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2000 bool Buffer::isSGML() const
2002 return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2003 textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2007 void Buffer::sgmlOpenTag(ostream & os, int depth,
2008 string const & latexname) const
2010 os << string(depth, ' ') << "<" << latexname << ">\n";
2014 void Buffer::sgmlCloseTag(ostream & os, int depth,
2015 string const & latexname) const
2017 os << string(depth, ' ') << "</" << latexname << ">\n";
2021 void Buffer::makeLinuxDocFile(string const & fname, int column)
2023 LyXParagraph * par = paragraph;
2025 string top_element = textclasslist.LatexnameOfClass(params.textclass);
2026 string environment_stack[10];
2029 int depth = 0; /* paragraph depth */
2031 ofstream ofs(fname.c_str());
2034 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2038 tex_code_break_column = column;
2041 if (params.preamble.empty()) {
2042 ofs << "<!doctype linuxdoc system>\n\n";
2045 ofs << "<!doctype linuxdoc system \n [ "
2046 << params.preamble << " \n]>\n\n";
2049 ofs << "<!-- " << LYX_DOCVERSION
2050 << " created this file. For more info see http://www.lyx.org/"
2053 if(params.options.empty())
2054 sgmlOpenTag(ofs, 0, top_element);
2056 string top = top_element;
2058 top += params.options;
2059 sgmlOpenTag(ofs, 0, top);
2063 int desc_on = 0; /* description mode*/
2064 LyXLayout const & style =
2065 textclasslist.Style(users->buffer()->params.textclass,
2067 par->AutoDeleteInsets();
2069 /* treat <toc> as a special case for compatibility with old code */
2070 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2071 Inset * inset = par->GetInset(0);
2072 char lyx_code = inset->LyxCode();
2073 if (lyx_code == Inset::TOC_CODE){
2074 string temp = "toc";
2075 sgmlOpenTag(ofs, depth, temp);
2078 linuxDocHandleFootnote(ofs, par, depth);
2083 // environment tag closing
2084 for( ; depth > par->depth; --depth) {
2085 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2086 environment_stack[depth].clear();
2089 // write opening SGML tags
2090 switch(style.latextype) {
2091 case LATEX_PARAGRAPH:
2092 if(depth == par->depth
2093 && !environment_stack[depth].empty()) {
2094 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2095 environment_stack[depth].clear();
2101 sgmlOpenTag(ofs, depth, style.latexname());
2106 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2108 if (!environment_stack[depth].empty()){
2109 sgmlCloseTag(ofs, depth,
2110 environment_stack[depth]);
2114 environment_stack[depth].clear();
2115 sgmlOpenTag(ofs, depth, style.latexname());
2118 case LATEX_ENVIRONMENT:
2119 case LATEX_ITEM_ENVIRONMENT:
2120 if(depth == par->depth
2121 && environment_stack[depth] != style.latexname()
2122 && !environment_stack[depth].empty()) {
2124 sgmlCloseTag(ofs, depth,
2125 environment_stack[depth]);
2126 environment_stack[depth].clear();
2128 if (depth < par->depth) {
2130 environment_stack[depth].clear();
2132 if (environment_stack[depth] != style.latexname()) {
2135 sgmlOpenTag(ofs, depth, temp);
2137 environment_stack[depth] = style.latexname();
2138 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2140 if(style.latextype == LATEX_ENVIRONMENT) break;
2142 desc_on = (style.labeltype == LABEL_MANUAL);
2149 sgmlOpenTag(ofs, depth + 1, item_name);
2152 sgmlOpenTag(ofs, depth, style.latexname());
2157 SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2160 linuxDocHandleFootnote(ofs, par, depth);
2162 while(par && par->IsDummy());
2165 /* write closing SGML tags */
2166 switch(style.latextype) {
2168 case LATEX_ENVIRONMENT:
2169 case LATEX_ITEM_ENVIRONMENT:
2172 sgmlCloseTag(ofs, depth, style.latexname());
2177 /* Close open tags */
2178 for(; depth > 0; --depth)
2179 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2181 if(!environment_stack[depth].empty())
2182 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2185 sgmlCloseTag(ofs, 0, top_element);
2188 // How to check for successful close
2192 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2195 string tag = "footnote";
2197 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2198 sgmlOpenTag(os, depth + 1, tag);
2199 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2200 sgmlCloseTag(os, depth + 1, tag);
2206 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2207 int const depth, int desc_on,
2208 LyXParagraph * & par)
2210 LyXParagraph * tpar = par;
2211 string tmp_par, extra_par;
2212 while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2213 (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2217 tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2218 "Caption").second) {
2219 sgmlOpenTag(os, depth + 1, inner_tag);
2220 SimpleDocBookOnePar(tmp_par, extra_par, tpar,
2221 desc_on, depth + 2);
2222 tmp_par = strip(tmp_par);
2223 tmp_par = frontStrip(tmp_par);
2225 sgmlCloseTag(os, depth+1, inner_tag);
2226 if(!extra_par.empty())
2232 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2235 string tag, inner_tag;
2236 string tmp_par, extra_par;
2237 bool inner_span = false;
2240 // This is not how I like to see enums. They should not be anonymous
2241 // and variables of its type should not be declared right after the
2242 // last brace. (Lgb)
2249 } last = NO_ONE, present = FOOTNOTE_LIKE;
2251 while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2252 if(last == present) {
2254 if(!tmp_par.empty()) {
2257 sgmlCloseTag(os, depth+1, inner_tag);
2258 sgmlOpenTag(os, depth+1, inner_tag);
2265 if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2266 if(!extra_par.empty()) os << extra_par;
2267 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2270 switch (par->footnotekind) {
2271 case LyXParagraph::FOOTNOTE:
2272 case LyXParagraph::ALGORITHM:
2275 present = FOOTNOTE_LIKE;
2278 case LyXParagraph::MARGIN:
2281 present = MARGIN_LIKE;
2284 case LyXParagraph::FIG:
2285 case LyXParagraph::WIDE_FIG:
2287 inner_tag = "title";
2291 case LyXParagraph::TAB:
2292 case LyXParagraph::WIDE_TAB:
2294 inner_tag = "title";
2299 sgmlOpenTag(os, depth, tag);
2300 if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2301 DocBookHandleCaption(os, inner_tag, depth,
2305 sgmlOpenTag(os, depth + 1, inner_tag);
2308 // ignore all caption here, we processed them above!!!
2309 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2310 "Caption").second) {
2311 SimpleDocBookOnePar(tmp_par, extra_par, par,
2312 desc_on, depth + 2);
2314 tmp_par = frontStrip(strip(tmp_par));
2320 if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2321 if(!extra_par.empty()) os << extra_par;
2322 if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2326 /* push a tag in a style stack */
2327 void Buffer::push_tag(ostream & os, char const * tag,
2328 int & pos, char stack[5][3])
2330 /* pop all previous tags */
2331 for (int j = pos; j >= 0; --j)
2332 os << "</" << stack[j] << ">";
2335 sprintf(stack[++pos], "%s", tag);
2338 for (int i = 0; i <= pos; ++i)
2339 os << "<" << stack[i] << ">";
2342 void Buffer::pop_tag(ostream & os, char const * tag,
2343 int & pos, char stack[5][3])
2347 // pop all tags till specified one
2348 for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2349 os << "</" << stack[j] << ">";
2352 os << "</" << tag << ">";
2354 // push all tags, but the specified one
2355 for (j = j + 1; j <= pos; ++j) {
2356 os << "<" << stack[j] << ">";
2357 strcpy(stack[j-1], stack[j]);
2363 /* handle internal paragraph parsing -- layout already processed */
2365 // checks, if newcol chars should be put into this line
2366 // writes newline, if necessary.
2368 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2369 const unsigned int newcol)
2372 if (colcount > lyxrc->ascii_linelen) {
2374 colcount = newcol; // assume write after this call
2379 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2380 int desc_on, int const /*depth*/)
2382 LyXFont font1, font2;
2385 LyXParagraph::size_type main_body;
2387 LyXLayout const & style = textclasslist.Style(params.textclass,
2390 char family_type = 0; // family font flag
2391 bool is_bold = false; // series font flag
2392 char shape_type = 0; // shape font flag
2393 bool is_em = false; // emphasis (italic) font flag
2395 int stack_num = -1; // style stack position
2396 char stack[5][3]; // style stack
2397 unsigned int char_line_count = 5; // Heuristic choice ;-)
2399 if (style.labeltype != LABEL_MANUAL)
2402 main_body = par->BeginningOfMainBody();
2404 /* gets paragraph main font */
2406 font1 = style.labelfont;
2411 /* parsing main loop */
2412 for (LyXParagraph::size_type i = 0;
2413 i < par->size(); ++i) {
2415 /* handle quote tag */
2416 if (i == main_body && !par->IsDummy()) {
2421 font2 = par->getFont(i);
2423 if (font1.family() != font2.family()) {
2424 switch(family_type) {
2426 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2427 push_tag(os, "tt", stack_num, stack);
2430 else if (font2.family() == LyXFont::SANS_FAMILY) {
2431 push_tag(os, "sf", stack_num, stack);
2436 pop_tag(os, "tt", stack_num, stack);
2437 if (font2.family() == LyXFont::SANS_FAMILY) {
2438 push_tag(os, "sf", stack_num, stack);
2446 pop_tag(os, "sf", stack_num, stack);
2447 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2448 push_tag(os, "tt", stack_num, stack);
2457 /* handle bold face */
2458 if (font1.series() != font2.series()) {
2459 if (font2.series() == LyXFont::BOLD_SERIES) {
2460 push_tag(os, "bf", stack_num, stack);
2464 pop_tag(os, "bf", stack_num, stack);
2469 /* handle italic and slanted fonts */
2470 if (font1.shape() != font2.shape()) {
2471 switch(shape_type) {
2473 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2474 push_tag(os, "it", stack_num, stack);
2477 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2478 push_tag(os, "sl", stack_num, stack);
2483 pop_tag(os, "it", stack_num, stack);
2484 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2485 push_tag(os, "sl", stack_num, stack);
2493 pop_tag(os, "sl", stack_num, stack);
2494 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2495 push_tag(os, "it", stack_num, stack);
2503 /* handle <em> tag */
2504 if (font1.emph() != font2.emph()) {
2505 if (font2.emph() == LyXFont::ON) {
2506 push_tag(os, "em", stack_num, stack);
2509 pop_tag(os, "em", stack_num, stack);
2514 c = par->GetChar(i);
2516 if (font2.latex() == LyXFont::ON) {
2517 // "TeX"-Mode on == > SGML-Mode on.
2519 os << c; // see LaTeX-Generation...
2521 } else if (c == LyXParagraph::META_INSET) {
2522 inset = par->GetInset(i);
2524 inset->Linuxdoc(tmp_out);
2529 if (par->linuxDocConvertChar(c, sgml_string)
2530 && !style.free_spacing) { // in freespacing
2532 // non-breaking characters
2536 linux_doc_line_break(os, char_line_count, 6);
2541 linux_doc_line_break(os, char_line_count, 1);
2547 char_line_count += sgml_string.length();
2553 /* needed if there is an optional argument but no contents */
2554 if (main_body > 0 && main_body == par->size()) {
2558 /* pop all defined Styles */
2559 for (j = stack_num; j >= 0; --j) {
2560 linux_doc_line_break(os,
2562 3 + strlen(stack[j]));
2563 os << "</" << stack[j] << ">";
2566 /* resets description flag correctly */
2569 /* <tag> not closed... */
2570 linux_doc_line_break(os, char_line_count, 6);
2574 /* fprintf(file, "</p>");*/
2580 /* print an error message */
2581 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2582 char const * message)
2584 InsetError * new_inset;
2586 /* insert an error marker in text */
2587 new_inset = new InsetError(message);
2588 par->InsertChar(pos, LyXParagraph::META_INSET);
2589 par->InsertInset(pos, new_inset);
2592 // This constant defines the maximum number of
2593 // environment layouts that can be nesteded.
2594 // The same applies for command layouts.
2595 // These values should be more than enough.
2596 // José Matos (1999/07/22)
2598 enum { MAX_NEST_LEVEL = 25};
2600 void Buffer::makeDocBookFile(string const & fname, int column)
2602 LyXParagraph * par = paragraph;
2604 string top_element= textclasslist.LatexnameOfClass(params.textclass);
2605 string environment_stack[MAX_NEST_LEVEL];
2606 string environment_inner[MAX_NEST_LEVEL];
2607 string command_stack[MAX_NEST_LEVEL];
2608 bool command_flag= false;
2609 int command_depth= 0, command_base= 0, cmd_depth= 0;
2611 string item_name, command_name;
2612 string c_depth, c_params, tmps;
2614 int depth= 0; /* paragraph depth */
2616 tex_code_break_column = column;
2618 ofstream ofs(fname.c_str());
2620 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2626 ofs << "<!doctype " << top_element
2627 << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2629 if (params.preamble.empty())
2632 ofs << "\n [ " << params.preamble << " \n]>\n\n";
2634 ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION
2635 << "\n See http://www.lyx.org/ for more information -->\n";
2637 if(params.options.empty())
2638 sgmlOpenTag(ofs, 0, top_element);
2640 string top = top_element;
2642 top += params.options;
2643 sgmlOpenTag(ofs, 0, top);
2647 int desc_on= 0; /* description mode*/
2648 LyXLayout const & style = textclasslist.Style(users->buffer()->params.textclass,
2650 par->AutoDeleteInsets();
2652 /* environment tag closing */
2653 for( ; depth > par->depth; --depth) {
2654 if(environment_inner[depth] != "!-- --") {
2655 item_name= "listitem";
2656 sgmlCloseTag(ofs, command_depth + depth,
2658 if( environment_inner[depth] == "varlistentry")
2659 sgmlCloseTag(ofs, depth+command_depth,
2660 environment_inner[depth]);
2662 sgmlCloseTag(ofs, depth + command_depth,
2663 environment_stack[depth]);
2664 environment_stack[depth].clear();
2665 environment_inner[depth].clear();
2668 if(depth == par->depth
2669 && environment_stack[depth] != style.latexname()
2670 && !environment_stack[depth].empty()) {
2671 if(environment_inner[depth] != "!-- --") {
2672 item_name= "listitem";
2673 sgmlCloseTag(ofs, command_depth+depth,
2675 if( environment_inner[depth] == "varlistentry")
2677 depth + command_depth,
2678 environment_inner[depth]);
2681 sgmlCloseTag(ofs, depth + command_depth,
2682 environment_stack[depth]);
2684 environment_stack[depth].clear();
2685 environment_inner[depth].clear();
2688 // Write opening SGML tags.
2689 switch(style.latextype) {
2690 case LATEX_PARAGRAPH:
2691 if(style.latexname() != "dummy")
2692 sgmlOpenTag(ofs, depth+command_depth,
2698 LinuxDocError(par, 0,
2699 _("Error : Wrong depth for "
2700 "LatexType Command.\n"));
2702 command_name = style.latexname();
2704 tmps = style.latexparam();
2705 c_params = split(tmps, c_depth,'|');
2707 cmd_depth= atoi(c_depth.c_str());
2710 if(cmd_depth<command_base) {
2711 for(int j = command_depth;
2712 j >= command_base; --j)
2713 if(!command_stack[j].empty())
2714 sgmlCloseTag(ofs, j, command_stack[j]);
2715 command_depth= command_base= cmd_depth;
2717 else if(cmd_depth <= command_depth) {
2718 for(int j = command_depth;
2719 j >= cmd_depth; --j)
2721 if(!command_stack[j].empty())
2722 sgmlCloseTag(ofs, j, command_stack[j]);
2723 command_depth= cmd_depth;
2726 command_depth= cmd_depth;
2729 command_depth = command_base = cmd_depth;
2730 command_flag = true;
2732 command_stack[command_depth]= command_name;
2734 // treat label as a special case for
2735 // more WYSIWYM handling.
2736 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2737 Inset * inset = par->GetInset(0);
2738 char lyx_code = inset->LyxCode();
2739 if (lyx_code == Inset::LABEL_CODE){
2740 command_name += " id=\"";
2741 command_name += (static_cast<InsetCommand *>(inset))->getContents();
2742 command_name += "\"";
2747 sgmlOpenTag(ofs, depth+command_depth, command_name);
2748 item_name = "title";
2749 sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2752 case LATEX_ENVIRONMENT:
2753 case LATEX_ITEM_ENVIRONMENT:
2754 if (depth < par->depth) {
2756 environment_stack[depth].clear();
2759 if (environment_stack[depth] != style.latexname()) {
2760 environment_stack[depth] = style.latexname();
2761 environment_inner[depth] = "!-- --";
2762 sgmlOpenTag(ofs, depth + command_depth,
2763 environment_stack[depth]);
2765 if(environment_inner[depth] != "!-- --") {
2766 item_name= "listitem";
2768 command_depth + depth,
2770 if (environment_inner[depth] == "varlistentry")
2772 depth + command_depth,
2773 environment_inner[depth]);
2777 if(style.latextype == LATEX_ENVIRONMENT) {
2778 if(!style.latexparam().empty())
2779 sgmlOpenTag(ofs, depth + command_depth,
2780 style.latexparam());
2784 desc_on = (style.labeltype == LABEL_MANUAL);
2787 environment_inner[depth]= "varlistentry";
2789 environment_inner[depth]= "listitem";
2791 sgmlOpenTag(ofs, depth + 1 + command_depth,
2792 environment_inner[depth]);
2796 sgmlOpenTag(ofs, depth + 1 + command_depth,
2801 sgmlOpenTag(ofs, depth + 1 + command_depth,
2806 sgmlOpenTag(ofs, depth + command_depth,
2812 string tmp_par, extra_par;
2814 SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
2815 depth + 1 + command_depth);
2819 DocBookHandleFootnote(ofs, par,
2820 depth + 1 + command_depth);
2822 while(par && par->IsDummy());
2825 /* write closing SGML tags */
2826 switch(style.latextype) {
2829 sgmlCloseTag(ofs, depth + command_depth, end_tag);
2831 case LATEX_ENVIRONMENT:
2832 if(!style.latexparam().empty())
2833 sgmlCloseTag(ofs, depth + command_depth,
2834 style.latexparam());
2836 case LATEX_ITEM_ENVIRONMENT:
2837 if(desc_on == 1) break;
2839 sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2841 case LATEX_PARAGRAPH:
2842 if(style.latexname() != "dummy")
2843 sgmlCloseTag(ofs, depth + command_depth,
2847 sgmlCloseTag(ofs, depth + command_depth,
2854 for(; depth >= 0; --depth) {
2855 if(!environment_stack[depth].empty()) {
2856 if(environment_inner[depth] != "!-- --") {
2857 item_name= "listitem";
2858 sgmlCloseTag(ofs, command_depth + depth,
2860 if( environment_inner[depth] == "varlistentry")
2861 sgmlCloseTag(ofs, depth + command_depth,
2862 environment_inner[depth]);
2865 sgmlCloseTag(ofs, depth + command_depth,
2866 environment_stack[depth]);
2870 for(int j = command_depth; j >= command_base; --j)
2871 if(!command_stack[j].empty())
2872 sgmlCloseTag(ofs, j, command_stack[j]);
2875 sgmlCloseTag(ofs, 0, top_element);
2878 // How to check for successful close
2882 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
2883 LyXParagraph * par, int & desc_on,
2887 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
2890 LyXFont font1, font2;
2893 LyXParagraph::size_type main_body;
2895 string emph= "emphasis";
2896 bool emph_flag= false;
2897 int char_line_count= 0;
2899 LyXLayout const & style = textclasslist.Style(params.textclass,
2902 if (style.labeltype != LABEL_MANUAL)
2905 main_body = par->BeginningOfMainBody();
2907 /* gets paragraph main font */
2909 font1 = style.labelfont;
2913 char_line_count = depth;
2914 if(!style.free_spacing)
2915 for (j = 0; j < depth; ++j)
2918 /* parsing main loop */
2919 for (LyXParagraph::size_type i = 0;
2920 i < par->size(); ++i) {
2921 font2 = par->getFont(i);
2923 /* handle <emphasis> tag */
2924 if (font1.emph() != font2.emph() && i) {
2925 if (font2.emph() == LyXFont::ON) {
2926 file += "<emphasis>";
2929 file += "</emphasis>";
2934 c = par->GetChar(i);
2936 if (c == LyXParagraph::META_INSET) {
2937 inset = par->GetInset(i);
2939 inset->DocBook(tmp_out);
2941 // This code needs some explanation:
2942 // Two insets are treated specially
2943 // label if it is the first element in a command paragraph
2945 // graphics inside tables or figure floats can't go on
2946 // title (the equivalente in latex for this case is caption
2947 // and title should come first
2950 if(desc_on!= 3 || i!= 0) {
2951 if(!tmp_out.empty() && tmp_out[0] == '@') {
2953 extra += frontStrip(tmp_out, '@');
2955 file += frontStrip(tmp_out, '@');
2960 } else if (font2.latex() == LyXFont::ON) {
2961 // "TeX"-Mode on ==> SGML-Mode on.
2968 if (par->linuxDocConvertChar(c, sgml_string)
2969 && !style.free_spacing) { // in freespacing
2971 // non-breaking characters
2976 file += "</term><listitem><para>";
2984 file += sgml_string;
2990 /* needed if there is an optional argument but no contents */
2991 if (main_body > 0 && main_body == par->size()) {
2995 file += "</emphasis>";
2998 /* resets description flag correctly */
3001 /* <term> not closed... */
3009 int Buffer::runLaTeX()
3011 if (!users->text) return 0;
3015 // get LaTeX-Filename
3016 string name = getLatexName();
3018 string path = OnlyPath(filename);
3020 string org_path = path;
3021 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3025 Path p(path); // path to LaTeX file
3026 users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));
3028 // Remove all error insets
3029 bool a = users->removeAutoInsets();
3031 // Always generate the LaTeX file
3032 makeLaTeXFile(name, org_path, false);
3035 // do the LaTex run(s)
3037 string latex_command = lyxrc->pdf_mode ?
3038 lyxrc->pdflatex_command : lyxrc->latex_command;
3039 LaTeX latex(latex_command, name, filepath);
3040 int res = latex.run(terr,
3041 users->owner()->getMiniBuffer()); // running latex
3043 // check return value from latex.run().
3044 if ((res & LaTeX::NO_LOGFILE)) {
3045 WriteAlert(_("LaTeX did not work!"),
3046 _("Missing log file:"), name);
3047 } else if ((res & LaTeX::ERRORS)) {
3048 users->owner()->getMiniBuffer()->Set(_("Done"));
3049 // Insert all errors as errors boxes
3050 users->insertErrors(terr);
3052 // Dvi should also be kept dirty if the latex run
3053 // ends up with errors. However it should be possible
3054 // to view a dirty dvi too.
3056 //no errors or any other things to think about so:
3057 users->owner()->getMiniBuffer()->Set(_("Done"));
3061 // if we removed error insets before we ran LaTeX or if we inserted
3062 // error insets after we ran LaTeX this must be run:
3063 if (a || (res & LaTeX::ERRORS)){
3066 users->updateScrollbar();
3070 return latex.getNumErrors();
3074 int Buffer::runLiterate()
3076 if (!users->text) return 0;
3080 // get LaTeX-Filename
3081 string name = getLatexName();
3082 // get Literate-Filename
3083 string lit_name = ChangeExtension (getLatexName(),
3084 lyxrc->literate_extension, true);
3086 string path = OnlyPath(filename);
3088 string org_path = path;
3089 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3093 Path p(path); // path to Literate file
3094 users->owner()->getMiniBuffer()->Set(_("Running Literate..."));
3096 // Remove all error insets
3097 bool a = users->removeAutoInsets();
3099 // generate the Literate file if necessary
3100 if (!isDviClean() || a) {
3101 makeLaTeXFile(lit_name, org_path, false);
3105 string latex_command = lyxrc->pdf_mode ?
3106 lyxrc->pdflatex_command : lyxrc->latex_command;
3107 Literate literate(latex_command, name, filepath,
3109 lyxrc->literate_command, lyxrc->literate_error_filter,
3110 lyxrc->build_command, lyxrc->build_error_filter);
3112 int res = literate.weave(terr, users->owner()->getMiniBuffer());
3114 // check return value from literate.weave().
3115 if ((res & Literate::NO_LOGFILE)) {
3116 WriteAlert(_("Literate command did not work!"),
3117 _("Missing log file:"), name);
3118 } else if ((res & Literate::ERRORS)) {
3119 users->owner()->getMiniBuffer()->Set(_("Done"));
3120 // Insert all errors as errors boxes
3121 users->insertErrors(terr);
3123 // Dvi should also be kept dirty if the latex run
3124 // ends up with errors. However it should be possible
3125 // to view a dirty dvi too.
3127 //no errors or any other things to think about so:
3128 users->owner()->getMiniBuffer()->Set(_("Done"));
3132 // if we removed error insets before we ran LaTeX or if we inserted
3133 // error insets after we ran LaTeX this must be run:
3134 if (a || (res & Literate::ERRORS)){
3137 users->updateScrollbar();
3141 return literate.getNumErrors();
3145 int Buffer::buildProgram()
3147 if (!users->text) return 0;
3151 // get LaTeX-Filename
3152 string name = getLatexName();
3153 // get Literate-Filename
3154 string lit_name = ChangeExtension(getLatexName(),
3155 lyxrc->literate_extension, true);
3157 string path = OnlyPath(filename);
3159 string org_path = path;
3160 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3164 Path p(path); // path to Literate file
3165 users->owner()->getMiniBuffer()->Set(_("Building Program..."));
3167 // Remove all error insets
3168 bool a = users->removeAutoInsets();
3170 // generate the LaTeX file if necessary
3171 if (!isNwClean() || a) {
3172 makeLaTeXFile(lit_name, org_path, false);
3176 string latex_command = lyxrc->pdf_mode ?
3177 lyxrc->pdflatex_command : lyxrc->latex_command;
3178 Literate literate(latex_command, name, filepath,
3180 lyxrc->literate_command, lyxrc->literate_error_filter,
3181 lyxrc->build_command, lyxrc->build_error_filter);
3183 int res = literate.build(terr, users->owner()->getMiniBuffer());
3185 // check return value from literate.build().
3186 if ((res & Literate::NO_LOGFILE)) {
3187 WriteAlert(_("Build did not work!"),
3188 _("Missing log file:"), name);
3189 } else if ((res & Literate::ERRORS)) {
3190 users->owner()->getMiniBuffer()->Set(_("Done"));
3191 // Insert all errors as errors boxes
3192 users->insertErrors(terr);
3194 // Literate files should also be kept dirty if the literate
3195 // command run ends up with errors.
3197 //no errors or any other things to think about so:
3198 users->owner()->getMiniBuffer()->Set(_("Done"));
3202 // if we removed error insets before we ran Literate/Build or if we inserted
3203 // error insets after we ran Literate/Build this must be run:
3204 if (a || (res & Literate::ERRORS)){
3207 users->updateScrollbar();
3211 return literate.getNumErrors();
3215 // This should be enabled when the Chktex class is implemented. (Asger)
3216 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3217 // Other flags: -wall -v0 -x
3218 int Buffer::runChktex()
3220 if (!users->text) return 0;
3224 // get LaTeX-Filename
3225 string name = getLatexName();
3226 string path = OnlyPath(filename);
3228 string org_path = path;
3229 if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3233 Path p(path); // path to LaTeX file
3234 users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3236 // Remove all error insets
3237 bool a = users->removeAutoInsets();
3239 // Generate the LaTeX file if neccessary
3240 if (!isDviClean() || a) {
3241 makeLaTeXFile(name, org_path, false);
3246 Chktex chktex(lyxrc->chktex_command, name, filepath);
3247 int res = chktex.run(terr); // run chktex
3250 WriteAlert(_("chktex did not work!"),
3251 _("Could not run with file:"), name);
3252 } else if (res > 0) {
3253 // Insert all errors as errors boxes
3254 users->insertErrors(terr);
3257 // if we removed error insets before we ran chktex or if we inserted
3258 // error insets after we ran chktex, this must be run:
3262 users->updateScrollbar();
3270 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
3272 LyXFont font1(LyXFont::ALL_INHERIT);
3275 LyXParagraph::size_type i;
3279 string fname1 = TmpFileName(string(), "RAT1");
3280 string fname2 = TmpFileName(string(), "RAT2");
3282 ofstream ofs(fname1.c_str());
3284 WriteAlert(_("LYX_ERROR:"),
3285 _("Cannot open temporary file:"), fname1);
3288 par->table->RoffEndOfCell(ofs, -1);
3289 for (i = 0; i < par->size(); ++i) {
3290 c = par->GetChar(i);
3291 if (par->table->IsContRow(cell)) {
3292 if (c == LyXParagraph::META_NEWLINE)
3296 font2 = par->GetFontSettings(i);
3297 if (font1.latex() != font2.latex()) {
3298 if (font2.latex() != LyXFont::OFF)
3302 case LyXParagraph::META_INSET:
3303 if ((inset = par->GetInset(i))) {
3304 fstream fs(fname2.c_str(), ios::in|ios::out);
3306 WriteAlert(_("LYX_ERROR:"),
3307 _("Cannot open temporary file:"), fname2);
3309 remove(fname1.c_str());
3312 inset->Latex(fs, -1);
3325 case LyXParagraph::META_NEWLINE:
3326 if (par->table->CellHasContRow(cell)>= 0)
3327 par->RoffContTableRows(ofs, i+1, cell);
3328 par->table->RoffEndOfCell(ofs, cell);
3331 case LyXParagraph::META_HFILL:
3333 case LyXParagraph::META_PROTECTED_SEPARATOR:
3343 << "RoffAsciiTable:"
3344 " NULL char in structure." << endl;
3348 par->table->RoffEndOfCell(ofs, cell);
3350 string cmd = lyxrc->ascii_roff_command + " >" + fname2;
3351 cmd = subst(cmd, "$$FName", fname1);
3352 Systemcalls one(Systemcalls::System, cmd);
3353 if (!(lyxerr.debugging(Debug::ROFF))) {
3354 remove(fname1.c_str());
3356 ifstream ifs(fname2.c_str());
3358 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3361 // now output the produced file
3365 WriteAlert(_("Error!"),
3366 _("Error executing *roff command on table"));
3367 // overread leading blank lines
3368 while(!ifs && (c == '\n'))
3371 for(j = 0; j < par->depth; ++j)
3373 while(!ifs && (c != '\n')) {
3378 // overread trailing blank lines
3379 while(!ifs && (c == '\n'))
3383 remove(fname2.c_str());
3387 /// changed Heinrich Bauer, 23/03/98
3388 bool Buffer::isDviClean() const
3390 if (lyxrc->use_tempdir)
3391 return dvi_clean_tmpd;
3393 return dvi_clean_orgd;
3397 /// changed Heinrich Bauer, 23/03/98
3398 void Buffer::markDviClean()
3400 if (lyxrc->use_tempdir)
3401 dvi_clean_tmpd = true;
3403 dvi_clean_orgd = true;
3407 /// changed Heinrich Bauer, 23/03/98
3408 void Buffer::markDviDirty()
3410 if (lyxrc->use_tempdir)
3411 dvi_clean_tmpd = false;
3413 dvi_clean_orgd = false;
3417 void Buffer::validate(LaTeXFeatures & features) const
3419 LyXParagraph * par = paragraph;
3420 LyXTextClass const & tclass =
3421 textclasslist.TextClass(params.textclass);
3423 // AMS Style is at document level
3425 features.amsstyle = (params.use_amsmath ||
3426 tclass.provides(LyXTextClass::amsmath));
3429 // We don't use "lyxerr.debug" because of speed. (Asger)
3430 if (lyxerr.debugging(Debug::LATEX))
3431 lyxerr << "Paragraph: " << par << endl;
3433 // Now just follow the list of paragraphs and run
3434 // validate on each of them.
3435 par->validate(features);
3437 // and then the next paragraph
3441 // the bullet shapes are buffer level not paragraph level
3442 // so they are tested here
3443 for (int i = 0; i < 4; ++i) {
3444 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3445 int font = params.user_defined_bullets[i].getFont();
3448 .user_defined_bullets[i]
3455 features.latexsym = true;
3459 features.amssymb = true;
3461 else if ((font >= 2 && font <= 5)) {
3462 features.pifont = true;
3467 if (lyxerr.debugging(Debug::LATEX)) {
3468 features.showStruct(params);
3473 void Buffer::setPaperStuff()
3475 params.papersize = BufferParams::PAPER_DEFAULT;
3476 char c1 = params.paperpackage;
3477 if (c1 == BufferParams::PACKAGE_NONE) {
3478 char c2 = params.papersize2;
3479 if (c2 == BufferParams::VM_PAPER_USLETTER)
3480 params.papersize = BufferParams::PAPER_USLETTER;
3481 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3482 params.papersize = BufferParams::PAPER_LEGALPAPER;
3483 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3484 params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3485 else if (c2 == BufferParams::VM_PAPER_A3)
3486 params.papersize = BufferParams::PAPER_A3PAPER;
3487 else if (c2 == BufferParams::VM_PAPER_A4)
3488 params.papersize = BufferParams::PAPER_A4PAPER;
3489 else if (c2 == BufferParams::VM_PAPER_A5)
3490 params.papersize = BufferParams::PAPER_A5PAPER;
3491 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3492 (c2 == BufferParams::VM_PAPER_B5))
3493 params.papersize = BufferParams::PAPER_B5PAPER;
3494 } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3495 (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3496 params.papersize = BufferParams::PAPER_A4PAPER;
3500 // This function should be in Buffer because it's a buffer's property (ale)
3501 string Buffer::getIncludeonlyList(char delim)
3504 LyXParagraph * par = paragraph;
3505 LyXParagraph::size_type pos;
3509 while ((inset = par->ReturnNextInsetPointer(pos))){
3510 if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3511 InsetInclude * insetinc =
3512 static_cast<InsetInclude*>(inset);
3513 if (insetinc->isInclude()
3514 && insetinc->isNoLoad()) {
3517 lst += ChangeExtension(insetinc->getContents(), string(), true);
3524 lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3529 // This is also a buffer property (ale)
3530 string Buffer::getReferenceList(char delim)
3532 /// if this is a child document and the parent is already loaded
3533 /// Use the parent's list instead [ale990407]
3534 if (!params.parentname.empty()
3535 && bufferlist.exists(params.parentname)) {
3536 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3538 return tmp->getReferenceList(delim);
3541 LyXParagraph * par = paragraph;
3542 LyXParagraph::size_type pos;
3547 while ((inset = par->ReturnNextInsetPointer(pos))){
3548 for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
3551 lst += inset->getLabel(i);
3557 lyxerr.debug() << "References(" << lst << ")" << endl;
3562 // This is also a buffer property (ale)
3563 string Buffer::getBibkeyList(char delim)
3565 /// if this is a child document and the parent is already loaded
3566 /// Use the parent's list instead [ale990412]
3567 if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3568 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3570 return tmp->getBibkeyList(delim);
3574 LyXParagraph * par = paragraph;
3577 if (!bibkeys.empty())
3579 bibkeys += par->bibkey->getContents();
3584 // Might be either using bibtex or a child has bibliography
3585 if (bibkeys.empty()) {
3589 LyXParagraph::size_type pos = -1;
3591 // Search for Bibtex or Include inset
3592 while ((inset = par->ReturnNextInsetPointer(pos))) {
3593 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3594 if (!bibkeys.empty())
3596 bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
3597 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3598 string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
3600 if (!bibkeys.empty())
3611 lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3616 bool Buffer::isDepClean(string const & name) const
3618 DEPCLEAN * item = dep_clean;
3619 while (item && item->master != name)
3621 if (!item) return true;
3626 void Buffer::markDepClean(string const & name)
3629 dep_clean = new DEPCLEAN;
3630 dep_clean->clean = true;
3631 dep_clean->master = name;
3632 dep_clean->next = 0;
3634 DEPCLEAN* item = dep_clean;
3635 while (item && item->master != name)
3640 item = new DEPCLEAN;
3642 item->master = name;
3649 void Buffer::Dispatch(string const & command)
3651 // Split command string into command and argument
3652 string cmd, line = frontStrip(command);
3653 string arg = strip(frontStrip(split(line, cmd, ' ')));
3655 Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3659 void Buffer::Dispatch(int action, string const & argument)
3663 MenuExport(this, argument);
3667 lyxerr << "A truly unknown func!" << endl;