]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
For Qt4.4 and up: Detach Buffer autosave into a new thread.
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <list>
24 #include <set>
25 #include <string>
26 #include <vector>
27
28
29 namespace lyx {
30
31 class BiblioInfo;
32 class BufferParams;
33 class BufferSet;
34 class DispatchResult;
35 class DocIterator;
36 class docstring_list;
37 class ErrorItem;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetRef;
43 class InsetLabel;
44 class Font;
45 class Format;
46 class Lexer;
47 class LyXRC;
48 class Text;
49 class LyXVC;
50 class LaTeXFeatures;
51 class Language;
52 class MacroData;
53 class MacroNameSet;
54 class MacroSet;
55 class OutputParams;
56 class Paragraph;
57 class ParConstIterator;
58 class ParIterator;
59 class ParagraphList;
60 class TeXErrors;
61 class TexRow;
62 class TocBackend;
63 class Undo;
64 class WordLangTuple;
65
66 namespace frontend {
67 class GuiBufferDelegate;
68 class WorkAreaManager;
69 }
70
71 namespace support {
72 class FileName;
73 class FileNameList;
74 }
75
76 /** The buffer object.
77  * This is the buffer object. It contains all the informations about
78  * a document loaded into LyX.
79  * The buffer object owns the Text (wrapped in an InsetText), which
80  * contains the individual paragraphs of the document.
81  *
82  *
83  * I am not sure if the class is complete or
84  * minimal, probably not.
85  * \author Lars Gullik Bjønnes
86  */
87 class Buffer {
88 public:
89         /// What type of log will \c getLogName() return?
90         enum LogType {
91                 latexlog, ///< LaTeX log
92                 buildlog  ///< Literate build log
93         };
94
95         /// Result of \c readFile()
96         enum ReadStatus {
97                 failure, ///< The file could not be read
98                 success, ///< The file could not be read
99                 wrongversion ///< The version of the file does not match ours
100         };
101
102
103         /// Method to check if a file is externally modified, used by
104         /// isExternallyModified()
105         /**
106          * timestamp is fast but inaccurate. For example, the granularity
107          * of timestamp on a FAT filesystem is 2 second. Also, various operations
108          * may touch the timestamp of a file even when its content is unchanged.
109          *
110          * checksum is accurate but slow, which can be a problem when it is
111          * frequently used, or used for a large file on a slow (network) file
112          * system.
113          *
114          * FIXME: replace this method with support/FileMonitor.
115          */
116         enum CheckMethod {
117                 checksum_method,  ///< Use file checksum
118                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
119         };
120
121         ///
122         enum UpdateScope {
123                 UpdateMaster,
124                 UpdateChildOnly
125         };
126
127         /// Constructor
128         explicit Buffer(std::string const & file, bool b = false);
129
130         /// Destructor
131         ~Buffer();
132
133         ///
134         Buffer * clone() const;
135
136         /** High-level interface to buffer functionality.
137             This function parses a command string and executes it.
138         */
139         void dispatch(std::string const & command, DispatchResult & result);
140
141         /// Maybe we know the function already by number...
142         void dispatch(FuncRequest const & func, DispatchResult & result);
143
144         /// Can this function be exectued?
145         /// \return true if we made a decision
146         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
147
148         /// read a new document from a string
149         bool readString(std::string const &);
150         /// load a new file
151         bool readFile(support::FileName const & filename);
152
153         /// read the header, returns number of unknown tokens
154         int readHeader(Lexer & lex);
155
156         /** Reads a file without header.
157             \param par if != 0 insert the file.
158             \return \c true if file is not completely read.
159         */
160         bool readDocument(Lexer &);
161
162         ///
163         DocIterator getParFromID(int id) const;
164         /// do we have a paragraph with this id?
165         bool hasParWithID(int id) const;
166
167         ///
168         frontend::WorkAreaManager & workAreaManager() const;
169
170         /** Save file.
171             Takes care of auto-save files and backup file if requested.
172             Returns \c true if the save is successful, \c false otherwise.
173         */
174         bool save() const;
175
176         /// Write document to stream. Returns \c false if unsuccesful.
177         bool write(std::ostream &) const;
178         /// save emergency file
179         /// \return a status message towards the user.
180         docstring emergencyWrite();
181         /// Write file. Returns \c false if unsuccesful.
182         bool writeFile(support::FileName const &) const;
183
184         /// Loads LyX file \c filename into buffer, *  and return success
185         bool loadLyXFile(support::FileName const & s);
186
187         /// Fill in the ErrorList with the TeXErrors
188         void bufferErrors(TeXErrors const &, ErrorList &) const;
189
190         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
191         bool makeLaTeXFile(support::FileName const & filename,
192                            std::string const & original_path,
193                            OutputParams const &,
194                            bool output_preamble = true,
195                            bool output_body = true) const;
196         /** Export the buffer to LaTeX.
197             If \p os is a file stream, and params().inputenc is "auto" or
198             "default", and the buffer contains text in different languages
199             with more than one encoding, then this method will change the
200             encoding associated to \p os. Therefore you must not call this
201             method with a string stream if the output is supposed to go to a
202             file. \code
203             ofdocstream ofs;
204             ofs.open("test.tex");
205             writeLaTeXSource(ofs, ...);
206             ofs.close();
207             \endcode is NOT equivalent to \code
208             odocstringstream oss;
209             writeLaTeXSource(oss, ...);
210             ofdocstream ofs;
211             ofs.open("test.tex");
212             ofs << oss.str();
213             ofs.close();
214             \endcode
215          */
216         void writeLaTeXSource(odocstream & os,
217                            std::string const & original_path,
218                            OutputParams const &,
219                            bool output_preamble = true,
220                            bool output_body = true) const;
221         ///
222         void makeDocBookFile(support::FileName const & filename,
223                              OutputParams const & runparams_in,
224                              bool only_body = false) const;
225         ///
226         void writeDocBookSource(odocstream & os, std::string const & filename,
227                              OutputParams const & runparams_in,
228                              bool only_body = false) const;
229         ///
230         void makeLyXHTMLFile(support::FileName const & filename,
231                              OutputParams const & runparams_in,
232                              bool only_body = false) const;
233         ///
234         void writeLyXHTMLSource(odocstream & os,
235                              OutputParams const & runparams_in,
236                              bool only_body = false) const;
237         /// returns the main language for the buffer (document)
238         Language const * language() const;
239         /// get l10n translated to the buffers language
240         docstring const B_(std::string const & l10n) const;
241
242         ///
243         int runChktex();
244         /// return true if the main lyx file does not need saving
245         bool isClean() const;
246         ///
247         bool isBakClean() const;
248         ///
249         bool isDepClean(std::string const & name) const;
250
251         /// whether or not disk file has been externally modified
252         bool isExternallyModified(CheckMethod method) const;
253
254         /// save timestamp and checksum of the given file.
255         void saveCheckSum(support::FileName const & file) const;
256
257         /// mark the main lyx file as not needing saving
258         void markClean() const;
259
260         ///
261         void markBakClean() const;
262
263         ///
264         void markDepClean(std::string const & name);
265
266         ///
267         void setUnnamed(bool flag = true);
268
269         /// Whether or not a filename has been assigned to this buffer
270         bool isUnnamed() const;
271
272         /// Whether or not this buffer is internal.
273         ///
274         /// An internal buffer does not contain a real document, but some auxiliary text segment.
275         /// It is not associated with a filename, it is never saved, thus it does not need to be
276         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
277         bool isInternal() const;
278
279         /// Mark this buffer as dirty.
280         void markDirty();
281
282         /// Returns the buffer's filename. It is always an absolute path.
283         support::FileName fileName() const;
284
285         /// Returns the buffer's filename. It is always an absolute path.
286         std::string absFileName() const;
287
288         /// Returns the the path where the buffer lives.
289         /// It is always an absolute path.
290         std::string filePath() const;
291
292         /** A transformed version of the file name, adequate for LaTeX.
293             \param no_path optional if \c true then the path is stripped.
294         */
295         std::string latexName(bool no_path = true) const;
296
297         /// Get the name and type of the log.
298         std::string logName(LogType * type = 0) const;
299
300         /// Change name of buffer. Updates "read-only" flag.
301         void setFileName(std::string const & newfile);
302
303         /// Set document's parent Buffer.
304         void setParent(Buffer const *);
305         Buffer const * parent() const;
306
307         // Collect all relative buffer
308         std::vector<Buffer const *> allRelatives() const;
309
310         /** Get the document's master (or \c this if this is not a
311             child document)
312          */
313         Buffer const * masterBuffer() const;
314
315         /// \return true if \p child is a child of this \c Buffer.
316         bool isChild(Buffer * child) const;
317         
318         /// return a vector with all children (and grandchildren)
319         std::vector<Buffer *> getChildren(bool grand_children = true) const;
320
321         /// Is buffer read-only?
322         bool isReadonly() const;
323
324         /// Set buffer read-only flag
325         void setReadonly(bool flag = true);
326
327         /// returns \c true if the buffer contains a LaTeX document
328         bool isLatex() const;
329         /// returns \c true if the buffer contains a DocBook document
330         bool isDocBook() const;
331         /// returns \c true if the buffer contains a Wed document
332         bool isLiterate() const;
333
334         /** Validate a buffer for LaTeX.
335             This validates the buffer, and returns a struct for use by
336             #makeLaTeX# and others. Its main use is to figure out what
337             commands and packages need to be included in the LaTeX file.
338             It (should) also check that the needed constructs are there
339             (i.e. that the \refs points to coresponding \labels). It
340             should perhaps inset "error" insets to help the user correct
341             obvious mistakes.
342         */
343         void validate(LaTeXFeatures &) const;
344
345         /// Update the cache with all bibfiles in use (including bibfiles
346         /// of loaded child documents).
347         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
348         ///
349         void invalidateBibinfoCache();
350         /// Return the cache with all bibfiles in use (including bibfiles
351         /// of loaded child documents).
352         support::FileNameList const & 
353                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
354         /// \return the bibliography information for this buffer's master,
355         /// or just for it, if it isn't a child.
356         BiblioInfo const & masterBibInfo() const;
357         /// \return the bibliography information for this buffer ONLY.
358         BiblioInfo const & localBibInfo() const;
359         ///
360         void getLabelList(std::vector<docstring> &) const;
361
362         ///
363         void changeLanguage(Language const * from, Language const * to);
364
365         ///
366         bool isMultiLingual() const;
367
368         ///
369         BufferParams & params();
370         BufferParams const & params() const;
371
372         /** The list of paragraphs.
373             This is a linked list of paragraph, this list holds the
374             whole contents of the document.
375          */
376         ParagraphList & paragraphs();
377         ParagraphList const & paragraphs() const;
378
379         /// LyX version control object.
380         LyXVC & lyxvc();
381         LyXVC const & lyxvc() const;
382
383         /// Where to put temporary files.
384         std::string const temppath() const;
385
386         /// Used when typesetting to place errorboxes.
387         TexRow const & texrow() const;
388         TexRow & texrow();
389
390         ///
391         ParIterator par_iterator_begin();
392         ///
393         ParConstIterator par_iterator_begin() const;
394         ///
395         ParIterator par_iterator_end();
396         ///
397         ParConstIterator par_iterator_end() const;
398
399         // Position of the child buffer where it appears first in the master.
400         DocIterator firstChildPosition(Buffer const * child);
401
402         /** \returns true only when the file is fully loaded.
403          *  Used to prevent the premature generation of previews
404          *  and by the citation inset.
405          */
406         bool isFullyLoaded() const;
407         /// Set by buffer_funcs' newFile.
408         void setFullyLoaded(bool);
409
410         /// Our main text (inside the top InsetText)
411         Text & text() const;
412
413         /// Our top InsetText
414         Inset & inset() const;
415
416         //
417         // Macro handling
418         //
419         /// Collect macro definitions in paragraphs
420         void updateMacros() const;
421         /// Iterate through the whole buffer and try to resolve macros
422         void updateMacroInstances() const;
423
424         /// List macro names of this buffer, the parent and the children
425         void listMacroNames(MacroNameSet & macros) const;
426         /// Collect macros of the parent and its children in front of this buffer.
427         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
428
429         /// Return macro defined before pos (or in the master buffer)
430         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
431         /// Return macro defined anywhere in the buffer (or in the master buffer)
432         MacroData const * getMacro(docstring const & name, bool global = true) const;
433         /// Return macro defined before the inclusion of the child
434         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
435
436         /// Collect user macro names at loading time
437         typedef std::set<docstring> UserMacroSet;
438         UserMacroSet usermacros;
439
440         /// Replace the inset contents for insets which InsetCode is equal
441         /// to the passed \p inset_code.
442         void changeRefsIfUnique(docstring const & from, docstring const & to,
443                 InsetCode code);
444
445         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
446         /// including preamble
447         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
448                 bool full_source) const;
449
450         /// Access to error list.
451         /// This method is used only for GUI visualisation of Buffer related
452         /// errors (like parsing or LateX compilation). This method is const
453         /// because modifying the returned ErrorList does not touch the document
454         /// contents.
455         ErrorList & errorList(std::string const & type) const;
456
457         /// The Toc backend.
458         /// This is useful only for screen visualisation of the Buffer. This
459         /// method is const because modifying this backend does not touch
460         /// the document contents.
461         TocBackend & tocBackend() const;
462
463         ///
464         Undo & undo();
465
466         /// This function is called when the buffer is changed.
467         void changed() const;
468         ///
469         void updateTocItem(std::string const &, DocIterator const &) const;
470         /// This function is called when the buffer structure is changed.
471         void structureChanged() const;
472         /// This function is called when some parsing error shows up.
473         void errors(std::string const & err, bool from_master = false) const;
474         /// This function is called when the buffer busy status change.
475         void setBusy(bool on) const;
476         /// This function is called when the buffer readonly status change.
477         void setReadOnly(bool on) const;
478         /// Update window titles of all users.
479         void updateTitles() const;
480         /// Reset autosave timers for all users.
481         void resetAutosaveTimers() const;
482         ///
483         void message(docstring const & msg) const;
484
485         ///
486         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
487         ///
488         bool hasGuiDelegate() const;
489
490         ///
491         void autoSave() const;
492         ///
493         void removeAutosaveFile() const;
494         ///
495         void moveAutosaveFile(support::FileName const & old) const;
496         ///
497         support::FileName getAutosaveFilename() const;
498
499         /// return the format of the buffer on a string
500         std::string bufferFormat() const;
501         /// return the default output format of the current backend
502         std::string getDefaultOutputFormat() const;
503
504         ///
505         bool doExport(std::string const & format, bool put_in_tempdir,
506                 std::string & result_file) const;
507         ///
508         bool doExport(std::string const & format, bool put_in_tempdir) const;
509         ///
510         bool preview(std::string const & format) const;
511         ///
512         bool isExportable(std::string const & format) const;
513         ///
514         std::vector<Format const *> exportableFormats(bool only_viewable) const;
515
516         ///
517         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
518         References & references(docstring const & label);
519         References const & references(docstring const & label) const;
520         void clearReferenceCache() const;
521         void setInsetLabel(docstring const & label, InsetLabel const * il);
522         InsetLabel const * insetLabel(docstring const & label) const;
523
524         /// return a list of all used branches (also in children)
525         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
526
527         /// sets the buffer_ member for every inset in this buffer.
528         // FIXME This really shouldn't be needed, but at the moment it's not
529         // clear how to do it just for the individual pieces we need.
530         void setBuffersForInsets() const;
531         /// Updates screen labels and some other information associated with
532         /// insets and paragraphs. Actually, it's more like a general "recurse
533         /// through the Buffer" routine, that visits all the insets and paragraphs.
534         void updateLabels() const { updateLabels(UpdateMaster, false); }
535         /// \param scope: whether to start with the master document or just
536         /// do this one.
537         /// \param output: whether we are preparing for output.
538         void updateLabels(UpdateScope scope, bool output) const;
539         /// 
540         void updateLabels(ParIterator & parit, bool output) const;
541
542         /// Spellcheck starting from \p from.
543         /// \p from initial position, will then points to the next misspelled
544         ///    word.
545         /// \p to will points to the end of the next misspelled word.
546         /// \p word_lang will contain the found misspelled word.
547         /// \return progress if a new word was found.
548         int spellCheck(DocIterator & from, DocIterator & to,
549                 WordLangTuple & word_lang, docstring_list & suggestions) const;
550
551 private:
552         /// search for macro in local (buffer) table or in children
553         MacroData const * getBufferMacro(docstring const & name,
554                                          DocIterator const & pos) const;
555         /** Update macro table starting with position of it
556             \param it in some text inset
557         */
558         void updateMacros(DocIterator & it,
559                                      DocIterator & scope) const;
560         ///
561         void setLabel(ParIterator & it) const;
562         ///
563         void collectRelatives(BufferSet & bufs) const;
564
565         ///
566         bool readFileHelper(support::FileName const & s);
567         ///
568         std::vector<std::string> backends() const;
569         /** Inserts a file into a document
570             \return \c false if method fails.
571         */
572         ReadStatus readFile(Lexer &, support::FileName const & filename,
573                             bool fromString = false);
574
575         /** If we have branches that use the file suffix
576             feature, return the file name with suffix appended.
577         */
578         support::FileName exportFileName() const;
579
580         /// Use the Pimpl idiom to hide the internals.
581         class Impl;
582         /// The pointer never changes although *pimpl_'s contents may.
583         Impl * const d;
584         ///
585         frontend::GuiBufferDelegate * gui_;
586
587         /// This function is called when the buffer structure is changed.
588         Signal structureChanged_;
589         /// This function is called when some parsing error shows up.
590         //Signal errors(std::string const &) = 0;
591         /// This function is called when some message shows up.
592         //Signal message(docstring const &) = 0;
593         /// This function is called when the buffer busy status change.
594         //Signal setBusy(bool) = 0;
595         /// Reset autosave timers for all users.
596         Signal resetAutosaveTimers_;
597 };
598
599
600 } // namespace lyx
601
602 #endif