3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
22 #include "errorlist.h"
25 #include "funcrequest.h"
27 #include "iterators.h"
30 #include "LaTeXFeatures.h"
31 #include "LyXAction.h"
36 #include "paragraph.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
44 #include "insets/insetbibitem.h"
45 #include "insets/insetbibtex.h"
46 #include "insets/insetinclude.h"
47 #include "insets/insettext.h"
49 #include "frontends/Alert.h"
51 #include "graphics/Previews.h"
53 #include "support/FileInfo.h"
54 #include "support/filetools.h"
55 #include "support/gzstream.h"
56 #include "support/lyxlib.h"
57 #include "support/os.h"
58 #include "support/path.h"
59 #include "support/textutils.h"
60 #include "support/tostr.h"
62 #include <boost/bind.hpp>
64 #include "support/std_sstream.h"
76 using lyx::support::AddName;
77 using lyx::support::ascii_lowercase;
78 using lyx::support::atoi;
79 using lyx::support::bformat;
80 using lyx::support::ChangeExtension;
81 using lyx::support::cmd_ret;
82 using lyx::support::compare_ascii_no_case;
83 using lyx::support::compare_no_case;
84 using lyx::support::contains;
85 using lyx::support::CreateBufferTmpDir;
86 using lyx::support::destroyDir;
87 using lyx::support::FileInfo;
88 using lyx::support::FileInfo;
89 using lyx::support::getExtFromContents;
90 using lyx::support::IsDirWriteable;
91 using lyx::support::IsFileWriteable;
92 using lyx::support::LibFileSearch;
93 using lyx::support::ltrim;
94 using lyx::support::MakeAbsPath;
95 using lyx::support::MakeDisplayPath;
96 using lyx::support::MakeLatexName;
97 using lyx::support::OnlyFilename;
98 using lyx::support::OnlyPath;
99 using lyx::support::Path;
100 using lyx::support::QuoteName;
101 using lyx::support::removeAutosaveFile;
102 using lyx::support::rename;
103 using lyx::support::RunCommand;
104 using lyx::support::split;
105 using lyx::support::strToInt;
106 using lyx::support::subst;
107 using lyx::support::tempName;
108 using lyx::support::trim;
110 namespace os = lyx::support::os;
114 using std::make_pair;
119 using std::ostringstream;
127 // all these externs should eventually be removed.
128 extern BufferList bufferlist;
132 const int LYX_FORMAT = 225;
134 bool openFileWrite(ofstream & ofs, string const & fname)
136 ofs.open(fname.c_str());
138 string const file = MakeDisplayPath(fname, 50);
139 string text = bformat(_("Could not open the specified "
140 "document\n%1$s."), file);
141 Alert::error(_("Could not open file"), text);
150 typedef std::map<string, bool> DepClean;
154 Impl(Buffer & parent, string const & file, bool readonly);
156 limited_stack<Undo> undostack;
157 limited_stack<Undo> redostack;
159 ParagraphList paragraphs;
165 /// need to regenerate .tex ?
169 mutable bool lyx_clean;
171 /// is autosave needed
172 mutable bool bak_clean;
174 /// is this a unnamed file (New...)
180 /// name of the file the buffer is associated with.
183 /// The path to the document file.
186 boost::scoped_ptr<Messages> messages;
188 /** set to true only when the file is fully loaded.
189 * Used to prevent the premature generation of previews
190 * and by the citation inset.
192 bool file_fully_loaded;
196 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
198 lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
199 filename(file), filepath(OnlyPath(file)), file_fully_loaded(false)
201 lyxvc.buffer(&parent);
202 if (readonly_ || lyxrc.use_tempdir)
203 temppath = CreateBufferTmpDir();
207 Buffer::Buffer(string const & file, bool ronly)
208 : pimpl_(new Impl(*this, file, ronly))
210 lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
216 lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
217 // here the buffer should take care that it is
218 // saved properly, before it goes into the void.
222 if (!temppath().empty() && destroyDir(temppath()) != 0) {
223 Alert::warning(_("Could not remove temporary directory"),
224 bformat(_("Could not remove the temporary directory %1$s"), temppath()));
227 paragraphs().clear();
229 // Remove any previewed LaTeX snippets associated with this buffer.
230 lyx::graphics::Previews::get().removeLoader(*this);
234 limited_stack<Undo> & Buffer::undostack()
236 return pimpl_->undostack;
240 limited_stack<Undo> const & Buffer::undostack() const
242 return pimpl_->undostack;
246 limited_stack<Undo> & Buffer::redostack()
248 return pimpl_->redostack;
252 limited_stack<Undo> const & Buffer::redostack() const
254 return pimpl_->redostack;
258 BufferParams & Buffer::params()
260 return pimpl_->params;
264 BufferParams const & Buffer::params() const
266 return pimpl_->params;
270 ParagraphList & Buffer::paragraphs()
272 return pimpl_->paragraphs;
276 ParagraphList const & Buffer::paragraphs() const
278 return pimpl_->paragraphs;
282 LyXVC & Buffer::lyxvc()
284 return pimpl_->lyxvc;
288 LyXVC const & Buffer::lyxvc() const
290 return pimpl_->lyxvc;
294 string const & Buffer::temppath() const
296 return pimpl_->temppath;
300 bool & Buffer::niceFile()
302 return pimpl_->nicefile;
306 bool Buffer::niceFile() const
308 return pimpl_->nicefile;
312 TexRow & Buffer::texrow()
314 return pimpl_->texrow;
318 TexRow const & Buffer::texrow() const
320 return pimpl_->texrow;
324 string const Buffer::getLatexName(bool no_path) const
326 string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
327 return no_path ? OnlyFilename(name) : name;
331 pair<Buffer::LogType, string> const Buffer::getLogName() const
333 string const filename = getLatexName(false);
335 if (filename.empty())
336 return make_pair(Buffer::latexlog, string());
338 string path = OnlyPath(filename);
340 if (lyxrc.use_tempdir || !IsDirWriteable(path))
343 string const fname = AddName(path,
344 OnlyFilename(ChangeExtension(filename,
347 AddName(path, OnlyFilename(
348 ChangeExtension(filename,
349 formats.extension("literate") + ".out")));
351 // If no Latex log or Build log is newer, show Build log
353 FileInfo const f_fi(fname);
354 FileInfo const b_fi(bname);
357 (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
358 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
359 return make_pair(Buffer::buildlog, bname);
361 lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
362 return make_pair(Buffer::latexlog, fname);
366 void Buffer::setReadonly(bool flag)
368 if (pimpl_->read_only != flag) {
369 pimpl_->read_only = flag;
375 void Buffer::setFileName(string const & newfile)
377 pimpl_->filename = MakeAbsPath(newfile);
378 pimpl_->filepath = OnlyPath(pimpl_->filename);
379 setReadonly(IsFileWriteable(pimpl_->filename) == 0);
384 // We'll remove this later. (Lgb)
387 void unknownClass(string const & unknown)
389 Alert::warning(_("Unknown document class"),
390 bformat(_("Using the default document class, because the "
391 "class %1$s is unknown."), unknown));
396 int Buffer::readHeader(LyXLex & lex)
398 int unknown_tokens = 0;
402 string const token = lex.getString();
407 if (token == "\\end_header")
410 lyxerr[Debug::PARSER] << "Handling header token: `"
411 << token << '\'' << endl;
414 string unknown = params().readToken(lex, token);
415 if (!unknown.empty()) {
416 if (unknown[0] != '\\') {
417 unknownClass(unknown);
420 string const s = bformat(_("Unknown token: "
424 error(ErrorItem(_("Header error"), s,
429 return unknown_tokens;
433 // candidate for move to BufferView
434 // (at least some parts in the beginning of the func)
437 // changed to be public and have one parameter
438 // if par = 0 normal behavior
439 // else insert behavior
440 // Returns false if "\end_document" is not read (Asger)
441 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
443 Paragraph::depth_type depth = 0;
444 bool the_end_read = false;
446 if (paragraphs().empty()) {
448 if (!params().getLyXTextClass().load()) {
449 string theclass = params().getLyXTextClass().name();
450 Alert::error(_("Can't load document class"), bformat(
451 "Using the default document class, because the "
452 " class %1$s could not be loaded.", theclass));
453 params().textclass = 0;
456 // We don't want to adopt the parameters from the
457 // document we insert, so read them into a temporary buffer
458 // and then discard it
460 Buffer tmpbuf("", false);
461 tmpbuf.readHeader(lex);
466 string const token = lex.getString();
471 lyxerr[Debug::PARSER] << "Handling token: `"
472 << token << '\'' << endl;
474 if (token == "\\end_document") {
479 readParagraph(lex, token, paragraphs(), pit, depth);
486 int Buffer::readParagraph(LyXLex & lex, string const & token,
487 ParagraphList & pars, ParagraphList::iterator & pit,
488 lyx::depth_type & depth)
490 static Change current_change;
493 if (token == "\\begin_layout") {
494 lex.pushToken(token);
497 par.params().depth(depth);
498 if (params().tracking_changes)
500 LyXFont f(LyXFont::ALL_INHERIT, params().language);
504 if (pit != pars.end())
507 pit = pars.insert(pit, par);
509 // FIXME: goddamn InsetTabular makes us pass a Buffer
511 ::readParagraph(*this, *pit, lex);
513 } else if (token == "\\begin_deeper") {
515 } else if (token == "\\end_deeper") {
517 lex.printError("\\end_deeper: " "depth is already null");
528 // needed to insert the selection
529 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
530 LyXFont const & fn,string const & str)
532 LyXLayout_ptr const & layout = par->layout();
536 par->checkInsertChar(font);
537 // insert the string, don't insert doublespace
538 bool space_inserted = true;
539 bool autobreakrows = !par->inInset() ||
540 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
541 for(string::const_iterator cit = str.begin();
542 cit != str.end(); ++cit) {
544 if (autobreakrows && (!par->empty() || par->allowEmpty())) {
545 breakParagraph(params(), paragraphs(), par, pos,
546 layout->isEnvironment());
549 space_inserted = true;
553 // do not insert consecutive spaces if !free_spacing
554 } else if ((*cit == ' ' || *cit == '\t') &&
555 space_inserted && !par->isFreeSpacing()) {
557 } else if (*cit == '\t') {
558 if (!par->isFreeSpacing()) {
559 // tabs are like spaces here
560 par->insertChar(pos, ' ', font);
562 space_inserted = true;
564 const pos_type nb = 8 - pos % 8;
565 for (pos_type a = 0; a < nb ; ++a) {
566 par->insertChar(pos, ' ', font);
569 space_inserted = true;
571 } else if (!IsPrintable(*cit)) {
572 // Ignore unprintables
575 // just insert the character
576 par->insertChar(pos, *cit, font);
578 space_inserted = (*cit == ' ');
585 bool Buffer::readFile(string const & filename)
587 // Check if the file is compressed.
588 string const format = getExtFromContents(filename);
589 if (format == "gzip" || format == "zip" || format == "compress") {
590 params().compressed = true;
593 bool ret = readFile(filename, paragraphs().begin());
595 // After we have read a file, we must ensure that the buffer
596 // language is set and used in the gui.
597 // If you know of a better place to put this, please tell me. (Lgb)
598 updateDocLang(params().language);
604 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
607 lex.setFile(filename);
609 return readFile(lex, filename, pit);
613 bool Buffer::fully_loaded() const
615 return pimpl_->file_fully_loaded;
619 void Buffer::fully_loaded(bool value)
621 pimpl_->file_fully_loaded = value;
625 bool Buffer::readFile(LyXLex & lex, string const & filename,
626 ParagraphList::iterator pit)
628 BOOST_ASSERT(!filename.empty());
631 Alert::error(_("Document could not be read"),
632 bformat(_("%1$s could not be read."), filename));
637 string const token(lex.getString());
640 Alert::error(_("Document could not be read"),
641 bformat(_("%1$s could not be read."), filename));
645 // the first token _must_ be...
646 if (token != "\\lyxformat") {
647 lyxerr << "Token: " << token << endl;
649 Alert::error(_("Document format failure"),
650 bformat(_("%1$s is not a LyX document."),
656 string tmp_format = lex.getString();
657 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
658 // if present remove ".," from string.
659 string::size_type dot = tmp_format.find_first_of(".,");
660 //lyxerr << " dot found at " << dot << endl;
661 if (dot != string::npos)
662 tmp_format.erase(dot, 1);
663 int file_format = strToInt(tmp_format);
664 //lyxerr << "format: " << file_format << endl;
666 if (file_format > LYX_FORMAT) {
667 Alert::warning(_("Document format failure"),
668 bformat(_("%1$s was created with a newer"
669 " version of LyX. This is likely to"
672 } else if (file_format < LYX_FORMAT) {
673 string const tmpfile = tempName();
674 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
675 if (command.empty()) {
676 Alert::error(_("Conversion script not found"),
677 bformat(_("%1$s is from an earlier"
678 " version of LyX, but the"
679 " conversion script lyx2lyx"
680 " could not be found."),
686 + " -o " + tmpfile + ' '
687 + QuoteName(filename);
688 lyxerr[Debug::INFO] << "Running '"
691 cmd_ret const ret = RunCommand(command);
692 if (ret.first != 0) {
693 Alert::error(_("Conversion script failed"),
694 bformat(_("%1$s is from an earlier version"
695 " of LyX, but the lyx2lyx script"
696 " failed to convert it."),
700 bool ret = readFile(tmpfile, pit);
701 // Do stuff with tmpfile name and buffer name here.
707 bool the_end = readBody(lex, pit);
708 params().setPaperStuff();
711 Alert::error(_("Document format failure"),
712 bformat(_("%1$s ended unexpectedly, which means"
713 " that it is probably corrupted."),
716 pimpl_->file_fully_loaded = true;
721 // Should probably be moved to somewhere else: BufferView? LyXView?
722 bool Buffer::save() const
724 // We don't need autosaves in the immediate future. (Asger)
725 resetAutosaveTimers();
729 if (lyxrc.make_backup) {
730 s = fileName() + '~';
731 if (!lyxrc.backupdir_path.empty())
732 s = AddName(lyxrc.backupdir_path,
733 subst(os::slashify_path(s),'/','!'));
735 // Rename is the wrong way of making a backup,
736 // this is the correct way.
737 /* truss cp fil fil2:
738 lstat("LyXVC3.lyx", 0xEFFFF898) Err#2 ENOENT
739 stat("LyXVC.lyx", 0xEFFFF688) = 0
740 open("LyXVC.lyx", O_RDONLY) = 3
741 open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
742 fstat(4, 0xEFFFF508) = 0
743 fstat(3, 0xEFFFF508) = 0
744 read(3, " # T h i s f i l e w".., 8192) = 5579
745 write(4, " # T h i s f i l e w".., 5579) = 5579
746 read(3, 0xEFFFD4A0, 8192) = 0
749 chmod("LyXVC3.lyx", 0100644) = 0
750 lseek(0, 0, SEEK_CUR) = 46440
754 // Should probably have some more error checking here.
755 // Doing it this way, also makes the inodes stay the same.
756 // This is still not a very good solution, in particular we
757 // might loose the owner of the backup.
758 FileInfo finfo(fileName());
760 mode_t fmode = finfo.getMode();
761 struct utimbuf times = {
762 finfo.getAccessTime(),
763 finfo.getModificationTime() };
765 ifstream ifs(fileName().c_str());
766 ofstream ofs(s.c_str(), ios::out|ios::trunc);
771 ::chmod(s.c_str(), fmode);
773 if (::utime(s.c_str(), ×)) {
774 lyxerr << "utime error." << endl;
777 lyxerr << "LyX was not able to make "
778 "backup copy. Beware." << endl;
783 if (writeFile(fileName())) {
785 removeAutosaveFile(fileName());
787 // Saving failed, so backup is not backup
788 if (lyxrc.make_backup) {
789 rename(s, fileName());
797 bool Buffer::writeFile(string const & fname) const
799 if (pimpl_->read_only && (fname == fileName())) {
803 FileInfo finfo(fname);
804 if (finfo.exist() && !finfo.writable()) {
810 if (params().compressed) {
811 gz::ogzstream ofs(fname.c_str());
816 retval = do_writeFile(ofs);
819 ofstream ofs(fname.c_str());
823 retval = do_writeFile(ofs);
830 bool Buffer::do_writeFile(ostream & ofs) const
834 // Use the standard "C" locale for file output.
835 ofs.imbue(std::locale::classic());
838 // The top of the file should not be written by params().
840 // write out a comment in the top of the file
841 ofs << "#LyX " << lyx_version
842 << " created this file. For more info see http://www.lyx.org/\n"
843 << "\\lyxformat " << LYX_FORMAT << "\n";
845 // now write out the buffer paramters.
846 params().writeFile(ofs);
848 ofs << "\\end_header\n";
850 Paragraph::depth_type depth = 0;
852 // this will write out all the paragraphs
853 // using recursive descent.
854 ParagraphList::const_iterator pit = paragraphs().begin();
855 ParagraphList::const_iterator pend = paragraphs().end();
856 for (; pit != pend; ++pit)
857 pit->write(*this, ofs, params(), depth);
859 // Write marker that shows file is complete
860 ofs << "\n\\end_document" << endl;
862 // Shouldn't really be needed....
865 // how to check if close went ok?
866 // Following is an attempt... (BE 20001011)
868 // good() returns false if any error occured, including some
870 // bad() returns true if something bad happened in the buffer,
871 // which should include file system full errors.
878 lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
880 lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
892 pair<int, string> const addDepth(int depth, int ldepth)
896 d += (ldepth - depth) * 2;
897 return make_pair(d, string(d, ' '));
903 string const Buffer::asciiParagraph(Paragraph const & par,
904 unsigned int linelen,
905 bool noparbreak) const
907 ostringstream buffer;
909 Paragraph::depth_type ltype_depth = 0;
910 bool ref_printed = false;
911 Paragraph::depth_type depth = par.params().depth();
913 // First write the layout
914 string const & tmp = par.layout()->name();
915 if (compare_no_case(tmp, "itemize") == 0) {
917 ltype_depth = depth + 1;
918 } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
920 ltype_depth = depth + 1;
921 } else if (contains(ascii_lowercase(tmp), "ection")) {
923 ltype_depth = depth + 1;
924 } else if (contains(ascii_lowercase(tmp), "aragraph")) {
926 ltype_depth = depth + 1;
927 } else if (compare_ascii_no_case(tmp, "description") == 0) {
929 ltype_depth = depth + 1;
930 } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
933 } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
941 /* maybe some vertical spaces */
943 /* the labelwidthstring used in lists */
947 /* some pagebreaks? */
951 /* what about the alignment */
953 // linelen <= 0 is special and means we don't have paragraph breaks
955 string::size_type currlinelen = 0;
961 buffer << string(depth * 2, ' ');
962 currlinelen += depth * 2;
965 // we should probably change to the paragraph language in the
966 // gettext here (if possible) so that strings are outputted in
967 // the correct language! (20012712 Jug)
971 case 4: // (Sub)Paragraph
972 case 5: // Description
976 buffer << _("Abstract") << "\n\n";
979 string const abst = _("Abstract: ");
981 currlinelen += abst.length();
984 case 7: // Bibliography
987 buffer << _("References") << "\n\n";
990 string const refs = _("References: ");
992 currlinelen += refs.length();
1000 string const parlab = par.params().labelString();
1001 buffer << parlab << ' ';
1002 currlinelen += parlab.length() + 1;
1010 pair<int, string> p = addDepth(depth, ltype_depth);
1012 currlinelen += p.first;
1015 // this is to change the linebreak to do it by word a bit more
1016 // intelligent hopefully! (only in the case where we have a
1017 // max linelength!) (Jug)
1021 for (pos_type i = 0; i < par.size(); ++i) {
1022 char c = par.getUChar(params(), i);
1024 case Paragraph::META_INSET:
1026 InsetOld const * inset = par.getInset(i);
1030 currlinelen += word.length();
1033 if (inset->ascii(*this, buffer, linelen)) {
1034 // to be sure it breaks paragraph
1035 currlinelen += linelen;
1044 currlinelen + word.length() > linelen - 10) {
1046 pair<int, string> p = addDepth(depth, ltype_depth);
1048 currlinelen = p.first;
1051 buffer << word << ' ';
1052 currlinelen += word.length() + 1;
1059 lyxerr[Debug::INFO] <<
1060 "writeAsciiFile: NULL char in structure." << endl;
1062 if ((linelen > 0) &&
1063 (currlinelen + word.length()) > linelen)
1067 pair<int, string> p =
1068 addDepth(depth, ltype_depth);
1070 currlinelen = p.first;
1077 return buffer.str();
1081 void Buffer::writeFileAscii(string const & fname, int linelen)
1084 if (!::openFileWrite(ofs, fname))
1086 writeFileAscii(ofs, linelen);
1090 void Buffer::writeFileAscii(ostream & os, int linelen)
1092 ParagraphList::iterator beg = paragraphs().begin();
1093 ParagraphList::iterator end = paragraphs().end();
1094 ParagraphList::iterator it = beg;
1095 for (; it != end; ++it) {
1096 os << asciiParagraph(*it, linelen, it == beg);
1102 void Buffer::makeLaTeXFile(string const & fname,
1103 string const & original_path,
1104 LatexRunParams const & runparams,
1105 bool output_preamble, bool output_body)
1107 lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1110 if (!::openFileWrite(ofs, fname))
1113 makeLaTeXFile(ofs, original_path,
1114 runparams, output_preamble, output_body);
1118 lyxerr << "File was not closed properly." << endl;
1123 void Buffer::makeLaTeXFile(ostream & os,
1124 string const & original_path,
1125 LatexRunParams const & runparams_in,
1126 bool output_preamble, bool output_body)
1128 LatexRunParams runparams = runparams_in;
1129 niceFile() = runparams.nice; // this will be used by Insetincludes.
1131 // validate the buffer.
1132 lyxerr[Debug::LATEX] << " Validating buffer..." << endl;
1133 LaTeXFeatures features(*this, params());
1135 lyxerr[Debug::LATEX] << " Buffer validation done." << endl;
1138 // The starting paragraph of the coming rows is the
1139 // first paragraph of the document. (Asger)
1140 texrow().start(paragraphs().begin()->id(), 0);
1142 if (output_preamble && runparams.nice) {
1143 os << "%% LyX " << lyx_version << " created this file. "
1144 "For more info, see http://www.lyx.org/.\n"
1145 "%% Do not edit unless you really know what "
1150 lyxerr[Debug::INFO] << "lyx header finished" << endl;
1151 // There are a few differences between nice LaTeX and usual files:
1152 // usual is \batchmode and has a
1153 // special input@path to allow the including of figures
1154 // with either \input or \includegraphics (what figinsets do).
1155 // input@path is set when the actual parameter
1156 // original_path is set. This is done for usual tex-file, but not
1157 // for nice-latex-file. (Matthias 250696)
1158 if (output_preamble) {
1159 if (!runparams.nice) {
1160 // code for usual, NOT nice-latex-file
1161 os << "\\batchmode\n"; // changed
1162 // from \nonstopmode
1165 if (!original_path.empty()) {
1166 string inputpath = os::external_path(original_path);
1167 subst(inputpath, "~", "\\string~");
1168 os << "\\makeatletter\n"
1169 << "\\def\\input@path{{"
1170 << inputpath << "/}}\n"
1171 << "\\makeatother\n";
1177 // Write the preamble
1178 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1184 os << "\\begin{document}\n";
1186 } // output_preamble
1187 lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1189 if (!lyxrc.language_auto_begin) {
1190 os << subst(lyxrc.language_command_begin, "$$lang",
1191 params().language->babel())
1196 latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1198 // add this just in case after all the paragraphs
1202 if (!lyxrc.language_auto_end) {
1203 os << subst(lyxrc.language_command_end, "$$lang",
1204 params().language->babel())
1209 if (output_preamble) {
1210 os << "\\end{document}\n";
1213 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1215 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1219 // Just to be sure. (Asger)
1222 lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1223 lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1226 // we want this to be true outside previews (for insetexternal)
1231 bool Buffer::isLatex() const
1233 return params().getLyXTextClass().outputType() == LATEX;
1237 bool Buffer::isLinuxDoc() const
1239 return params().getLyXTextClass().outputType() == LINUXDOC;
1243 bool Buffer::isLiterate() const
1245 return params().getLyXTextClass().outputType() == LITERATE;
1249 bool Buffer::isDocBook() const
1251 return params().getLyXTextClass().outputType() == DOCBOOK;
1255 bool Buffer::isSGML() const
1257 LyXTextClass const & tclass = params().getLyXTextClass();
1259 return tclass.outputType() == LINUXDOC ||
1260 tclass.outputType() == DOCBOOK;
1264 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1267 if (!::openFileWrite(ofs, fname))
1270 niceFile() = nice; // this will be used by included files.
1272 LaTeXFeatures features(*this, params());
1278 LyXTextClass const & tclass = params().getLyXTextClass();
1280 string top_element = tclass.latexname();
1283 ofs << "<!doctype linuxdoc system";
1285 string preamble = params().preamble;
1286 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1288 preamble += features.getIncludedFiles(name);
1289 preamble += features.getLyXSGMLEntities();
1291 if (!preamble.empty()) {
1292 ofs << " [ " << preamble << " ]";
1296 if (params().options.empty())
1297 sgml::openTag(ofs, 0, false, top_element);
1299 string top = top_element;
1301 top += params().options;
1302 sgml::openTag(ofs, 0, false, top);
1306 ofs << "<!-- LyX " << lyx_version
1307 << " created this file. For more info see http://www.lyx.org/"
1310 linuxdocParagraphs(*this, paragraphs(), ofs);
1314 sgml::closeTag(ofs, 0, false, top_element);
1318 // How to check for successful close
1320 // we want this to be true outside previews (for insetexternal)
1325 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1328 if (!::openFileWrite(ofs, fname))
1331 niceFile() = nice; // this will be used by Insetincludes.
1333 LaTeXFeatures features(*this, params());
1338 LyXTextClass const & tclass = params().getLyXTextClass();
1339 string top_element = tclass.latexname();
1342 ofs << "<!DOCTYPE " << top_element
1343 << " PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1345 string preamble = params().preamble;
1346 string const name = nice ? ChangeExtension(pimpl_->filename, ".sgml")
1348 preamble += features.getIncludedFiles(name);
1349 preamble += features.getLyXSGMLEntities();
1351 if (!preamble.empty()) {
1352 ofs << "\n [ " << preamble << " ]";
1357 string top = top_element;
1359 top += params().language->code();
1362 if (!params().options.empty()) {
1364 top += params().options;
1366 sgml::openTag(ofs, 0, false, top);
1368 ofs << "<!-- DocBook file was created by LyX " << lyx_version
1369 << "\n See http://www.lyx.org/ for more information -->\n";
1371 docbookParagraphs(*this, paragraphs(), ofs);
1374 sgml::closeTag(ofs, 0, false, top_element);
1377 // How to check for successful close
1379 // we want this to be true outside previews (for insetexternal)
1384 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1385 // Other flags: -wall -v0 -x
1386 int Buffer::runChktex()
1390 // get LaTeX-Filename
1391 string const name = getLatexName();
1392 string path = filePath();
1394 string const org_path = path;
1395 if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1399 Path p(path); // path to LaTeX file
1400 message(_("Running chktex..."));
1402 // Generate the LaTeX file if neccessary
1403 LatexRunParams runparams;
1404 runparams.flavor = LatexRunParams::LATEX;
1405 runparams.nice = false;
1406 makeLaTeXFile(name, org_path, runparams);
1409 Chktex chktex(lyxrc.chktex_command, name, filePath());
1410 int res = chktex.run(terr); // run chktex
1413 Alert::error(_("chktex failure"),
1414 _("Could not run chktex successfully."));
1415 } else if (res > 0) {
1416 // Insert all errors as errors boxes
1417 bufferErrors(*this, terr);
1426 void Buffer::validate(LaTeXFeatures & features) const
1428 LyXTextClass const & tclass = params().getLyXTextClass();
1430 if (params().tracking_changes) {
1431 features.require("dvipost");
1432 features.require("color");
1435 // AMS Style is at document level
1436 if (params().use_amsmath == BufferParams::AMS_ON
1437 || tclass.provides(LyXTextClass::amsmath))
1438 features.require("amsmath");
1440 for_each(paragraphs().begin(), paragraphs().end(),
1441 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1443 // the bullet shapes are buffer level not paragraph level
1444 // so they are tested here
1445 for (int i = 0; i < 4; ++i) {
1446 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1447 int const font = params().user_defined_bullet(i).getFont();
1449 int const c = params()
1450 .user_defined_bullet(i)
1457 features.require("latexsym");
1459 } else if (font == 1) {
1460 features.require("amssymb");
1461 } else if ((font >= 2 && font <= 5)) {
1462 features.require("pifont");
1467 if (lyxerr.debugging(Debug::LATEX)) {
1468 features.showStruct();
1473 void Buffer::getLabelList(std::vector<string> & list) const
1475 /// if this is a child document and the parent is already loaded
1476 /// Use the parent's list instead [ale990407]
1477 if (!params().parentname.empty()
1478 && bufferlist.exists(params().parentname)) {
1479 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1481 tmp->getLabelList(list);
1486 for (inset_iterator it = inset_const_iterator_begin();
1487 it != inset_const_iterator_end(); ++it) {
1488 it->getLabelList(*this, list);
1493 // This is also a buffer property (ale)
1494 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1496 /// if this is a child document and the parent is already loaded
1497 /// use the parent's list instead [ale990412]
1498 if (!params().parentname.empty() &&
1499 bufferlist.exists(params().parentname)) {
1500 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1502 tmp->fillWithBibKeys(keys);
1507 for (inset_iterator it = inset_const_iterator_begin();
1508 it != inset_const_iterator_end(); ++it) {
1509 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1510 InsetBibtex const & inset =
1511 dynamic_cast<InsetBibtex const &>(*it);
1512 inset.fillWithBibKeys(*this, keys);
1513 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1514 InsetInclude const & inset =
1515 dynamic_cast<InsetInclude const &>(*it);
1516 inset.fillWithBibKeys(*this, keys);
1517 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1518 InsetBibitem const & inset =
1519 dynamic_cast<InsetBibitem const &>(*it);
1520 string const key = inset.getContents();
1521 string const opt = inset.getOptions();
1522 string const ref; // = pit->asString(this, false);
1523 string const info = opt + "TheBibliographyRef" + ref;
1524 keys.push_back(pair<string, string>(key, info));
1530 bool Buffer::isDepClean(string const & name) const
1532 DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1533 if (it == pimpl_->dep_clean.end())
1539 void Buffer::markDepClean(string const & name)
1541 pimpl_->dep_clean[name] = true;
1545 bool Buffer::dispatch(string const & command, bool * result)
1547 return dispatch(lyxaction.lookupFunc(command), result);
1551 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1553 bool dispatched = true;
1555 switch (func.action) {
1557 bool const tmp = Exporter::Export(this, func.argument, false);
1570 void Buffer::changeLanguage(Language const * from, Language const * to)
1572 lyxerr << "Changing Language!" << endl;
1574 // Take care of l10n/i18n
1577 ParIterator end = par_iterator_end();
1578 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1579 it->changeLanguage(params(), from, to);
1583 void Buffer::updateDocLang(Language const * nlang)
1585 pimpl_->messages.reset(new Messages(nlang->code()));
1589 bool Buffer::isMultiLingual()
1591 ParIterator end = par_iterator_end();
1592 for (ParIterator it = par_iterator_begin(); it != end; ++it)
1593 if (it->isMultiLingual(params()))
1600 void Buffer::inset_iterator::setParagraph()
1602 while (pit != pend) {
1603 it = pit->insetlist.begin();
1604 if (it != pit->insetlist.end())
1611 InsetOld * Buffer::getInsetFromID(int id_arg) const
1613 for (inset_iterator it = inset_const_iterator_begin();
1614 it != inset_const_iterator_end(); ++it)
1616 if (it->id() == id_arg)
1618 InsetOld * in = it->getInsetFromID(id_arg);
1626 ParIterator Buffer::getParFromID(int id) const
1628 #warning FIXME: const correctness! (Andre)
1629 ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1630 ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1632 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1634 // John says this is called with id == -1 from undo
1635 lyxerr << "getParFromID(), id: " << id << endl;
1639 for (; it != end; ++it)
1647 bool Buffer::hasParWithID(int id) const
1649 ParConstIterator it = par_iterator_begin();
1650 ParConstIterator end = par_iterator_end();
1653 // John says this is called with id == -1 from undo
1654 lyxerr << "hasParWithID(), id: " << id << endl;
1658 for (; it != end; ++it)
1666 ParIterator Buffer::par_iterator_begin()
1668 return ParIterator(paragraphs().begin(), paragraphs());
1672 ParIterator Buffer::par_iterator_end()
1674 return ParIterator(paragraphs().end(), paragraphs());
1678 ParConstIterator Buffer::par_iterator_begin() const
1680 ParagraphList const & pars = paragraphs();
1681 return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1685 ParConstIterator Buffer::par_iterator_end() const
1687 ParagraphList const & pars = paragraphs();
1688 return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1692 Language const * Buffer::getLanguage() const
1694 return params().language;
1698 string const Buffer::B_(string const & l10n) const
1700 if (pimpl_->messages.get()) {
1701 return pimpl_->messages->get(l10n);
1708 bool Buffer::isClean() const
1710 return pimpl_->lyx_clean;
1714 bool Buffer::isBakClean() const
1716 return pimpl_->bak_clean;
1720 void Buffer::markClean() const
1722 if (!pimpl_->lyx_clean) {
1723 pimpl_->lyx_clean = true;
1726 // if the .lyx file has been saved, we don't need an
1728 pimpl_->bak_clean = true;
1732 void Buffer::markBakClean()
1734 pimpl_->bak_clean = true;
1738 void Buffer::setUnnamed(bool flag)
1740 pimpl_->unnamed = flag;
1744 bool Buffer::isUnnamed()
1746 return pimpl_->unnamed;
1750 void Buffer::markDirty()
1752 if (pimpl_->lyx_clean) {
1753 pimpl_->lyx_clean = false;
1756 pimpl_->bak_clean = false;
1758 DepClean::iterator it = pimpl_->dep_clean.begin();
1759 DepClean::const_iterator const end = pimpl_->dep_clean.end();
1761 for (; it != end; ++it) {
1767 string const & Buffer::fileName() const
1769 return pimpl_->filename;
1773 string const & Buffer::filePath() const
1775 return pimpl_->filepath;
1779 bool Buffer::isReadonly() const
1781 return pimpl_->read_only;
1785 void Buffer::setParentName(string const & name)
1787 params().parentname = name;
1791 Buffer::inset_iterator::inset_iterator()
1796 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1803 Buffer::inset_iterator Buffer::inset_iterator_begin()
1805 return inset_iterator(paragraphs().begin(), paragraphs().end());
1809 Buffer::inset_iterator Buffer::inset_iterator_end()
1811 return inset_iterator(paragraphs().end(), paragraphs().end());
1815 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1817 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1818 return inset_iterator(pars.begin(), pars.end());
1822 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1824 ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1825 return inset_iterator(pars.end(), pars.end());
1829 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1833 if (it == pit->insetlist.end()) {
1842 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1844 inset_iterator tmp = *this;
1850 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1856 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1862 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1868 lyx::pos_type Buffer::inset_iterator::getPos() const
1874 bool operator==(Buffer::inset_iterator const & iter1,
1875 Buffer::inset_iterator const & iter2)
1877 return iter1.pit == iter2.pit
1878 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1882 bool operator!=(Buffer::inset_iterator const & iter1,
1883 Buffer::inset_iterator const & iter2)
1885 return !(iter1 == iter2);