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
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_plaintext.h"
51 #include "paragraph_funcs.h"
52 #include "Paragraph.h"
53 #include "ParagraphParameters.h"
54 #include "ParIterator.h"
55 #include "PDFOptions.h"
56 #include "SpellChecker.h"
59 #include "TexStream.h"
61 #include "TextClass.h"
62 #include "TocBackend.h"
64 #include "VCBackend.h"
66 #include "WordLangTuple.h"
69 #include "insets/InsetBibitem.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetInclude.h"
72 #include "insets/InsetText.h"
74 #include "mathed/MacroTable.h"
75 #include "mathed/MathMacroTemplate.h"
76 #include "mathed/MathSupport.h"
78 #include "frontends/alert.h"
79 #include "frontends/Delegates.h"
80 #include "frontends/WorkAreaManager.h"
82 #include "graphics/Previews.h"
84 #include "support/lassert.h"
85 #include "support/convert.h"
86 #include "support/debug.h"
87 #include "support/docstring_list.h"
88 #include "support/ExceptionMessage.h"
89 #include "support/FileName.h"
90 #include "support/FileNameList.h"
91 #include "support/filetools.h"
92 #include "support/ForkedCalls.h"
93 #include "support/gettext.h"
94 #include "support/gzstream.h"
95 #include "support/lstrings.h"
96 #include "support/lyxalgo.h"
97 #include "support/os.h"
98 #include "support/Package.h"
99 #include "support/Path.h"
100 #include "support/Systemcall.h"
101 #include "support/textutils.h"
102 #include "support/types.h"
104 #include <boost/bind.hpp>
105 #include <boost/shared_ptr.hpp>
117 using namespace lyx::support;
121 namespace Alert = frontend::Alert;
122 namespace os = support::os;
126 // Do not remove the comment below, so we get merge conflict in
127 // independent branches. Instead add your own.
128 int const LYX_FORMAT = 354; // jspitzm: support for \print[sub]index*
130 typedef map<string, bool> DepClean;
131 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
133 void showPrintError(string const & name)
135 docstring str = bformat(_("Could not print the document %1$s.\n"
136 "Check that your printer is set up correctly."),
137 makeDisplayPath(name, 50));
138 Alert::error(_("Print document failed"), str);
143 class BufferSet : public std::set<Buffer const *> {};
148 Impl(Buffer & parent, FileName const & file, bool readonly);
162 mutable TexRow texrow;
164 /// need to regenerate .tex?
168 mutable bool lyx_clean;
170 /// is autosave needed?
171 mutable bool bak_clean;
173 /// is this a unnamed file (New...)?
179 /// name of the file the buffer is associated with.
182 /** Set to true only when the file is fully loaded.
183 * Used to prevent the premature generation of previews
184 * and by the citation inset.
186 bool file_fully_loaded;
189 mutable TocBackend toc_backend;
192 typedef pair<DocIterator, MacroData> ScopeMacro;
193 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
194 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
195 /// map from the macro name to the position map,
196 /// which maps the macro definition position to the scope and the MacroData.
197 NamePositionScopeMacroMap macros;
200 /// positions of child buffers in the buffer
201 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
202 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
203 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
204 /// position of children buffers in this buffer
205 BufferPositionMap children_positions;
206 /// map from children inclusion positions to their scope and their buffer
207 PositionScopeBufferMap position_to_children;
209 /// Container for all sort of Buffer dependant errors.
210 map<string, ErrorList> errorLists;
212 /// timestamp and checksum used to test if the file has been externally
213 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
215 unsigned long checksum_;
218 frontend::WorkAreaManager * wa_;
223 /// A cache for the bibfiles (including bibfiles of loaded child
224 /// documents), needed for appropriate update of natbib labels.
225 mutable support::FileNameList bibfilesCache_;
227 // FIXME The caching mechanism could be improved. At present, we have a
228 // cache for each Buffer, that caches all the bibliography info for that
229 // Buffer. A more efficient solution would be to have a global cache per
230 // file, and then to construct the Buffer's bibinfo from that.
231 /// A cache for bibliography info
232 mutable BiblioInfo bibinfo_;
233 /// whether the bibinfo cache is valid
234 bool bibinfoCacheValid_;
235 /// Cache of timestamps of .bib files
236 map<FileName, time_t> bibfileStatus_;
238 mutable RefCache ref_cache_;
240 /// our Text that should be wrapped in an InsetText
243 /// This is here to force the test to be done whenever parent_buffer
245 Buffer const * parent() const {
246 // if parent_buffer is not loaded, then it has been unloaded,
247 // which means that parent_buffer is an invalid pointer. So we
248 // set it to null in that case.
249 if (!theBufferList().isLoaded(parent_buffer))
251 return parent_buffer;
254 void setParent(Buffer const * pb) { parent_buffer = pb; }
256 /// So we can force access via the accessors.
257 mutable Buffer const * parent_buffer;
261 /// Creates the per buffer temporary directory
262 static FileName createBufferTmpDir()
265 // We are in our own directory. Why bother to mangle name?
266 // In fact I wrote this code to circumvent a problematic behaviour
267 // (bug?) of EMX mkstemp().
268 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
269 convert<string>(count++));
271 if (!tmpfl.createDirectory(0777)) {
272 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
273 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
274 from_utf8(tmpfl.absFilename())));
280 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
281 : lyx_clean(true), bak_clean(true), unnamed(false),
282 read_only(readonly_), filename(file), file_fully_loaded(false),
283 toc_backend(&parent), macro_lock(false), timestamp_(0),
284 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
287 temppath = createBufferTmpDir();
288 lyxvc.setBuffer(&parent);
290 wa_ = new frontend::WorkAreaManager;
294 Buffer::Buffer(string const & file, bool readonly)
295 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
297 LYXERR(Debug::INFO, "Buffer::Buffer()");
299 d->inset = new InsetText(*this);
300 d->inset->setAutoBreakRows(true);
301 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
307 LYXERR(Debug::INFO, "Buffer::~Buffer()");
308 // here the buffer should take care that it is
309 // saved properly, before it goes into the void.
311 // GuiView already destroyed
314 if (d->unnamed && d->filename.extension() == "internal") {
315 // No need to do additional cleanups for internal buffer.
320 // loop over children
321 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
322 Impl::BufferPositionMap::iterator end = d->children_positions.end();
323 for (; it != end; ++it) {
324 Buffer * child = const_cast<Buffer *>(it->first);
325 // The child buffer might have been closed already.
326 if (theBufferList().isLoaded(child))
327 theBufferList().releaseChild(this, child);
330 // clear references to children in macro tables
331 d->children_positions.clear();
332 d->position_to_children.clear();
334 if (!d->temppath.destroyDirectory()) {
335 Alert::warning(_("Could not remove temporary directory"),
336 bformat(_("Could not remove the temporary directory %1$s"),
337 from_utf8(d->temppath.absFilename())));
340 // Remove any previewed LaTeX snippets associated with this buffer.
341 thePreviews().removeLoader(*this);
347 void Buffer::changed() const
354 frontend::WorkAreaManager & Buffer::workAreaManager() const
356 LASSERT(d->wa_, /**/);
361 Text & Buffer::text() const
363 return d->inset->text();
367 Inset & Buffer::inset() const
373 BufferParams & Buffer::params()
379 BufferParams const & Buffer::params() const
385 ParagraphList & Buffer::paragraphs()
387 return text().paragraphs();
391 ParagraphList const & Buffer::paragraphs() const
393 return text().paragraphs();
397 LyXVC & Buffer::lyxvc()
403 LyXVC const & Buffer::lyxvc() const
409 string const Buffer::temppath() const
411 return d->temppath.absFilename();
415 TexRow & Buffer::texrow()
421 TexRow const & Buffer::texrow() const
427 TocBackend & Buffer::tocBackend() const
429 return d->toc_backend;
433 Undo & Buffer::undo()
439 string Buffer::latexName(bool const no_path) const
441 FileName latex_name = makeLatexName(d->filename);
442 return no_path ? latex_name.onlyFileName()
443 : latex_name.absFilename();
447 string Buffer::logName(LogType * type) const
449 string const filename = latexName(false);
451 if (filename.empty()) {
457 string const path = temppath();
459 FileName const fname(addName(temppath(),
460 onlyFilename(changeExtension(filename,
462 FileName const bname(
463 addName(path, onlyFilename(
464 changeExtension(filename,
465 formats.extension("literate") + ".out"))));
467 // If no Latex log or Build log is newer, show Build log
469 if (bname.exists() &&
470 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
471 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
474 return bname.absFilename();
476 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
479 return fname.absFilename();
483 void Buffer::setReadonly(bool const flag)
485 if (d->read_only != flag) {
492 void Buffer::setFileName(string const & newfile)
494 d->filename = makeAbsPath(newfile);
495 setReadonly(d->filename.isReadOnly());
500 int Buffer::readHeader(Lexer & lex)
502 int unknown_tokens = 0;
504 int begin_header_line = -1;
506 // Initialize parameters that may be/go lacking in header:
507 params().branchlist().clear();
508 params().preamble.erase();
509 params().options.erase();
510 params().master.erase();
511 params().float_placement.erase();
512 params().paperwidth.erase();
513 params().paperheight.erase();
514 params().leftmargin.erase();
515 params().rightmargin.erase();
516 params().topmargin.erase();
517 params().bottommargin.erase();
518 params().headheight.erase();
519 params().headsep.erase();
520 params().footskip.erase();
521 params().columnsep.erase();
522 params().fontsCJK.erase();
523 params().listings_params.clear();
524 params().clearLayoutModules();
525 params().clearRemovedModules();
526 params().pdfoptions().clear();
527 params().indiceslist().clear();
529 for (int i = 0; i < 4; ++i) {
530 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
531 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
534 ErrorList & errorList = d->errorLists["Parse"];
543 if (token == "\\end_header")
547 if (token == "\\begin_header") {
548 begin_header_line = line;
552 LYXERR(Debug::PARSER, "Handling document header token: `"
555 string unknown = params().readToken(lex, token, d->filename.onlyPath());
556 if (!unknown.empty()) {
557 if (unknown[0] != '\\' && token == "\\textclass") {
558 Alert::warning(_("Unknown document class"),
559 bformat(_("Using the default document class, because the "
560 "class %1$s is unknown."), from_utf8(unknown)));
563 docstring const s = bformat(_("Unknown token: "
567 errorList.push_back(ErrorItem(_("Document header error"),
572 if (begin_header_line) {
573 docstring const s = _("\\begin_header is missing");
574 errorList.push_back(ErrorItem(_("Document header error"),
578 params().makeDocumentClass();
580 return unknown_tokens;
585 // changed to be public and have one parameter
586 // Returns true if "\end_document" is not read (Asger)
587 bool Buffer::readDocument(Lexer & lex)
589 ErrorList & errorList = d->errorLists["Parse"];
592 if (!lex.checkFor("\\begin_document")) {
593 docstring const s = _("\\begin_document is missing");
594 errorList.push_back(ErrorItem(_("Document header error"),
598 // we are reading in a brand new document
599 LASSERT(paragraphs().empty(), /**/);
603 if (params().outputChanges) {
604 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
605 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
606 LaTeXFeatures::isAvailable("xcolor");
608 if (!dvipost && !xcolorulem) {
609 Alert::warning(_("Changes not shown in LaTeX output"),
610 _("Changes will not be highlighted in LaTeX output, "
611 "because neither dvipost nor xcolor/ulem are installed.\n"
612 "Please install these packages or redefine "
613 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
614 } else if (!xcolorulem) {
615 Alert::warning(_("Changes not shown in LaTeX output"),
616 _("Changes will not be highlighted in LaTeX output "
617 "when using pdflatex, because xcolor and ulem are not installed.\n"
618 "Please install both packages or redefine "
619 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
623 if (!params().master.empty()) {
624 FileName const master_file = makeAbsPath(params().master,
625 onlyPath(absFileName()));
626 if (isLyXFilename(master_file.absFilename())) {
628 checkAndLoadLyXFile(master_file, true);
630 // necessary e.g. after a reload
631 // to re-register the child (bug 5873)
632 // FIXME: clean up updateMacros (here, only
633 // child registering is needed).
634 master->updateMacros();
635 // set master as master buffer, but only
636 // if we are a real child
637 if (master->isChild(this))
639 // if the master is not fully loaded
640 // it is probably just loading this
641 // child. No warning needed then.
642 else if (master->isFullyLoaded())
643 LYXERR0("The master '"
645 << "' assigned to this document ("
647 << ") does not include "
648 "this document. Ignoring the master assignment.");
654 bool const res = text().read(*this, lex, errorList, d->inset);
657 updateMacroInstances();
662 // needed to insert the selection
663 void Buffer::insertStringAsLines(ParagraphList & pars,
664 pit_type & pit, pos_type & pos,
665 Font const & fn, docstring const & str, bool autobreakrows)
669 // insert the string, don't insert doublespace
670 bool space_inserted = true;
671 for (docstring::const_iterator cit = str.begin();
672 cit != str.end(); ++cit) {
673 Paragraph & par = pars[pit];
675 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
676 breakParagraph(params(), pars, pit, pos,
677 par.layout().isEnvironment());
680 space_inserted = true;
684 // do not insert consecutive spaces if !free_spacing
685 } else if ((*cit == ' ' || *cit == '\t') &&
686 space_inserted && !par.isFreeSpacing()) {
688 } else if (*cit == '\t') {
689 if (!par.isFreeSpacing()) {
690 // tabs are like spaces here
691 par.insertChar(pos, ' ', font, params().trackChanges);
693 space_inserted = true;
695 par.insertChar(pos, *cit, font, params().trackChanges);
697 space_inserted = true;
699 } else if (!isPrintable(*cit)) {
700 // Ignore unprintables
703 // just insert the character
704 par.insertChar(pos, *cit, font, params().trackChanges);
706 space_inserted = (*cit == ' ');
713 bool Buffer::readString(string const & s)
715 params().compressed = false;
717 // remove dummy empty par
718 paragraphs().clear();
722 FileName const name = FileName::tempName("Buffer_readString");
723 switch (readFile(lex, name, true)) {
727 // We need to call lyx2lyx, so write the input to a file
728 ofstream os(name.toFilesystemEncoding().c_str());
731 return readFile(name);
741 bool Buffer::readFile(FileName const & filename)
743 FileName fname(filename);
745 params().compressed = fname.isZippedFile();
747 // remove dummy empty par
748 paragraphs().clear();
751 if (readFile(lex, fname) != success)
758 bool Buffer::isFullyLoaded() const
760 return d->file_fully_loaded;
764 void Buffer::setFullyLoaded(bool value)
766 d->file_fully_loaded = value;
770 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
773 LASSERT(!filename.empty(), /**/);
775 // the first (non-comment) token _must_ be...
776 if (!lex.checkFor("\\lyxformat")) {
777 Alert::error(_("Document format failure"),
778 bformat(_("%1$s is not a readable LyX document."),
779 from_utf8(filename.absFilename())));
785 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
786 // if present remove ".," from string.
787 size_t dot = tmp_format.find_first_of(".,");
788 //lyxerr << " dot found at " << dot << endl;
789 if (dot != string::npos)
790 tmp_format.erase(dot, 1);
791 int const file_format = convert<int>(tmp_format);
792 //lyxerr << "format: " << file_format << endl;
794 // save timestamp and checksum of the original disk file, making sure
795 // to not overwrite them with those of the file created in the tempdir
796 // when it has to be converted to the current format.
798 // Save the timestamp and checksum of disk file. If filename is an
799 // emergency file, save the timestamp and checksum of the original lyx file
800 // because isExternallyModified will check for this file. (BUG4193)
801 string diskfile = filename.absFilename();
802 if (suffixIs(diskfile, ".emergency"))
803 diskfile = diskfile.substr(0, diskfile.size() - 10);
804 saveCheckSum(FileName(diskfile));
807 if (file_format != LYX_FORMAT) {
810 // lyx2lyx would fail
813 FileName const tmpfile = FileName::tempName("Buffer_readFile");
814 if (tmpfile.empty()) {
815 Alert::error(_("Conversion failed"),
816 bformat(_("%1$s is from a different"
817 " version of LyX, but a temporary"
818 " file for converting it could"
820 from_utf8(filename.absFilename())));
823 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
824 if (lyx2lyx.empty()) {
825 Alert::error(_("Conversion script not found"),
826 bformat(_("%1$s is from a different"
827 " version of LyX, but the"
828 " conversion script lyx2lyx"
829 " could not be found."),
830 from_utf8(filename.absFilename())));
833 ostringstream command;
834 command << os::python()
835 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
836 << " -t " << convert<string>(LYX_FORMAT)
837 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
838 << ' ' << quoteName(filename.toFilesystemEncoding());
839 string const command_str = command.str();
841 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
843 cmd_ret const ret = runCommand(command_str);
844 if (ret.first != 0) {
845 Alert::error(_("Conversion script failed"),
846 bformat(_("%1$s is from a different version"
847 " of LyX, but the lyx2lyx script"
848 " failed to convert it."),
849 from_utf8(filename.absFilename())));
852 bool const ret = readFile(tmpfile);
853 // Do stuff with tmpfile name and buffer name here.
854 return ret ? success : failure;
859 if (readDocument(lex)) {
860 Alert::error(_("Document format failure"),
861 bformat(_("%1$s ended unexpectedly, which means"
862 " that it is probably corrupted."),
863 from_utf8(filename.absFilename())));
866 d->file_fully_loaded = true;
871 // Should probably be moved to somewhere else: BufferView? LyXView?
872 bool Buffer::save() const
874 // We don't need autosaves in the immediate future. (Asger)
875 resetAutosaveTimers();
877 string const encodedFilename = d->filename.toFilesystemEncoding();
880 bool madeBackup = false;
882 // make a backup if the file already exists
883 if (lyxrc.make_backup && fileName().exists()) {
884 backupName = FileName(absFileName() + '~');
885 if (!lyxrc.backupdir_path.empty()) {
886 string const mangledName =
887 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
888 backupName = FileName(addName(lyxrc.backupdir_path,
891 if (fileName().copyTo(backupName)) {
894 Alert::error(_("Backup failure"),
895 bformat(_("Cannot create backup file %1$s.\n"
896 "Please check whether the directory exists and is writeable."),
897 from_utf8(backupName.absFilename())));
898 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
902 // ask if the disk file has been externally modified (use checksum method)
903 if (fileName().exists() && isExternallyModified(checksum_method)) {
904 docstring const file = makeDisplayPath(absFileName(), 20);
905 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
906 "you want to overwrite this file?"), file);
907 int const ret = Alert::prompt(_("Overwrite modified file?"),
908 text, 1, 1, _("&Overwrite"), _("&Cancel"));
913 if (writeFile(d->filename)) {
917 // Saving failed, so backup is not backup
919 backupName.moveTo(d->filename);
925 bool Buffer::writeFile(FileName const & fname) const
927 if (d->read_only && fname == d->filename)
932 docstring const str = bformat(_("Saving document %1$s..."),
933 makeDisplayPath(fname.absFilename()));
936 if (params().compressed) {
937 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
938 retval = ofs && write(ofs);
940 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
941 retval = ofs && write(ofs);
945 message(str + _(" could not write file!"));
949 removeAutosaveFile();
951 saveCheckSum(d->filename);
952 message(str + _(" done."));
958 bool Buffer::write(ostream & ofs) const
961 // Use the standard "C" locale for file output.
962 ofs.imbue(locale::classic());
965 // The top of the file should not be written by params().
967 // write out a comment in the top of the file
968 ofs << "#LyX " << lyx_version
969 << " created this file. For more info see http://www.lyx.org/\n"
970 << "\\lyxformat " << LYX_FORMAT << "\n"
971 << "\\begin_document\n";
973 /// For each author, set 'used' to true if there is a change
974 /// by this author in the document; otherwise set it to 'false'.
975 AuthorList::Authors::const_iterator a_it = params().authors().begin();
976 AuthorList::Authors::const_iterator a_end = params().authors().end();
977 for (; a_it != a_end; ++a_it)
978 a_it->second.setUsed(false);
980 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
981 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
982 for ( ; it != end; ++it)
983 it->checkAuthors(params().authors());
985 // now write out the buffer parameters.
986 ofs << "\\begin_header\n";
987 params().writeFile(ofs);
988 ofs << "\\end_header\n";
991 ofs << "\n\\begin_body\n";
992 text().write(*this, ofs);
993 ofs << "\n\\end_body\n";
995 // Write marker that shows file is complete
996 ofs << "\\end_document" << endl;
998 // Shouldn't really be needed....
1001 // how to check if close went ok?
1002 // Following is an attempt... (BE 20001011)
1004 // good() returns false if any error occured, including some
1005 // formatting error.
1006 // bad() returns true if something bad happened in the buffer,
1007 // which should include file system full errors.
1012 lyxerr << "File was not closed properly." << endl;
1019 bool Buffer::makeLaTeXFile(FileName const & fname,
1020 string const & original_path,
1021 OutputParams const & runparams_in,
1022 bool output_preamble, bool output_body) const
1024 OutputParams runparams = runparams_in;
1025 if (params().useXetex)
1026 runparams.flavor = OutputParams::XETEX;
1028 string const encoding = runparams.encoding->iconvName();
1029 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1032 try { ofs.reset(encoding); }
1033 catch (iconv_codecvt_facet_exception & e) {
1034 lyxerr << "Caught iconv exception: " << e.what() << endl;
1035 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1036 "verify that the support software for your encoding (%1$s) is "
1037 "properly installed"), from_ascii(encoding)));
1040 if (!openFileWrite(ofs, fname))
1043 //TexStream ts(ofs.rdbuf(), &texrow());
1044 ErrorList & errorList = d->errorLists["Export"];
1046 bool failed_export = false;
1049 writeLaTeXSource(ofs, original_path,
1050 runparams, output_preamble, output_body);
1052 catch (EncodingException & e) {
1053 odocstringstream ods;
1054 ods.put(e.failed_char);
1056 oss << "0x" << hex << e.failed_char << dec;
1057 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1058 " (code point %2$s)"),
1059 ods.str(), from_utf8(oss.str()));
1060 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1061 "representable in the chosen encoding.\n"
1062 "Changing the document encoding to utf8 could help."),
1063 e.par_id, e.pos, e.pos + 1));
1064 failed_export = true;
1066 catch (iconv_codecvt_facet_exception & e) {
1067 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1068 _(e.what()), -1, 0, 0));
1069 failed_export = true;
1071 catch (exception const & e) {
1072 errorList.push_back(ErrorItem(_("conversion failed"),
1073 _(e.what()), -1, 0, 0));
1074 failed_export = true;
1077 lyxerr << "Caught some really weird exception..." << endl;
1083 failed_export = true;
1084 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1088 return !failed_export;
1092 void Buffer::writeLaTeXSource(odocstream & os,
1093 string const & original_path,
1094 OutputParams const & runparams_in,
1095 bool const output_preamble, bool const output_body) const
1097 // The child documents, if any, shall be already loaded at this point.
1099 OutputParams runparams = runparams_in;
1101 // Classify the unicode characters appearing in math insets
1102 Encodings::initUnicodeMath(*this);
1104 // validate the buffer.
1105 LYXERR(Debug::LATEX, " Validating buffer...");
1106 LaTeXFeatures features(*this, params(), runparams);
1108 LYXERR(Debug::LATEX, " Buffer validation done.");
1110 // The starting paragraph of the coming rows is the
1111 // first paragraph of the document. (Asger)
1112 if (output_preamble && runparams.nice) {
1113 os << "%% LyX " << lyx_version << " created this file. "
1114 "For more info, see http://www.lyx.org/.\n"
1115 "%% Do not edit unless you really know what "
1117 d->texrow.newline();
1118 d->texrow.newline();
1120 LYXERR(Debug::INFO, "lyx document header finished");
1122 // Don't move this behind the parent_buffer=0 code below,
1123 // because then the macros will not get the right "redefinition"
1124 // flag as they don't see the parent macros which are output before.
1127 // fold macros if possible, still with parent buffer as the
1128 // macros will be put in the prefix anyway.
1129 updateMacroInstances();
1131 // There are a few differences between nice LaTeX and usual files:
1132 // usual is \batchmode and has a
1133 // special input@path to allow the including of figures
1134 // with either \input or \includegraphics (what figinsets do).
1135 // input@path is set when the actual parameter
1136 // original_path is set. This is done for usual tex-file, but not
1137 // for nice-latex-file. (Matthias 250696)
1138 // Note that input@path is only needed for something the user does
1139 // in the preamble, included .tex files or ERT, files included by
1140 // LyX work without it.
1141 if (output_preamble) {
1142 if (!runparams.nice) {
1143 // code for usual, NOT nice-latex-file
1144 os << "\\batchmode\n"; // changed
1145 // from \nonstopmode
1146 d->texrow.newline();
1148 if (!original_path.empty()) {
1150 // We don't know the encoding of inputpath
1151 docstring const inputpath = from_utf8(latex_path(original_path));
1152 os << "\\makeatletter\n"
1153 << "\\def\\input@path{{"
1154 << inputpath << "/}}\n"
1155 << "\\makeatother\n";
1156 d->texrow.newline();
1157 d->texrow.newline();
1158 d->texrow.newline();
1161 // get parent macros (if this buffer has a parent) which will be
1162 // written at the document begin further down.
1163 MacroSet parentMacros;
1164 listParentMacros(parentMacros, features);
1166 // Write the preamble
1167 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1169 runparams.use_japanese = features.isRequired("japanese");
1175 os << "\\begin{document}\n";
1176 d->texrow.newline();
1178 // output the parent macros
1179 MacroSet::iterator it = parentMacros.begin();
1180 MacroSet::iterator end = parentMacros.end();
1181 for (; it != end; ++it)
1182 (*it)->write(os, true);
1183 } // output_preamble
1185 d->texrow.start(paragraphs().begin()->id(), 0);
1187 LYXERR(Debug::INFO, "preamble finished, now the body.");
1189 // if we are doing a real file with body, even if this is the
1190 // child of some other buffer, let's cut the link here.
1191 // This happens for example if only a child document is printed.
1192 Buffer const * save_parent = 0;
1193 if (output_preamble) {
1194 save_parent = d->parent();
1199 latexParagraphs(*this, text(), os, d->texrow, runparams);
1201 // Restore the parenthood if needed
1202 if (output_preamble)
1203 d->setParent(save_parent);
1205 // add this just in case after all the paragraphs
1207 d->texrow.newline();
1209 if (output_preamble) {
1210 os << "\\end{document}\n";
1211 d->texrow.newline();
1212 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1214 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1216 runparams_in.encoding = runparams.encoding;
1218 // Just to be sure. (Asger)
1219 d->texrow.newline();
1221 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1222 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1226 bool Buffer::isLatex() const
1228 return params().documentClass().outputType() == LATEX;
1232 bool Buffer::isLiterate() const
1234 return params().documentClass().outputType() == LITERATE;
1238 bool Buffer::isDocBook() const
1240 return params().documentClass().outputType() == DOCBOOK;
1244 void Buffer::makeDocBookFile(FileName const & fname,
1245 OutputParams const & runparams,
1246 bool const body_only) const
1248 LYXERR(Debug::LATEX, "makeDocBookFile...");
1251 if (!openFileWrite(ofs, fname))
1254 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1258 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1262 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1263 OutputParams const & runparams,
1264 bool const only_body) const
1266 LaTeXFeatures features(*this, params(), runparams);
1271 DocumentClass const & tclass = params().documentClass();
1272 string const top_element = tclass.latexname();
1275 if (runparams.flavor == OutputParams::XML)
1276 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1279 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1282 if (! tclass.class_header().empty())
1283 os << from_ascii(tclass.class_header());
1284 else if (runparams.flavor == OutputParams::XML)
1285 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1286 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1288 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1290 docstring preamble = from_utf8(params().preamble);
1291 if (runparams.flavor != OutputParams::XML ) {
1292 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1293 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1294 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1295 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1298 string const name = runparams.nice
1299 ? changeExtension(absFileName(), ".sgml") : fname;
1300 preamble += features.getIncludedFiles(name);
1301 preamble += features.getLyXSGMLEntities();
1303 if (!preamble.empty()) {
1304 os << "\n [ " << preamble << " ]";
1309 string top = top_element;
1311 if (runparams.flavor == OutputParams::XML)
1312 top += params().language->code();
1314 top += params().language->code().substr(0, 2);
1317 if (!params().options.empty()) {
1319 top += params().options;
1322 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1323 << " file was created by LyX " << lyx_version
1324 << "\n See http://www.lyx.org/ for more information -->\n";
1326 params().documentClass().counters().reset();
1330 sgml::openTag(os, top);
1332 docbookParagraphs(paragraphs(), *this, os, runparams);
1333 sgml::closeTag(os, top_element);
1337 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1338 // Other flags: -wall -v0 -x
1339 int Buffer::runChktex()
1343 // get LaTeX-Filename
1344 FileName const path(temppath());
1345 string const name = addName(path.absFilename(), latexName());
1346 string const org_path = filePath();
1348 PathChanger p(path); // path to LaTeX file
1349 message(_("Running chktex..."));
1351 // Generate the LaTeX file if neccessary
1352 OutputParams runparams(¶ms().encoding());
1353 runparams.flavor = OutputParams::LATEX;
1354 runparams.nice = false;
1355 makeLaTeXFile(FileName(name), org_path, runparams);
1358 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1359 int const res = chktex.run(terr); // run chktex
1362 Alert::error(_("chktex failure"),
1363 _("Could not run chktex successfully."));
1364 } else if (res > 0) {
1365 ErrorList & errlist = d->errorLists["ChkTeX"];
1367 bufferErrors(terr, errlist);
1378 void Buffer::validate(LaTeXFeatures & features) const
1380 params().validate(features);
1384 for_each(paragraphs().begin(), paragraphs().end(),
1385 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1387 if (lyxerr.debugging(Debug::LATEX)) {
1388 features.showStruct();
1393 void Buffer::getLabelList(vector<docstring> & list) const
1395 // If this is a child document, use the parent's list instead.
1396 Buffer const * const pbuf = d->parent();
1398 pbuf->getLabelList(list);
1403 Toc & toc = d->toc_backend.toc("label");
1404 TocIterator toc_it = toc.begin();
1405 TocIterator end = toc.end();
1406 for (; toc_it != end; ++toc_it) {
1407 if (toc_it->depth() == 0)
1408 list.push_back(toc_it->str());
1413 void Buffer::updateBibfilesCache(UpdateScope scope) const
1415 // If this is a child document, use the parent's cache instead.
1416 Buffer const * const pbuf = d->parent();
1417 if (pbuf && scope != UpdateChildOnly) {
1418 pbuf->updateBibfilesCache();
1422 d->bibfilesCache_.clear();
1423 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1424 if (it->lyxCode() == BIBTEX_CODE) {
1425 InsetBibtex const & inset =
1426 static_cast<InsetBibtex const &>(*it);
1427 support::FileNameList const bibfiles = inset.getBibFiles();
1428 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1431 } else if (it->lyxCode() == INCLUDE_CODE) {
1432 InsetInclude & inset =
1433 static_cast<InsetInclude &>(*it);
1434 inset.updateBibfilesCache();
1435 support::FileNameList const & bibfiles =
1436 inset.getBibfilesCache();
1437 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1442 // the bibinfo cache is now invalid
1443 d->bibinfoCacheValid_ = false;
1447 void Buffer::invalidateBibinfoCache()
1449 d->bibinfoCacheValid_ = false;
1453 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1455 // If this is a child document, use the parent's cache instead.
1456 Buffer const * const pbuf = d->parent();
1457 if (pbuf && scope != UpdateChildOnly)
1458 return pbuf->getBibfilesCache();
1460 // We update the cache when first used instead of at loading time.
1461 if (d->bibfilesCache_.empty())
1462 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1464 return d->bibfilesCache_;
1468 BiblioInfo const & Buffer::masterBibInfo() const
1470 // if this is a child document and the parent is already loaded
1471 // use the parent's list instead [ale990412]
1472 Buffer const * const tmp = masterBuffer();
1475 return tmp->masterBibInfo();
1476 return localBibInfo();
1480 BiblioInfo const & Buffer::localBibInfo() const
1482 if (d->bibinfoCacheValid_) {
1483 support::FileNameList const & bibfilesCache = getBibfilesCache();
1484 // compare the cached timestamps with the actual ones.
1485 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1486 support::FileNameList::const_iterator en = bibfilesCache.end();
1487 for (; ei != en; ++ ei) {
1488 time_t lastw = ei->lastModified();
1489 if (lastw != d->bibfileStatus_[*ei]) {
1490 d->bibinfoCacheValid_ = false;
1491 d->bibfileStatus_[*ei] = lastw;
1497 if (!d->bibinfoCacheValid_) {
1498 d->bibinfo_.clear();
1499 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1500 it->fillWithBibKeys(d->bibinfo_, it);
1501 d->bibinfoCacheValid_ = true;
1507 bool Buffer::isDepClean(string const & name) const
1509 DepClean::const_iterator const it = d->dep_clean.find(name);
1510 if (it == d->dep_clean.end())
1516 void Buffer::markDepClean(string const & name)
1518 d->dep_clean[name] = true;
1522 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1524 switch (cmd.action) {
1525 case LFUN_BUFFER_EXPORT: {
1526 docstring const arg = cmd.argument();
1527 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1529 flag.message(bformat(
1530 _("Don't know how to export to format: %1$s"), arg));
1531 flag.setEnabled(enable);
1535 case LFUN_BRANCH_ACTIVATE:
1536 case LFUN_BRANCH_DEACTIVATE: {
1537 BranchList const & branchList = params().branchlist();
1538 docstring const branchName = cmd.argument();
1539 flag.setEnabled(!branchName.empty()
1540 && branchList.find(branchName));
1544 case LFUN_BUFFER_PRINT:
1545 // if no Buffer is present, then of course we won't be called!
1546 flag.setEnabled(true);
1556 void Buffer::dispatch(string const & command, DispatchResult & result)
1558 return dispatch(lyxaction.lookupFunc(command), result);
1562 // NOTE We can end up here even if we have no GUI, because we are called
1563 // by LyX::exec to handled command-line requests. So we may need to check
1564 // whether we have a GUI or not. The boolean use_gui holds this information.
1565 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1567 // We'll set this back to false if need be.
1568 bool dispatched = true;
1570 switch (func.action) {
1571 case LFUN_BUFFER_EXPORT: {
1572 bool success = doExport(to_utf8(func.argument()), false);
1573 dr.setError(success);
1575 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1580 case LFUN_BRANCH_ACTIVATE:
1581 case LFUN_BRANCH_DEACTIVATE: {
1582 BranchList & branchList = params().branchlist();
1583 docstring const branchName = func.argument();
1584 // the case without a branch name is handled elsewhere
1585 if (branchName.empty()) {
1589 Branch * branch = branchList.find(branchName);
1591 LYXERR0("Branch " << branchName << " does not exist.");
1593 docstring const msg =
1594 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1597 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1599 dr.update(Update::Force);
1604 case LFUN_BUFFER_PRINT: {
1605 // we'll assume there's a problem until we succeed
1607 string target = func.getArg(0);
1608 string target_name = func.getArg(1);
1609 string command = func.getArg(2);
1612 || target_name.empty()
1613 || command.empty()) {
1614 LYXERR0("Unable to parse " << func.argument());
1615 docstring const msg =
1616 bformat(_("Unable to parse \"%1$s\""), func.argument());
1620 if (target != "printer" && target != "file") {
1621 LYXERR0("Unrecognized target \"" << target << '"');
1622 docstring const msg =
1623 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1628 if (!doExport("dvi", true)) {
1629 showPrintError(absFileName());
1630 dr.setMessage(_("Error exporting to DVI."));
1634 // Push directory path.
1635 string const path = temppath();
1636 // Prevent the compiler from optimizing away p
1640 // there are three cases here:
1641 // 1. we print to a file
1642 // 2. we print directly to a printer
1643 // 3. we print using a spool command (print to file first)
1646 string const dviname = changeExtension(latexName(true), "dvi");
1648 if (target == "printer") {
1649 if (!lyxrc.print_spool_command.empty()) {
1650 // case 3: print using a spool
1651 string const psname = changeExtension(dviname,".ps");
1652 command += ' ' + lyxrc.print_to_file
1655 + quoteName(dviname);
1657 string command2 = lyxrc.print_spool_command + ' ';
1658 if (target_name != "default") {
1659 command2 += lyxrc.print_spool_printerprefix
1663 command2 += quoteName(psname);
1665 // If successful, then spool command
1666 res = one.startscript(Systemcall::Wait, command);
1669 // If there's no GUI, we have to wait on this command. Otherwise,
1670 // LyX deletes the temporary directory, and with it the spooled
1671 // file, before it can be printed!!
1672 Systemcall::Starttype stype = use_gui ?
1673 Systemcall::DontWait : Systemcall::Wait;
1674 res = one.startscript(stype, command2);
1677 // case 2: print directly to a printer
1678 if (target_name != "default")
1679 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1681 Systemcall::Starttype stype = use_gui ?
1682 Systemcall::DontWait : Systemcall::Wait;
1683 res = one.startscript(stype, command + quoteName(dviname));
1687 // case 1: print to a file
1688 FileName const filename(makeAbsPath(target_name, filePath()));
1689 FileName const dvifile(makeAbsPath(dviname, path));
1690 if (filename.exists()) {
1691 docstring text = bformat(
1692 _("The file %1$s already exists.\n\n"
1693 "Do you want to overwrite that file?"),
1694 makeDisplayPath(filename.absFilename()));
1695 if (Alert::prompt(_("Overwrite file?"),
1696 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1699 command += ' ' + lyxrc.print_to_file
1700 + quoteName(filename.toFilesystemEncoding())
1702 + quoteName(dvifile.toFilesystemEncoding());
1704 Systemcall::Starttype stype = use_gui ?
1705 Systemcall::DontWait : Systemcall::Wait;
1706 res = one.startscript(stype, command);
1712 dr.setMessage(_("Error running external commands."));
1713 showPrintError(absFileName());
1722 dr.dispatched(dispatched);
1726 void Buffer::changeLanguage(Language const * from, Language const * to)
1728 LASSERT(from, /**/);
1731 for_each(par_iterator_begin(),
1733 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1737 bool Buffer::isMultiLingual() const
1739 ParConstIterator end = par_iterator_end();
1740 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1741 if (it->isMultiLingual(params()))
1748 DocIterator Buffer::getParFromID(int const id) const
1750 Buffer * buf = const_cast<Buffer *>(this);
1752 // John says this is called with id == -1 from undo
1753 lyxerr << "getParFromID(), id: " << id << endl;
1754 return doc_iterator_end(buf);
1757 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1758 if (it.paragraph().id() == id)
1761 return doc_iterator_end(buf);
1765 bool Buffer::hasParWithID(int const id) const
1767 return !getParFromID(id).atEnd();
1771 ParIterator Buffer::par_iterator_begin()
1773 return ParIterator(doc_iterator_begin(this));
1777 ParIterator Buffer::par_iterator_end()
1779 return ParIterator(doc_iterator_end(this));
1783 ParConstIterator Buffer::par_iterator_begin() const
1785 return ParConstIterator(doc_iterator_begin(this));
1789 ParConstIterator Buffer::par_iterator_end() const
1791 return ParConstIterator(doc_iterator_end(this));
1795 Language const * Buffer::language() const
1797 return params().language;
1801 docstring const Buffer::B_(string const & l10n) const
1803 return params().B_(l10n);
1807 bool Buffer::isClean() const
1809 return d->lyx_clean;
1813 bool Buffer::isBakClean() const
1815 return d->bak_clean;
1819 bool Buffer::isExternallyModified(CheckMethod method) const
1821 LASSERT(d->filename.exists(), /**/);
1822 // if method == timestamp, check timestamp before checksum
1823 return (method == checksum_method
1824 || d->timestamp_ != d->filename.lastModified())
1825 && d->checksum_ != d->filename.checksum();
1829 void Buffer::saveCheckSum(FileName const & file) const
1831 if (file.exists()) {
1832 d->timestamp_ = file.lastModified();
1833 d->checksum_ = file.checksum();
1835 // in the case of save to a new file.
1842 void Buffer::markClean() const
1844 if (!d->lyx_clean) {
1845 d->lyx_clean = true;
1848 // if the .lyx file has been saved, we don't need an
1850 d->bak_clean = true;
1854 void Buffer::markBakClean() const
1856 d->bak_clean = true;
1860 void Buffer::setUnnamed(bool flag)
1866 bool Buffer::isUnnamed() const
1872 // FIXME: this function should be moved to buffer_pimpl.C
1873 void Buffer::markDirty()
1876 d->lyx_clean = false;
1879 d->bak_clean = false;
1881 DepClean::iterator it = d->dep_clean.begin();
1882 DepClean::const_iterator const end = d->dep_clean.end();
1884 for (; it != end; ++it)
1889 FileName Buffer::fileName() const
1895 string Buffer::absFileName() const
1897 return d->filename.absFilename();
1901 string Buffer::filePath() const
1903 return d->filename.onlyPath().absFilename() + "/";
1907 bool Buffer::isReadonly() const
1909 return d->read_only;
1913 void Buffer::setParent(Buffer const * buffer)
1915 // Avoids recursive include.
1916 d->setParent(buffer == this ? 0 : buffer);
1921 Buffer const * Buffer::parent() const
1927 void Buffer::collectRelatives(BufferSet & bufs) const
1931 parent()->collectRelatives(bufs);
1933 // loop over children
1934 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1935 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1936 for (; it != end; ++it)
1937 bufs.insert(const_cast<Buffer *>(it->first));
1941 std::vector<Buffer const *> Buffer::allRelatives() const
1944 collectRelatives(bufs);
1945 BufferSet::iterator it = bufs.begin();
1946 std::vector<Buffer const *> ret;
1947 for (; it != bufs.end(); ++it)
1953 Buffer const * Buffer::masterBuffer() const
1955 Buffer const * const pbuf = d->parent();
1959 return pbuf->masterBuffer();
1963 bool Buffer::isChild(Buffer * child) const
1965 return d->children_positions.find(child) != d->children_positions.end();
1969 DocIterator Buffer::firstChildPosition(Buffer const * child)
1971 Impl::BufferPositionMap::iterator it;
1972 it = d->children_positions.find(child);
1973 if (it == d->children_positions.end())
1974 return DocIterator(this);
1979 std::vector<Buffer *> Buffer::getChildren() const
1981 std::vector<Buffer *> clist;
1982 // loop over children
1983 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1984 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1985 for (; it != end; ++it) {
1986 Buffer * child = const_cast<Buffer *>(it->first);
1987 clist.push_back(child);
1988 // there might be grandchildren
1989 std::vector<Buffer *> glist = child->getChildren();
1990 for (vector<Buffer *>::const_iterator git = glist.begin();
1991 git != glist.end(); ++git)
1992 clist.push_back(*git);
1998 template<typename M>
1999 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2004 typename M::iterator it = m.lower_bound(x);
2005 if (it == m.begin())
2013 MacroData const * Buffer::getBufferMacro(docstring const & name,
2014 DocIterator const & pos) const
2016 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2018 // if paragraphs have no macro context set, pos will be empty
2022 // we haven't found anything yet
2023 DocIterator bestPos = par_iterator_begin();
2024 MacroData const * bestData = 0;
2026 // find macro definitions for name
2027 Impl::NamePositionScopeMacroMap::iterator nameIt
2028 = d->macros.find(name);
2029 if (nameIt != d->macros.end()) {
2030 // find last definition in front of pos or at pos itself
2031 Impl::PositionScopeMacroMap::const_iterator it
2032 = greatest_below(nameIt->second, pos);
2033 if (it != nameIt->second.end()) {
2035 // scope ends behind pos?
2036 if (pos < it->second.first) {
2037 // Looks good, remember this. If there
2038 // is no external macro behind this,
2039 // we found the right one already.
2040 bestPos = it->first;
2041 bestData = &it->second.second;
2045 // try previous macro if there is one
2046 if (it == nameIt->second.begin())
2053 // find macros in included files
2054 Impl::PositionScopeBufferMap::const_iterator it
2055 = greatest_below(d->position_to_children, pos);
2056 if (it == d->position_to_children.end())
2057 // no children before
2061 // do we know something better (i.e. later) already?
2062 if (it->first < bestPos )
2065 // scope ends behind pos?
2066 if (pos < it->second.first) {
2067 // look for macro in external file
2068 d->macro_lock = true;
2069 MacroData const * data
2070 = it->second.second->getMacro(name, false);
2071 d->macro_lock = false;
2073 bestPos = it->first;
2079 // try previous file if there is one
2080 if (it == d->position_to_children.begin())
2085 // return the best macro we have found
2090 MacroData const * Buffer::getMacro(docstring const & name,
2091 DocIterator const & pos, bool global) const
2096 // query buffer macros
2097 MacroData const * data = getBufferMacro(name, pos);
2101 // If there is a master buffer, query that
2102 Buffer const * const pbuf = d->parent();
2104 d->macro_lock = true;
2105 MacroData const * macro = pbuf->getMacro(
2106 name, *this, false);
2107 d->macro_lock = false;
2113 data = MacroTable::globalMacros().get(name);
2122 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2124 // set scope end behind the last paragraph
2125 DocIterator scope = par_iterator_begin();
2126 scope.pit() = scope.lastpit() + 1;
2128 return getMacro(name, scope, global);
2132 MacroData const * Buffer::getMacro(docstring const & name,
2133 Buffer const & child, bool global) const
2135 // look where the child buffer is included first
2136 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2137 if (it == d->children_positions.end())
2140 // check for macros at the inclusion position
2141 return getMacro(name, it->second, global);
2145 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2147 pit_type lastpit = it.lastpit();
2149 // look for macros in each paragraph
2150 while (it.pit() <= lastpit) {
2151 Paragraph & par = it.paragraph();
2153 // iterate over the insets of the current paragraph
2154 InsetList const & insets = par.insetList();
2155 InsetList::const_iterator iit = insets.begin();
2156 InsetList::const_iterator end = insets.end();
2157 for (; iit != end; ++iit) {
2158 it.pos() = iit->pos;
2160 // is it a nested text inset?
2161 if (iit->inset->asInsetText()) {
2162 // Inset needs its own scope?
2163 InsetText const * itext = iit->inset->asInsetText();
2164 bool newScope = itext->isMacroScope();
2166 // scope which ends just behind the inset
2167 DocIterator insetScope = it;
2170 // collect macros in inset
2171 it.push_back(CursorSlice(*iit->inset));
2172 updateMacros(it, newScope ? insetScope : scope);
2177 // is it an external file?
2178 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2179 // get buffer of external file
2180 InsetInclude const & inset =
2181 static_cast<InsetInclude const &>(*iit->inset);
2182 d->macro_lock = true;
2183 Buffer * child = inset.getChildBuffer();
2184 d->macro_lock = false;
2188 // register its position, but only when it is
2189 // included first in the buffer
2190 if (d->children_positions.find(child) ==
2191 d->children_positions.end())
2192 d->children_positions[child] = it;
2194 // register child with its scope
2195 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2199 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2203 MathMacroTemplate & macroTemplate =
2204 static_cast<MathMacroTemplate &>(*iit->inset);
2205 MacroContext mc(*this, it);
2206 macroTemplate.updateToContext(mc);
2209 bool valid = macroTemplate.validMacro();
2210 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2211 // then the BufferView's cursor will be invalid in
2212 // some cases which leads to crashes.
2217 d->macros[macroTemplate.name()][it] =
2218 Impl::ScopeMacro(scope, MacroData(*this, it));
2228 void Buffer::updateMacros() const
2233 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2235 // start with empty table
2237 d->children_positions.clear();
2238 d->position_to_children.clear();
2240 // Iterate over buffer, starting with first paragraph
2241 // The scope must be bigger than any lookup DocIterator
2242 // later. For the global lookup, lastpit+1 is used, hence
2243 // we use lastpit+2 here.
2244 DocIterator it = par_iterator_begin();
2245 DocIterator outerScope = it;
2246 outerScope.pit() = outerScope.lastpit() + 2;
2247 updateMacros(it, outerScope);
2251 void Buffer::updateMacroInstances() const
2253 LYXERR(Debug::MACROS, "updateMacroInstances for "
2254 << d->filename.onlyFileName());
2255 DocIterator it = doc_iterator_begin(this);
2256 DocIterator end = doc_iterator_end(this);
2257 for (; it != end; it.forwardPos()) {
2258 // look for MathData cells in InsetMathNest insets
2259 Inset * inset = it.nextInset();
2263 InsetMath * minset = inset->asInsetMath();
2267 // update macro in all cells of the InsetMathNest
2268 DocIterator::idx_type n = minset->nargs();
2269 MacroContext mc = MacroContext(*this, it);
2270 for (DocIterator::idx_type i = 0; i < n; ++i) {
2271 MathData & data = minset->cell(i);
2272 data.updateMacros(0, mc);
2278 void Buffer::listMacroNames(MacroNameSet & macros) const
2283 d->macro_lock = true;
2285 // loop over macro names
2286 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2287 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2288 for (; nameIt != nameEnd; ++nameIt)
2289 macros.insert(nameIt->first);
2291 // loop over children
2292 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2293 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2294 for (; it != end; ++it)
2295 it->first->listMacroNames(macros);
2298 Buffer const * const pbuf = d->parent();
2300 pbuf->listMacroNames(macros);
2302 d->macro_lock = false;
2306 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2308 Buffer const * const pbuf = d->parent();
2313 pbuf->listMacroNames(names);
2316 MacroNameSet::iterator it = names.begin();
2317 MacroNameSet::iterator end = names.end();
2318 for (; it != end; ++it) {
2320 MacroData const * data =
2321 pbuf->getMacro(*it, *this, false);
2323 macros.insert(data);
2325 // we cannot access the original MathMacroTemplate anymore
2326 // here to calls validate method. So we do its work here manually.
2327 // FIXME: somehow make the template accessible here.
2328 if (data->optionals() > 0)
2329 features.require("xargs");
2335 Buffer::References & Buffer::references(docstring const & label)
2338 return const_cast<Buffer *>(masterBuffer())->references(label);
2340 RefCache::iterator it = d->ref_cache_.find(label);
2341 if (it != d->ref_cache_.end())
2342 return it->second.second;
2344 static InsetLabel const * dummy_il = 0;
2345 static References const dummy_refs;
2346 it = d->ref_cache_.insert(
2347 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2348 return it->second.second;
2352 Buffer::References const & Buffer::references(docstring const & label) const
2354 return const_cast<Buffer *>(this)->references(label);
2358 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2360 masterBuffer()->d->ref_cache_[label].first = il;
2364 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2366 return masterBuffer()->d->ref_cache_[label].first;
2370 void Buffer::clearReferenceCache() const
2373 d->ref_cache_.clear();
2377 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2380 //FIXME: This does not work for child documents yet.
2381 LASSERT(code == CITE_CODE, /**/);
2382 // Check if the label 'from' appears more than once
2383 vector<docstring> labels;
2385 BiblioInfo const & keys = masterBibInfo();
2386 BiblioInfo::const_iterator bit = keys.begin();
2387 BiblioInfo::const_iterator bend = keys.end();
2389 for (; bit != bend; ++bit)
2391 labels.push_back(bit->first);
2394 if (count(labels.begin(), labels.end(), from) > 1)
2397 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2398 if (it->lyxCode() == code) {
2399 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2400 docstring const oldValue = inset.getParam(paramName);
2401 if (oldValue == from)
2402 inset.setParam(paramName, to);
2408 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2409 pit_type par_end, bool full_source) const
2411 OutputParams runparams(¶ms().encoding());
2412 runparams.nice = true;
2413 runparams.flavor = params().useXetex ?
2414 OutputParams::XETEX : OutputParams::LATEX;
2415 runparams.linelen = lyxrc.plaintext_linelen;
2416 // No side effect of file copying and image conversion
2417 runparams.dryrun = true;
2421 os << "% " << _("Preview source code") << "\n\n";
2422 d->texrow.newline();
2423 d->texrow.newline();
2425 writeDocBookSource(os, absFileName(), runparams, false);
2427 // latex or literate
2428 writeLaTeXSource(os, string(), runparams, true, true);
2430 runparams.par_begin = par_begin;
2431 runparams.par_end = par_end;
2432 if (par_begin + 1 == par_end) {
2434 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2438 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2439 convert<docstring>(par_begin),
2440 convert<docstring>(par_end - 1))
2443 d->texrow.newline();
2444 d->texrow.newline();
2445 // output paragraphs
2447 docbookParagraphs(paragraphs(), *this, os, runparams);
2449 // latex or literate
2450 latexParagraphs(*this, text(), os, d->texrow, runparams);
2455 ErrorList & Buffer::errorList(string const & type) const
2457 static ErrorList emptyErrorList;
2458 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2459 if (I == d->errorLists.end())
2460 return emptyErrorList;
2466 void Buffer::updateTocItem(std::string const & type,
2467 DocIterator const & dit) const
2470 gui_->updateTocItem(type, dit);
2474 void Buffer::structureChanged() const
2477 gui_->structureChanged();
2481 void Buffer::errors(string const & err) const
2488 void Buffer::message(docstring const & msg) const
2495 void Buffer::setBusy(bool on) const
2502 void Buffer::setReadOnly(bool on) const
2505 d->wa_->setReadOnly(on);
2509 void Buffer::updateTitles() const
2512 d->wa_->updateTitles();
2516 void Buffer::resetAutosaveTimers() const
2519 gui_->resetAutosaveTimers();
2523 bool Buffer::hasGuiDelegate() const
2529 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2538 class AutoSaveBuffer : public ForkedProcess {
2541 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2542 : buffer_(buffer), fname_(fname) {}
2544 virtual boost::shared_ptr<ForkedProcess> clone() const
2546 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2551 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2552 from_utf8(fname_.absFilename())));
2553 return run(DontWait);
2557 virtual int generateChild();
2559 Buffer const & buffer_;
2564 int AutoSaveBuffer::generateChild()
2566 // tmp_ret will be located (usually) in /tmp
2567 // will that be a problem?
2568 // Note that this calls ForkedCalls::fork(), so it's
2569 // ok cross-platform.
2570 pid_t const pid = fork();
2571 // If you want to debug the autosave
2572 // you should set pid to -1, and comment out the fork.
2573 if (pid != 0 && pid != -1)
2576 // pid = -1 signifies that lyx was unable
2577 // to fork. But we will do the save
2579 bool failed = false;
2580 FileName const tmp_ret = FileName::tempName("lyxauto");
2581 if (!tmp_ret.empty()) {
2582 buffer_.writeFile(tmp_ret);
2583 // assume successful write of tmp_ret
2584 if (!tmp_ret.moveTo(fname_))
2590 // failed to write/rename tmp_ret so try writing direct
2591 if (!buffer_.writeFile(fname_)) {
2592 // It is dangerous to do this in the child,
2593 // but safe in the parent, so...
2594 if (pid == -1) // emit message signal.
2595 buffer_.message(_("Autosave failed!"));
2599 if (pid == 0) // we are the child so...
2608 FileName Buffer::getAutosaveFilename() const
2610 string const fpath = isUnnamed() ? lyxrc.document_path : filePath();
2611 string const fname = "#" + d->filename.onlyFileName() + "#";
2612 return makeAbsPath(fname, fpath);
2616 void Buffer::removeAutosaveFile() const
2618 FileName const f = getAutosaveFilename();
2624 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2626 FileName const newauto = getAutosaveFilename();
2627 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2628 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2632 // Perfect target for a thread...
2633 void Buffer::autoSave() const
2635 if (isBakClean() || isReadonly()) {
2636 // We don't save now, but we'll try again later
2637 resetAutosaveTimers();
2641 // emit message signal.
2642 message(_("Autosaving current document..."));
2643 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2647 resetAutosaveTimers();
2651 string Buffer::bufferFormat() const
2657 if (params().useXetex)
2659 if (params().encoding().package() == Encoding::japanese)
2665 string Buffer::getDefaultOutputFormat() const
2667 if (!params().defaultOutputFormat.empty()
2668 && params().defaultOutputFormat != "default")
2669 return params().defaultOutputFormat;
2670 typedef vector<Format const *> Formats;
2671 Formats formats = exportableFormats(true);
2674 || params().useXetex
2675 || params().encoding().package() == Encoding::japanese) {
2676 if (formats.empty())
2678 // return the first we find
2679 return formats.front()->name();
2681 return lyxrc.default_view_format;
2686 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2687 string & result_file) const
2689 string backend_format;
2690 OutputParams runparams(¶ms().encoding());
2691 runparams.flavor = OutputParams::LATEX;
2692 runparams.linelen = lyxrc.plaintext_linelen;
2693 vector<string> backs = backends();
2694 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2695 // Get shortest path to format
2696 Graph::EdgePath path;
2697 for (vector<string>::const_iterator it = backs.begin();
2698 it != backs.end(); ++it) {
2699 Graph::EdgePath p = theConverters().getPath(*it, format);
2700 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2701 backend_format = *it;
2706 runparams.flavor = theConverters().getFlavor(path);
2708 Alert::error(_("Couldn't export file"),
2709 bformat(_("No information for exporting the format %1$s."),
2710 formats.prettyName(format)));
2714 backend_format = format;
2715 // FIXME: Don't hardcode format names here, but use a flag
2716 if (backend_format == "pdflatex")
2717 runparams.flavor = OutputParams::PDFLATEX;
2720 string filename = latexName(false);
2721 filename = addName(temppath(), filename);
2722 filename = changeExtension(filename,
2723 formats.extension(backend_format));
2726 updateMacroInstances();
2728 // Plain text backend
2729 if (backend_format == "text")
2730 writePlaintextFile(*this, FileName(filename), runparams);
2732 else if (backend_format == "lyx")
2733 writeFile(FileName(filename));
2735 else if (isDocBook()) {
2736 runparams.nice = !put_in_tempdir;
2737 makeDocBookFile(FileName(filename), runparams);
2740 else if (backend_format == format) {
2741 runparams.nice = true;
2742 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2744 } else if (!lyxrc.tex_allows_spaces
2745 && contains(filePath(), ' ')) {
2746 Alert::error(_("File name error"),
2747 _("The directory path to the document cannot contain spaces."));
2750 runparams.nice = false;
2751 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2755 string const error_type = (format == "program")
2756 ? "Build" : bufferFormat();
2757 ErrorList & error_list = d->errorLists[error_type];
2758 string const ext = formats.extension(format);
2759 FileName const tmp_result_file(changeExtension(filename, ext));
2760 bool const success = theConverters().convert(this, FileName(filename),
2761 tmp_result_file, FileName(absFileName()), backend_format, format,
2763 // Emit the signal to show the error list.
2764 if (format != backend_format)
2769 if (put_in_tempdir) {
2770 result_file = tmp_result_file.absFilename();
2774 result_file = changeExtension(absFileName(), ext);
2775 // We need to copy referenced files (e. g. included graphics
2776 // if format == "dvi") to the result dir.
2777 vector<ExportedFile> const files =
2778 runparams.exportdata->externalFiles(format);
2779 string const dest = onlyPath(result_file);
2780 CopyStatus status = SUCCESS;
2781 for (vector<ExportedFile>::const_iterator it = files.begin();
2782 it != files.end() && status != CANCEL; ++it) {
2783 string const fmt = formats.getFormatFromFile(it->sourceName);
2784 status = copyFile(fmt, it->sourceName,
2785 makeAbsPath(it->exportName, dest),
2786 it->exportName, status == FORCE);
2788 if (status == CANCEL) {
2789 message(_("Document export cancelled."));
2790 } else if (tmp_result_file.exists()) {
2791 // Finally copy the main file
2792 status = copyFile(format, tmp_result_file,
2793 FileName(result_file), result_file,
2795 message(bformat(_("Document exported as %1$s "
2797 formats.prettyName(format),
2798 makeDisplayPath(result_file)));
2800 // This must be a dummy converter like fax (bug 1888)
2801 message(bformat(_("Document exported as %1$s"),
2802 formats.prettyName(format)));
2809 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2812 return doExport(format, put_in_tempdir, result_file);
2816 bool Buffer::preview(string const & format) const
2819 if (!doExport(format, true, result_file))
2821 return formats.view(*this, FileName(result_file), format);
2825 bool Buffer::isExportable(string const & format) const
2827 vector<string> backs = backends();
2828 for (vector<string>::const_iterator it = backs.begin();
2829 it != backs.end(); ++it)
2830 if (theConverters().isReachable(*it, format))
2836 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2838 vector<string> backs = backends();
2839 vector<Format const *> result =
2840 theConverters().getReachable(backs[0], only_viewable, true);
2841 for (vector<string>::const_iterator it = backs.begin() + 1;
2842 it != backs.end(); ++it) {
2843 vector<Format const *> r =
2844 theConverters().getReachable(*it, only_viewable, false);
2845 result.insert(result.end(), r.begin(), r.end());
2851 vector<string> Buffer::backends() const
2854 if (params().baseClass()->isTeXClassAvailable()) {
2855 v.push_back(bufferFormat());
2856 // FIXME: Don't hardcode format names here, but use a flag
2857 if (v.back() == "latex")
2858 v.push_back("pdflatex");
2860 v.push_back("text");
2866 bool Buffer::readFileHelper(FileName const & s)
2868 // File information about normal file
2870 docstring const file = makeDisplayPath(s.absFilename(), 50);
2871 docstring text = bformat(_("The specified document\n%1$s"
2872 "\ncould not be read."), file);
2873 Alert::error(_("Could not read document"), text);
2877 // Check if emergency save file exists and is newer.
2878 FileName const e(s.absFilename() + ".emergency");
2880 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2881 docstring const file = makeDisplayPath(s.absFilename(), 20);
2882 docstring const text =
2883 bformat(_("An emergency save of the document "
2885 "Recover emergency save?"), file);
2886 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2887 _("&Recover"), _("&Load Original"),
2891 // the file is not saved if we load the emergency file.
2901 // Now check if autosave file is newer.
2902 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2904 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2905 docstring const file = makeDisplayPath(s.absFilename(), 20);
2906 docstring const text =
2907 bformat(_("The backup of the document "
2908 "%1$s is newer.\n\nLoad the "
2909 "backup instead?"), file);
2910 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2911 _("&Load backup"), _("Load &original"),
2915 // the file is not saved if we load the autosave file.
2919 // Here we delete the autosave
2930 bool Buffer::loadLyXFile(FileName const & s)
2932 if (s.isReadableFile()) {
2933 if (readFileHelper(s)) {
2934 lyxvc().file_found_hook(s);
2935 if (!s.isWritable())
2940 docstring const file = makeDisplayPath(s.absFilename(), 20);
2941 // Here we probably should run
2942 if (LyXVC::file_not_found_hook(s)) {
2943 docstring const text =
2944 bformat(_("Do you want to retrieve the document"
2945 " %1$s from version control?"), file);
2946 int const ret = Alert::prompt(_("Retrieve from version control?"),
2947 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2950 // How can we know _how_ to do the checkout?
2951 // With the current VC support it has to be,
2952 // a RCS file since CVS do not have special ,v files.
2954 return loadLyXFile(s);
2962 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2964 TeXErrors::Errors::const_iterator cit = terr.begin();
2965 TeXErrors::Errors::const_iterator end = terr.end();
2967 for (; cit != end; ++cit) {
2970 int errorRow = cit->error_in_line;
2971 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2977 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2978 } while (found && id_start == id_end && pos_start == pos_end);
2980 errorList.push_back(ErrorItem(cit->error_desc,
2981 cit->error_text, id_start, pos_start, pos_end));
2986 void Buffer::setBuffersForInsets() const
2988 inset().setBuffer(const_cast<Buffer &>(*this));
2992 void Buffer::updateLabels(UpdateScope scope) const
2994 // Use the master text class also for child documents
2995 Buffer const * const master = masterBuffer();
2996 DocumentClass const & textclass = master->params().documentClass();
2998 // keep the buffers to be children in this set. If the call from the
2999 // master comes back we can see which of them were actually seen (i.e.
3000 // via an InsetInclude). The remaining ones in the set need still be updated.
3001 static std::set<Buffer const *> bufToUpdate;
3002 if (scope == UpdateMaster) {
3003 // If this is a child document start with the master
3004 if (master != this) {
3005 bufToUpdate.insert(this);
3006 master->updateLabels();
3007 // Do this here in case the master has no gui associated with it. Then,
3008 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3012 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3013 if (bufToUpdate.find(this) == bufToUpdate.end())
3017 // start over the counters in the master
3018 textclass.counters().reset();
3021 // update will be done below for this buffer
3022 bufToUpdate.erase(this);
3024 // update all caches
3025 clearReferenceCache();
3028 Buffer & cbuf = const_cast<Buffer &>(*this);
3030 LASSERT(!text().paragraphs().empty(), /**/);
3033 ParIterator parit = cbuf.par_iterator_begin();
3034 updateLabels(parit);
3037 // TocBackend update will be done later.
3040 cbuf.tocBackend().update();
3041 if (scope == UpdateMaster)
3042 cbuf.structureChanged();
3046 static depth_type getDepth(DocIterator const & it)
3048 depth_type depth = 0;
3049 for (size_t i = 0 ; i < it.depth() ; ++i)
3050 if (!it[i].inset().inMathed())
3051 depth += it[i].paragraph().getDepth() + 1;
3052 // remove 1 since the outer inset does not count
3056 static depth_type getItemDepth(ParIterator const & it)
3058 Paragraph const & par = *it;
3059 LabelType const labeltype = par.layout().labeltype;
3061 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3064 // this will hold the lowest depth encountered up to now.
3065 depth_type min_depth = getDepth(it);
3066 ParIterator prev_it = it;
3069 --prev_it.top().pit();
3071 // start of nested inset: go to outer par
3073 if (prev_it.empty()) {
3074 // start of document: nothing to do
3079 // We search for the first paragraph with same label
3080 // that is not more deeply nested.
3081 Paragraph & prev_par = *prev_it;
3082 depth_type const prev_depth = getDepth(prev_it);
3083 if (labeltype == prev_par.layout().labeltype) {
3084 if (prev_depth < min_depth)
3085 return prev_par.itemdepth + 1;
3086 if (prev_depth == min_depth)
3087 return prev_par.itemdepth;
3089 min_depth = min(min_depth, prev_depth);
3090 // small optimization: if we are at depth 0, we won't
3091 // find anything else
3092 if (prev_depth == 0)
3098 static bool needEnumCounterReset(ParIterator const & it)
3100 Paragraph const & par = *it;
3101 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3102 depth_type const cur_depth = par.getDepth();
3103 ParIterator prev_it = it;
3104 while (prev_it.pit()) {
3105 --prev_it.top().pit();
3106 Paragraph const & prev_par = *prev_it;
3107 if (prev_par.getDepth() <= cur_depth)
3108 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3110 // start of nested inset: reset
3115 // set the label of a paragraph. This includes the counters.
3116 static void setLabel(Buffer const & buf, ParIterator & it)
3118 BufferParams const & bp = buf.masterBuffer()->params();
3119 DocumentClass const & textclass = bp.documentClass();
3120 Paragraph & par = it.paragraph();
3121 Layout const & layout = par.layout();
3122 Counters & counters = textclass.counters();
3124 if (par.params().startOfAppendix()) {
3125 // FIXME: only the counter corresponding to toplevel
3126 // sectionning should be reset
3128 counters.appendix(true);
3130 par.params().appendix(counters.appendix());
3132 // Compute the item depth of the paragraph
3133 par.itemdepth = getItemDepth(it);
3135 if (layout.margintype == MARGIN_MANUAL) {
3136 if (par.params().labelWidthString().empty())
3137 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3139 par.params().labelWidthString(docstring());
3142 switch(layout.labeltype) {
3144 if (layout.toclevel <= bp.secnumdepth
3145 && (layout.latextype != LATEX_ENVIRONMENT
3146 || isFirstInSequence(it.pit(), it.plist()))) {
3147 counters.step(layout.counter);
3148 par.params().labelString(
3149 par.expandLabel(layout, bp));
3151 par.params().labelString(docstring());
3154 case LABEL_ITEMIZE: {
3155 // At some point of time we should do something more
3156 // clever here, like:
3157 // par.params().labelString(
3158 // bp.user_defined_bullet(par.itemdepth).getText());
3159 // for now, use a simple hardcoded label
3160 docstring itemlabel;
3161 switch (par.itemdepth) {
3163 itemlabel = char_type(0x2022);
3166 itemlabel = char_type(0x2013);
3169 itemlabel = char_type(0x2217);
3172 itemlabel = char_type(0x2219); // or 0x00b7
3175 par.params().labelString(itemlabel);
3179 case LABEL_ENUMERATE: {
3180 // FIXME: Yes I know this is a really, really! bad solution
3182 docstring enumcounter = from_ascii("enum");
3184 switch (par.itemdepth) {
3193 enumcounter += "iv";
3196 // not a valid enumdepth...
3200 // Maybe we have to reset the enumeration counter.
3201 if (needEnumCounterReset(it))
3202 counters.reset(enumcounter);
3204 counters.step(enumcounter);
3208 switch (par.itemdepth) {
3210 format = N_("\\arabic{enumi}.");
3213 format = N_("(\\alph{enumii})");
3216 format = N_("\\roman{enumiii}.");
3219 format = N_("\\Alph{enumiv}.");
3222 // not a valid enumdepth...
3226 par.params().labelString(counters.counterLabel(
3227 par.translateIfPossible(from_ascii(format), bp)));
3232 case LABEL_SENSITIVE: {
3233 string const & type = counters.current_float();
3234 docstring full_label;
3236 full_label = buf.B_("Senseless!!! ");
3238 docstring name = buf.B_(textclass.floats().getType(type).name());
3239 if (counters.hasCounter(from_utf8(type))) {
3240 counters.step(from_utf8(type));
3241 full_label = bformat(from_ascii("%1$s %2$s:"),
3243 counters.theCounter(from_utf8(type)));
3245 full_label = bformat(from_ascii("%1$s #:"), name);
3247 par.params().labelString(full_label);
3251 case LABEL_NO_LABEL:
3252 par.params().labelString(docstring());
3256 case LABEL_TOP_ENVIRONMENT:
3257 case LABEL_CENTERED_TOP_ENVIRONMENT:
3260 par.params().labelString(
3261 par.translateIfPossible(layout.labelstring(), bp));
3267 void Buffer::updateLabels(ParIterator & parit) const
3269 LASSERT(parit.pit() == 0, /**/);
3271 // set the position of the text in the buffer to be able
3272 // to resolve macros in it. This has nothing to do with
3273 // labels, but by putting it here we avoid implementing
3274 // a whole bunch of traversal routines just for this call.
3275 parit.text()->setMacrocontextPosition(parit);
3277 depth_type maxdepth = 0;
3278 pit_type const lastpit = parit.lastpit();
3279 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3280 // reduce depth if necessary
3281 parit->params().depth(min(parit->params().depth(), maxdepth));
3282 maxdepth = parit->getMaxDepthAfter();
3284 // set the counter for this paragraph
3285 setLabel(*this, parit);
3288 InsetList::const_iterator iit = parit->insetList().begin();
3289 InsetList::const_iterator end = parit->insetList().end();
3290 for (; iit != end; ++iit) {
3291 parit.pos() = iit->pos;
3292 iit->inset->updateLabels(parit);
3298 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3299 docstring & word) const
3301 bool inword = false;
3302 bool ignoreword = false;
3304 // Go backward a bit if needed in order to return the word currently
3305 // pointed by 'from'.
3306 while (from && from.pos() && isLetter(from))
3308 // OK, we start from here.
3310 while (to.depth()) {
3317 lang_code = to.paragraph().getFontSettings(params(),
3318 to.pos()).language()->code();
3320 // Insets like optional hyphens and ligature
3321 // break are part of a word.
3322 if (!to.paragraph().isInset(to.pos())) {
3323 char_type const c = to.paragraph().getChar(to.pos());
3328 } else { // !isLetter(cur)
3329 if (inword && !word.empty() && !ignoreword)
3341 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3342 WordLangTuple & word_lang, docstring_list & suggestions) const
3345 SpellChecker::Result res = SpellChecker::OK;
3346 SpellChecker * speller = theSpellChecker();
3347 suggestions.clear();
3349 while (nextWord(from, to, word)) {
3351 string lang_code = lyxrc.spellchecker_use_alt_lang
3352 ? lyxrc.spellchecker_alt_lang
3353 : from.paragraph().getFontSettings(params(), from.pos()).language()->code();
3354 WordLangTuple wl(word, lang_code);
3355 res = speller->check(wl);
3356 // ... just bail out if the spellchecker reports an error.
3357 if (!speller->error().empty()) {
3358 throw ExceptionMessage(WarningException,
3359 _("The spellchecker has failed."), speller->error());
3361 if (res != SpellChecker::OK && res != SpellChecker::IGNORED_WORD) {
3367 while (!(word = speller->nextMiss()).empty())
3368 suggestions.push_back(word);