4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
18 #include "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
56 class ParConstIterator;
66 class GuiBufferDelegate;
67 class WorkAreaManager;
77 typedef std::list<Buffer *> ListOfBuffers;
80 /** The buffer object.
81 * This is the buffer object. It contains all the informations about
82 * a document loaded into LyX.
83 * The buffer object owns the Text (wrapped in an InsetText), which
84 * contains the individual paragraphs of the document.
87 * I am not sure if the class is complete or
88 * minimal, probably not.
89 * \author Lars Gullik Bjønnes
93 /// What type of log will \c getLogName() return?
95 latexlog, ///< LaTeX log
96 buildlog ///< Literate build log
99 /// Result of \c readFile()
109 ReadEmergencyFailure,
122 /// Method to check if a file is externally modified, used by
123 /// isExternallyModified()
125 * timestamp is fast but inaccurate. For example, the granularity
126 * of timestamp on a FAT filesystem is 2 second. Also, various operations
127 * may touch the timestamp of a file even when its content is unchanged.
129 * checksum is accurate but slow, which can be a problem when it is
130 * frequently used, or used for a large file on a slow (network) file
133 * FIXME: replace this method with support/FileMonitor.
136 checksum_method, ///< Use file checksum
137 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
147 explicit Buffer(std::string const & file, bool readonly = false,
148 Buffer const * cloned_buffer = 0);
154 Buffer * clone() const;
156 bool isClone() const;
158 /** High-level interface to buffer functionality.
159 This function parses a command string and executes it.
161 void dispatch(std::string const & command, DispatchResult & result);
163 /// Maybe we know the function already by number...
164 void dispatch(FuncRequest const & func, DispatchResult & result);
166 /// Can this function be exectued?
167 /// \return true if we made a decision
168 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
171 DocIterator getParFromID(int id) const;
172 /// do we have a paragraph with this id?
173 bool hasParWithID(int id) const;
176 frontend::WorkAreaManager & workAreaManager() const;
179 Takes care of auto-save files and backup file if requested.
180 Returns \c true if the save is successful, \c false otherwise.
183 /// Renames and saves the buffer
184 bool saveAs(support::FileName const & fn);
186 /// Write document to stream. Returns \c false if unsuccessful.
187 bool write(std::ostream &) const;
188 /// Write file. Returns \c false if unsuccessful.
189 bool writeFile(support::FileName const &) const;
191 /// \name Functions involved in reading files/strings.
193 /// Loads the LyX file into the buffer. This function
194 /// tries to extract the file from version control if it
195 /// cannot be found. If it can be found, it will try to
196 /// read an emergency save file or an autosave file.
197 /// \sa loadThisLyXFile
198 ReadStatus loadLyXFile();
199 /// Loads the LyX file \c fn into the buffer. If you want
200 /// to check for files in a version control container,
201 /// emergency or autosave files, one should use \c loadLyXFile.
203 ReadStatus loadThisLyXFile(support::FileName const & fn);
204 /// read a new document from a string
205 bool readString(std::string const &);
206 /// Reloads the LyX file
208 //FIXME: The following function should be private
210 /// read the header, returns number of unknown tokens
211 int readHeader(Lexer & lex);
215 typedef std::map<Buffer const *, Buffer *> BufferMap;
217 void clone(BufferMap &) const;
218 /// save timestamp and checksum of the given file.
219 void saveCheckSum() const;
221 ReadStatus readFile(support::FileName const & fn);
222 /// Reads a file without header.
223 /// \param par if != 0 insert the file.
224 /// \return \c true if file is not completely read.
225 bool readDocument(Lexer &);
226 /// Try to extract the file from a version control container
227 /// before reading if the file cannot be found. This is only
228 /// implemented for RCS.
229 /// \sa LyXVC::file_not_found_hook
230 ReadStatus extractFromVC();
231 /// Reads the first tag of a LyX File and
232 /// returns the file format number.
233 ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
234 int & file_format) const;
235 /// Convert the LyX file to the LYX_FORMAT using
236 /// the lyx2lyx script and returns the filename
237 /// of the temporary file to be read
238 ReadStatus convertLyXFormat(support::FileName const & fn,
239 support::FileName & tmpfile, int from_format);
243 /// \name Functions involved in autosave and emergency files.
245 /// Save an autosave file to #filename.lyx#
246 bool autoSave() const;
247 /// save emergency file
248 /// \return a status message towards the user.
249 docstring emergencyWrite();
251 //FIXME:The following function should be private
254 void removeAutosaveFile() const;
257 /// Try to load an autosave file associated to \c fn.
258 ReadStatus loadAutosave();
259 /// Try to load an emergency file associated to \c fn.
260 ReadStatus loadEmergency();
261 /// Get the filename of the emergency file associated with the Buffer
262 support::FileName getEmergencyFileName() const;
263 /// Get the filename of the autosave file associated with the Buffer
264 support::FileName getAutosaveFileName() const;
266 void moveAutosaveFile(support::FileName const & old) const;
270 /// Fill in the ErrorList with the TeXErrors
271 void bufferErrors(TeXErrors const &, ErrorList &) const;
273 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
274 bool makeLaTeXFile(support::FileName const & filename,
275 std::string const & original_path,
276 OutputParams const &,
277 bool output_preamble = true,
278 bool output_body = true) const;
279 /** Export the buffer to LaTeX.
280 If \p os is a file stream, and params().inputenc is "auto" or
281 "default", and the buffer contains text in different languages
282 with more than one encoding, then this method will change the
283 encoding associated to \p os. Therefore you must not call this
284 method with a string stream if the output is supposed to go to a
287 otexstream os(ofs, texrow);
288 ofs.open("test.tex");
289 writeLaTeXSource(os, ...);
291 \endcode is NOT equivalent to \code
292 odocstringstream oss;
293 otexstream os(oss, texrow);
294 writeLaTeXSource(os, ...);
296 ofs.open("test.tex");
301 void writeLaTeXSource(otexstream & os,
302 std::string const & original_path,
303 OutputParams const &,
304 bool output_preamble = true,
305 bool output_body = true) const;
307 void makeDocBookFile(support::FileName const & filename,
308 OutputParams const & runparams_in,
309 bool only_body = false) const;
311 void writeDocBookSource(odocstream & os, std::string const & filename,
312 OutputParams const & runparams_in,
313 bool only_body = false) const;
315 void makeLyXHTMLFile(support::FileName const & filename,
316 OutputParams const & runparams_in,
317 bool only_body = false) const;
319 void writeLyXHTMLSource(odocstream & os,
320 OutputParams const & runparams_in,
321 bool only_body = false) const;
322 /// returns the main language for the buffer (document)
323 Language const * language() const;
324 /// get l10n translated to the buffers language
325 docstring const B_(std::string const & l10n) const;
329 /// return true if the main lyx file does not need saving
330 bool isClean() const;
332 bool isDepClean(std::string const & name) const;
334 /// whether or not disk file has been externally modified
335 bool isExternallyModified(CheckMethod method) const;
337 /// mark the main lyx file as not needing saving
338 void markClean() const;
341 void markDepClean(std::string const & name);
344 void setUnnamed(bool flag = true);
346 /// Whether or not a filename has been assigned to this buffer
347 bool isUnnamed() const;
349 /// Whether or not this buffer is internal.
351 /// An internal buffer does not contain a real document, but some auxiliary text segment.
352 /// It is not associated with a filename, it is never saved, thus it does not need to be
353 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
354 bool isInternal() const;
356 /// Mark this buffer as dirty.
359 /// Returns the buffer's filename. It is always an absolute path.
360 support::FileName fileName() const;
362 /// Returns the buffer's filename. It is always an absolute path.
363 std::string absFileName() const;
365 /// Returns the the path where the buffer lives.
366 /// It is always an absolute path.
367 std::string filePath() const;
369 /** A transformed version of the file name, adequate for LaTeX.
370 \param no_path optional if \c true then the path is stripped.
372 std::string latexName(bool no_path = true) const;
374 /// Get the name and type of the log.
375 std::string logName(LogType * type = 0) const;
377 /// Set document's parent Buffer.
378 void setParent(Buffer const *);
379 Buffer const * parent() const;
381 /** Get the document's master (or \c this if this is not a
384 Buffer const * masterBuffer() const;
386 /// \return true if \p child is a child of this \c Buffer.
387 bool isChild(Buffer * child) const;
389 /// \return true if this \c Buffer has children
390 bool hasChildren() const;
392 /// \return a list of the direct children of this Buffer.
393 /// this list has no duplicates and is in the order in which
394 /// the children appear.
395 ListOfBuffers getChildren() const;
397 /// \return a list of all descendents of this Buffer (children,
398 /// grandchildren, etc). this list has no duplicates and is in
399 /// the order in which the children appear.
400 ListOfBuffers getDescendents() const;
402 /// Collect all relative buffers, in the order in which they appear.
403 /// I.e., the "root" Buffer is first, then its first child, then any
404 /// of its children, etc. However, there are no duplicates in this
406 /// This is "stable", too, in the sense that it returns the same
407 /// thing from whichever Buffer it is called.
408 ListOfBuffers allRelatives() const;
410 /// Is buffer read-only?
411 bool isReadonly() const;
413 /// Set buffer read-only flag
414 void setReadonly(bool flag = true);
416 /** Validate a buffer for LaTeX.
417 This validates the buffer, and returns a struct for use by
418 #makeLaTeX# and others. Its main use is to figure out what
419 commands and packages need to be included in the LaTeX file.
420 It (should) also check that the needed constructs are there
421 (i.e. that the \refs points to coresponding \labels). It
422 should perhaps inset "error" insets to help the user correct
425 void validate(LaTeXFeatures &) const;
427 /// Reference information is cached in the Buffer, so we do not
428 /// have to check or read things over and over.
430 /// There are two caches.
432 /// One is a cache of the BibTeX files from which reference info is
433 /// being gathered. This cache is PER BUFFER, and the cache for the
434 /// master essentially includes the cache for its children. This gets
435 /// invalidated when an InsetBibtex is created, deleted, or modified.
437 /// The other is a cache of the reference information itself. This
438 /// exists only in the master buffer, and when it needs to be updated,
439 /// the children add their information to the master's cache.
441 /// Calling this method invalidates the cache and so requires a
443 void invalidateBibinfoCache() const;
444 /// This invalidates the cache of files we need to check.
445 void invalidateBibfileCache() const;
446 /// Updates the cached bibliography information, checking first to see
447 /// whether the cache is valid. If so, we do nothing. If not, then we
448 /// reload all the BibTeX info.
449 /// Note that this operates on the master document.
450 void reloadBibInfoCache() const;
451 /// \return the bibliography information for this buffer's master,
452 /// or just for it, if it isn't a child.
453 BiblioInfo const & masterBibInfo() const;
454 /// collect bibliography info from the various insets in this buffer.
455 void collectBibKeys() const;
456 /// add some BiblioInfo to our cache
457 void addBiblioInfo(BiblioInfo const & bi) const;
458 /// add a single piece of bibliography info to our cache
459 void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
461 bool citeLabelsValid() const;
463 void getLabelList(std::vector<docstring> &) const;
466 void changeLanguage(Language const * from, Language const * to);
469 bool isMultiLingual() const;
471 std::set<Language const *> getLanguages() const;
474 BufferParams & params();
475 BufferParams const & params() const;
477 /** The list of paragraphs.
478 This is a linked list of paragraph, this list holds the
479 whole contents of the document.
481 ParagraphList & paragraphs();
482 ParagraphList const & paragraphs() const;
484 /// LyX version control object.
486 LyXVC const & lyxvc() const;
488 /// Where to put temporary files.
489 std::string const temppath() const;
491 /// Used when typesetting to place errorboxes.
492 TexRow const & texrow() const;
496 ParIterator par_iterator_begin();
498 ParConstIterator par_iterator_begin() const;
500 ParIterator par_iterator_end();
502 ParConstIterator par_iterator_end() const;
504 // Position of the child buffer where it appears first in the master.
505 DocIterator firstChildPosition(Buffer const * child);
507 /** \returns true only when the file is fully loaded.
508 * Used to prevent the premature generation of previews
509 * and by the citation inset.
511 bool isFullyLoaded() const;
512 /// Set by buffer_funcs' newFile.
513 void setFullyLoaded(bool);
515 /// Update the LaTeX preview snippets associated with this buffer
516 void updatePreviews() const;
517 /// Remove any previewed LaTeX snippets associated with this buffer
518 void removePreviews() const;
520 /// Our main text (inside the top InsetText)
523 /// Our top InsetText
524 Inset & inset() const;
529 /// Collect macro definitions in paragraphs
530 void updateMacros() const;
531 /// Iterate through the whole buffer and try to resolve macros
532 void updateMacroInstances(UpdateType) const;
534 /// List macro names of this buffer, the parent and the children
535 void listMacroNames(MacroNameSet & macros) const;
536 /// Collect macros of the parent and its children in front of this buffer.
537 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
539 /// Return macro defined before pos (or in the master buffer)
540 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
541 /// Return macro defined anywhere in the buffer (or in the master buffer)
542 MacroData const * getMacro(docstring const & name, bool global = true) const;
543 /// Return macro defined before the inclusion of the child
544 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
546 /// Collect user macro names at loading time
547 typedef std::set<docstring> UserMacroSet;
548 mutable UserMacroSet usermacros;
550 /// Replace the inset contents for insets which InsetCode is equal
551 /// to the passed \p inset_code.
552 void changeRefsIfUnique(docstring const & from, docstring const & to,
555 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
556 /// including preamble
557 void getSourceCode(odocstream & os, std::string const format,
558 pit_type par_begin, pit_type par_end, bool full_source) const;
560 /// Access to error list.
561 /// This method is used only for GUI visualisation of Buffer related
562 /// errors (like parsing or LateX compilation). This method is const
563 /// because modifying the returned ErrorList does not touch the document
565 ErrorList & errorList(std::string const & type) const;
568 /// This is useful only for screen visualisation of the Buffer. This
569 /// method is const because modifying this backend does not touch
570 /// the document contents.
571 TocBackend & tocBackend() const;
576 /// This function is called when the buffer is changed.
577 void changed(bool update_metrics) const;
579 void setChild(DocIterator const & dit, Buffer * child);
581 void updateTocItem(std::string const &, DocIterator const &) const;
582 /// This function is called when the buffer structure is changed.
583 void structureChanged() const;
584 /// This function is called when some parsing error shows up.
585 void errors(std::string const & err, bool from_master = false) const;
586 /// This function is called when the buffer busy status change.
587 void setBusy(bool on) const;
588 /// Update window titles of all users.
589 void updateTitles() const;
590 /// Reset autosave timers for all users.
591 void resetAutosaveTimers() const;
593 void message(docstring const & msg) const;
596 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
598 bool hasGuiDelegate() const;
603 bool doExport(std::string const & format, bool put_in_tempdir,
604 bool includeall, std::string & result_file) const;
606 bool doExport(std::string const & format, bool put_in_tempdir,
607 bool includeall = false) const;
609 bool preview(std::string const & format, bool includeall = false) const;
610 /// mark the buffer as busy exporting something, or not
611 void setExportStatus(bool e) const;
613 bool isExporting() const;
616 typedef std::vector<std::pair<Inset *, ParIterator> > References;
617 References & references(docstring const & label);
618 References const & references(docstring const & label) const;
619 void clearReferenceCache() const;
620 void setInsetLabel(docstring const & label, InsetLabel const * il);
621 InsetLabel const * insetLabel(docstring const & label) const;
623 /// return a list of all used branches (also in children)
624 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
626 /// sets the buffer_ member for every inset in this buffer.
627 // FIXME This really shouldn't be needed, but at the moment it's not
628 // clear how to do it just for the individual pieces we need.
629 void setBuffersForInsets() const;
630 /// Updates screen labels and some other information associated with
631 /// insets and paragraphs. Actually, it's more like a general "recurse
632 /// through the Buffer" routine, that visits all the insets and paragraphs.
633 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
634 /// \param scope: whether to start with the master document or just
636 /// \param output: whether we are preparing for output.
637 void updateBuffer(UpdateScope scope, UpdateType utype) const;
639 void updateBuffer(ParIterator & parit, UpdateType utype) const;
641 /// Spellcheck starting from \p from.
642 /// \p from initial position, will then points to the next misspelled
644 /// \p to will points to the end of the next misspelled word.
645 /// \p word_lang will contain the found misspelled word.
646 /// \return progress if a new word was found.
647 int spellCheck(DocIterator & from, DocIterator & to,
648 WordLangTuple & word_lang, docstring_list & suggestions) const;
650 void checkChildBuffers();
653 /// Change name of buffer. Updates "read-only" flag.
654 void setFileName(support::FileName const & fname);
656 void getLanguages(std::set<Language const *> &) const;
657 /// Checks whether any of the referenced bibfiles have changed since the
658 /// last time we loaded the cache. Note that this does NOT update the
659 /// cached information.
660 void checkIfBibInfoCacheIsValid() const;
661 /// Update the list of all bibfiles in use (including bibfiles
662 /// of loaded child documents).
663 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
664 /// Return the list with all bibfiles in use (including bibfiles
665 /// of loaded child documents).
666 support::FileNameList const &
667 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
669 void collectChildren(ListOfBuffers & children, bool grand_children) const;
672 /// Use the Pimpl idiom to hide the internals.
674 /// The pointer never changes although *pimpl_'s contents may.