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 "update_flags.h"
18 #include "insets/InsetCode.h"
20 #include "support/strfwd.h"
21 #include "support/types.h"
22 #include "support/SignalSlot.h"
58 class ParConstIterator;
68 class GuiBufferDelegate;
69 class WorkAreaManager;
77 /** The buffer object.
78 * This is the buffer object. It contains all the informations about
79 * a document loaded into LyX.
80 * The buffer object owns the Text (wrapped in an InsetText), which
81 * contains the individual paragraphs of the document.
84 * I am not sure if the class is complete or
85 * minimal, probably not.
86 * \author Lars Gullik Bjønnes
90 /// What type of log will \c getLogName() return?
92 latexlog, ///< LaTeX log
93 buildlog ///< Literate build log
96 /// Result of \c readFile()
98 failure, ///< The file could not be read
99 success, ///< The file could not be read
100 wrongversion ///< The version of the file does not match ours
104 /// Method to check if a file is externally modified, used by
105 /// isExternallyModified()
107 * timestamp is fast but inaccurate. For example, the granularity
108 * of timestamp on a FAT filesystem is 2 second. Also, various operations
109 * may touch the timestamp of a file even when its content is unchanged.
111 * checksum is accurate but slow, which can be a problem when it is
112 * frequently used, or used for a large file on a slow (network) file
115 * FIXME: replace this method with support/FileMonitor.
118 checksum_method, ///< Use file checksum
119 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
129 explicit Buffer(std::string const & file, bool readonly = false,
130 Buffer const * cloned_buffer = 0);
136 Buffer * clone() const;
138 bool isClone() const;
140 /** High-level interface to buffer functionality.
141 This function parses a command string and executes it.
143 void dispatch(std::string const & command, DispatchResult & result);
145 /// Maybe we know the function already by number...
146 void dispatch(FuncRequest const & func, DispatchResult & result);
148 /// Can this function be exectued?
149 /// \return true if we made a decision
150 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
152 /// read a new document from a string
153 bool readString(std::string const &);
155 bool readFile(support::FileName const & filename);
157 /// read the header, returns number of unknown tokens
158 int readHeader(Lexer & lex);
160 /** Reads a file without header.
161 \param par if != 0 insert the file.
162 \return \c true if file is not completely read.
164 bool readDocument(Lexer &);
167 DocIterator getParFromID(int id) const;
168 /// do we have a paragraph with this id?
169 bool hasParWithID(int id) const;
172 frontend::WorkAreaManager & workAreaManager() const;
175 Takes care of auto-save files and backup file if requested.
176 Returns \c true if the save is successful, \c false otherwise.
180 /// Write document to stream. Returns \c false if unsuccesful.
181 bool write(std::ostream &) const;
182 /// save emergency file
183 /// \return a status message towards the user.
184 docstring emergencyWrite();
185 /// Write file. Returns \c false if unsuccesful.
186 bool writeFile(support::FileName const &) const;
188 /// Loads LyX file \c filename into buffer, * and return success
189 bool loadLyXFile(support::FileName const & s);
190 /// Reloads the LyX file
193 /// Fill in the ErrorList with the TeXErrors
194 void bufferErrors(TeXErrors const &, ErrorList &) const;
196 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
197 bool makeLaTeXFile(support::FileName const & filename,
198 std::string const & original_path,
199 OutputParams const &,
200 bool output_preamble = true,
201 bool output_body = true) const;
202 /** Export the buffer to LaTeX.
203 If \p os is a file stream, and params().inputenc is "auto" or
204 "default", and the buffer contains text in different languages
205 with more than one encoding, then this method will change the
206 encoding associated to \p os. Therefore you must not call this
207 method with a string stream if the output is supposed to go to a
210 ofs.open("test.tex");
211 writeLaTeXSource(ofs, ...);
213 \endcode is NOT equivalent to \code
214 odocstringstream oss;
215 writeLaTeXSource(oss, ...);
217 ofs.open("test.tex");
222 void writeLaTeXSource(odocstream & os,
223 std::string const & original_path,
224 OutputParams const &,
225 bool output_preamble = true,
226 bool output_body = true) const;
228 void makeDocBookFile(support::FileName const & filename,
229 OutputParams const & runparams_in,
230 bool only_body = false) const;
232 void writeDocBookSource(odocstream & os, std::string const & filename,
233 OutputParams const & runparams_in,
234 bool only_body = false) const;
236 void makeLyXHTMLFile(support::FileName const & filename,
237 OutputParams const & runparams_in,
238 bool only_body = false) const;
240 void writeLyXHTMLSource(odocstream & os,
241 OutputParams const & runparams_in,
242 bool only_body = false) const;
243 /// returns the main language for the buffer (document)
244 Language const * language() const;
245 /// get l10n translated to the buffers language
246 docstring const B_(std::string const & l10n) const;
250 /// return true if the main lyx file does not need saving
251 bool isClean() const;
253 bool isDepClean(std::string const & name) const;
255 /// whether or not disk file has been externally modified
256 bool isExternallyModified(CheckMethod method) const;
258 /// save timestamp and checksum of the given file.
259 void saveCheckSum(support::FileName const & file) const;
261 /// mark the main lyx file as not needing saving
262 void markClean() const;
265 void markDepClean(std::string const & name);
268 void setUnnamed(bool flag = true);
270 /// Whether or not a filename has been assigned to this buffer
271 bool isUnnamed() const;
273 /// Whether or not this buffer is internal.
275 /// An internal buffer does not contain a real document, but some auxiliary text segment.
276 /// It is not associated with a filename, it is never saved, thus it does not need to be
277 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
278 bool isInternal() const;
280 /// Mark this buffer as dirty.
283 /// Returns the buffer's filename. It is always an absolute path.
284 support::FileName fileName() const;
286 /// Returns the buffer's filename. It is always an absolute path.
287 std::string absFileName() const;
289 /// Returns the the path where the buffer lives.
290 /// It is always an absolute path.
291 std::string filePath() const;
293 /** A transformed version of the file name, adequate for LaTeX.
294 \param no_path optional if \c true then the path is stripped.
296 std::string latexName(bool no_path = true) const;
298 /// Get the name and type of the log.
299 std::string logName(LogType * type = 0) const;
301 /// Change name of buffer. Updates "read-only" flag.
302 void setFileName(std::string const & newfile);
304 /// Set document's parent Buffer.
305 void setParent(Buffer const *);
306 Buffer const * parent() const;
308 // Collect all relative buffer
309 std::vector<Buffer const *> allRelatives() const;
311 /** Get the document's master (or \c this if this is not a
314 Buffer const * masterBuffer() const;
316 /// \return true if \p child is a child of this \c Buffer.
317 bool isChild(Buffer * child) const;
319 /// return a vector with all children (and grandchildren)
320 std::vector<Buffer *> getChildren(bool grand_children = true) const;
322 /// Add all children (and grandchildren) to supplied vector
323 void getChildren(std::vector<Buffer *> & children, bool grand_children = true) const;
325 /// Is buffer read-only?
326 bool isReadonly() const;
328 /// Set buffer read-only flag
329 void setReadonly(bool flag = true);
331 /// returns \c true if the buffer contains a LaTeX document
332 bool isLatex() const;
333 /// returns \c true if the buffer contains a DocBook document
334 bool isDocBook() const;
335 /// returns \c true if the buffer contains a Wed document
336 bool isLiterate() const;
338 /** Validate a buffer for LaTeX.
339 This validates the buffer, and returns a struct for use by
340 #makeLaTeX# and others. Its main use is to figure out what
341 commands and packages need to be included in the LaTeX file.
342 It (should) also check that the needed constructs are there
343 (i.e. that the \refs points to coresponding \labels). It
344 should perhaps inset "error" insets to help the user correct
347 void validate(LaTeXFeatures &) const;
349 /// Update the list of all bibfiles in use (including bibfiles
350 /// of loaded child documents).
351 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
352 /// Return the list with all bibfiles in use (including bibfiles
353 /// of loaded child documents).
354 support::FileNameList const &
355 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
356 /// Information from BibTeX databases is cached in the Buffer, so
357 /// we do not have to read the file over and over.
358 /// Calling this method invalidates the cache and so requires a
360 void invalidateBibinfoCache();
361 /// Updates the cached bibliography information.
362 /// Note that you MUST call this method to update the cache. It will
363 /// not happen otherwise. (Currently, it is called at the start of
364 /// updateLabels() and from GuiCitation.)
365 void checkBibInfoCache() const;
366 /// \return the bibliography information for this buffer's master,
367 /// or just for it, if it isn't a child.
368 BiblioInfo const & masterBibInfo() const;
369 /// \return the bibliography information for this buffer ONLY.
370 BiblioInfo const & localBibInfo() const;
372 void getLabelList(std::vector<docstring> &) const;
375 void changeLanguage(Language const * from, Language const * to);
378 bool isMultiLingual() const;
381 BufferParams & params();
382 BufferParams const & params() const;
384 /** The list of paragraphs.
385 This is a linked list of paragraph, this list holds the
386 whole contents of the document.
388 ParagraphList & paragraphs();
389 ParagraphList const & paragraphs() const;
391 /// LyX version control object.
393 LyXVC const & lyxvc() const;
395 /// Where to put temporary files.
396 std::string const temppath() const;
398 /// Used when typesetting to place errorboxes.
399 TexRow const & texrow() const;
403 ParIterator par_iterator_begin();
405 ParConstIterator par_iterator_begin() const;
407 ParIterator par_iterator_end();
409 ParConstIterator par_iterator_end() const;
411 // Position of the child buffer where it appears first in the master.
412 DocIterator firstChildPosition(Buffer const * child);
414 /** \returns true only when the file is fully loaded.
415 * Used to prevent the premature generation of previews
416 * and by the citation inset.
418 bool isFullyLoaded() const;
419 /// Set by buffer_funcs' newFile.
420 void setFullyLoaded(bool);
422 /// Our main text (inside the top InsetText)
425 /// Our top InsetText
426 Inset & inset() const;
431 /// Collect macro definitions in paragraphs
432 void updateMacros() const;
433 /// Iterate through the whole buffer and try to resolve macros
434 void updateMacroInstances() const;
436 /// List macro names of this buffer, the parent and the children
437 void listMacroNames(MacroNameSet & macros) const;
438 /// Collect macros of the parent and its children in front of this buffer.
439 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
441 /// Return macro defined before pos (or in the master buffer)
442 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
443 /// Return macro defined anywhere in the buffer (or in the master buffer)
444 MacroData const * getMacro(docstring const & name, bool global = true) const;
445 /// Return macro defined before the inclusion of the child
446 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
448 /// Collect user macro names at loading time
449 typedef std::set<docstring> UserMacroSet;
450 UserMacroSet usermacros;
452 /// Replace the inset contents for insets which InsetCode is equal
453 /// to the passed \p inset_code.
454 void changeRefsIfUnique(docstring const & from, docstring const & to,
457 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
458 /// including preamble
459 void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
460 bool full_source) const;
462 /// Access to error list.
463 /// This method is used only for GUI visualisation of Buffer related
464 /// errors (like parsing or LateX compilation). This method is const
465 /// because modifying the returned ErrorList does not touch the document
467 ErrorList & errorList(std::string const & type) const;
470 /// This is useful only for screen visualisation of the Buffer. This
471 /// method is const because modifying this backend does not touch
472 /// the document contents.
473 TocBackend & tocBackend() const;
478 /// This function is called when the buffer is changed.
479 void changed(bool update_metrics) const;
481 void setChild(DocIterator const & dit, Buffer * child);
483 void updateTocItem(std::string const &, DocIterator const &) const;
484 /// This function is called when the buffer structure is changed.
485 void structureChanged() const;
486 /// This function is called when some parsing error shows up.
487 void errors(std::string const & err, bool from_master = false) const;
488 /// This function is called when the buffer busy status change.
489 void setBusy(bool on) const;
490 /// Update window titles of all users.
491 void updateTitles() const;
492 /// Reset autosave timers for all users.
493 void resetAutosaveTimers() const;
495 void message(docstring const & msg) const;
498 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
500 bool hasGuiDelegate() const;
503 void autoSave() const;
505 void removeAutosaveFile() const;
507 void moveAutosaveFile(support::FileName const & old) const;
509 support::FileName getAutosaveFilename() const;
511 /// return the format of the buffer on a string
512 std::string bufferFormat() const;
513 /// return the default output format of the current backend
514 std::string getDefaultOutputFormat() const;
517 bool doExport(std::string const & format, bool put_in_tempdir,
518 bool includeall, std::string & result_file) const;
520 bool doExport(std::string const & format, bool put_in_tempdir,
521 bool includeall = false) const;
523 bool preview(std::string const & format, bool includeall = false) const;
525 bool isExportable(std::string const & format) const;
527 std::vector<Format const *> exportableFormats(bool only_viewable) const;
529 bool isExportableFormat(std::string const & format) const;
532 typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
533 References & references(docstring const & label);
534 References const & references(docstring const & label) const;
535 void clearReferenceCache() const;
536 void setInsetLabel(docstring const & label, InsetLabel const * il);
537 InsetLabel const * insetLabel(docstring const & label) const;
539 /// return a list of all used branches (also in children)
540 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
542 /// sets the buffer_ member for every inset in this buffer.
543 // FIXME This really shouldn't be needed, but at the moment it's not
544 // clear how to do it just for the individual pieces we need.
545 void setBuffersForInsets() const;
546 /// Updates screen labels and some other information associated with
547 /// insets and paragraphs. Actually, it's more like a general "recurse
548 /// through the Buffer" routine, that visits all the insets and paragraphs.
549 void updateLabels() const { updateLabels(UpdateMaster, InternalUpdate); }
550 /// \param scope: whether to start with the master document or just
552 /// \param output: whether we are preparing for output.
553 void updateLabels(UpdateScope scope, UpdateType utype) const;
555 void updateLabels(ParIterator & parit, UpdateType utype) const;
557 /// Spellcheck starting from \p from.
558 /// \p from initial position, will then points to the next misspelled
560 /// \p to will points to the end of the next misspelled word.
561 /// \p word_lang will contain the found misspelled word.
562 /// \return progress if a new word was found.
563 int spellCheck(DocIterator & from, DocIterator & to,
564 WordLangTuple & word_lang, docstring_list & suggestions) const;
567 /// search for macro in local (buffer) table or in children
568 MacroData const * getBufferMacro(docstring const & name,
569 DocIterator const & pos) const;
570 /** Update macro table starting with position of it
571 \param it in some text inset
573 void updateMacros(DocIterator & it,
574 DocIterator & scope) const;
576 void setLabel(ParIterator & it, UpdateType utype) const;
578 void collectRelatives(BufferSet & bufs) const;
581 bool readFileHelper(support::FileName const & s);
583 std::vector<std::string> backends() const;
584 /** Inserts a file into a document
585 \return \c false if method fails.
587 ReadStatus readFile(Lexer &, support::FileName const & filename,
588 bool fromString = false);
590 /** If we have branches that use the file suffix
591 feature, return the file name with suffix appended.
593 support::FileName exportFileName() const;
595 /// Use the Pimpl idiom to hide the internals.
597 /// The pointer never changes although *pimpl_'s contents may.
600 frontend::GuiBufferDelegate * gui_;
602 /// This function is called when the buffer structure is changed.
603 Signal structureChanged_;
604 /// This function is called when some parsing error shows up.
605 //Signal errors(std::string const &) = 0;
606 /// This function is called when some message shows up.
607 //Signal message(docstring const &) = 0;
608 /// This function is called when the buffer busy status change.
609 //Signal setBusy(bool) = 0;
610 /// Reset autosave timers for all users.
611 Signal resetAutosaveTimers_;