Files

File Paths

Any Text object (eg: string) can be treated as if it were a path to a file on disk, eg: ‘/path/to/file.txt’. Each of the folder and file names in the path is called a component. The following Text object commands all work on file paths:

Text Object Commands (path additions)

.filePathComponents v1.1

Returns an array of all components in the path, eg: the path ‘/path/to/file.txt’ would return (‘/’, ‘path’, ‘to’, ‘file.txt’).

.lastFilePathComponent v1.1

The name of the last component in the path, eg: the path ‘/path/to/file.txt’ would return ‘file.txt’.

.lastFilePathComponentWithoutExtension v1.1

The name of the last component in the path, with the extension removed, if it had one, eg: the path ‘/path/to/file.txt’ would return ‘file’.

.filePathExtension v1.1

The file extension of the last path component, if it had one, eg: the path ‘/path/to/file.txt’ would return ‘txt’.

.abbreviatedFilePath v1.1

The full path, but with the tilde character (“~”) used to abbreviate the user’s home folder, eg: the path ‘/Users/SeniorOso/file.txt’ would return ‘~/file.txt’.

.expandedFilePath v1.1

The full path, but with the tilde character (“~”) expanded to be the user’s home folder, eg: the path ‘~/file.txt’ would return ‘/Users/SeniorOso/file.txt’.

.filePathByAppendingComponent name v1.1

Returns a new file path that is formed by appending the given component to the already existing path. This method takes care of adding the separator as necessary.

.filePathByRemovingLastComponent v1.1

Returns a new path with the last component of the existing path removed, eg: the path ‘/path/to/file.txt’ would return ‘/path/to’.

.filePathByChangingLastComponent component v2.0

Returns a new file path that is formed by deleting the last file component (file extension and all), and then appending a new one (which may or may not have an extension).

.filePathByChangingLastComponentName name v2.0

Returns a new file path that is formed by replacing the existing last file component’s name with the one given, leaving the original file extension intact.

.filePathByAppendingExtension extension v1.1

Returns a new file path that is formed by appending the given file extension to the already existing path. This method takes care of adding the separator as necessary.

.filePathByAppendingComponentNameSuffix suffix v2.0

Returns a new file path that is formed by appending the given suffix to the end of the last component’s name (inserting the give suffix before the existing extension, if one exists). 

For example: can easily change “path/name.txt” to “path/name-suffix.txt”.

.filePathByChangingExtension extension v1.2

Returns a new file path that is formed by removing the existing file extension and then appending a the new one, eg:

$name = 'Idée Fixe.txt'

$name = $name.filePathByChangingExtension('rtf')

# $name is now 'Idée Fixe.rtf'

File Path Example

The following code saves a copy of the active document to the same folder as the original, but with a “*” in the file name:

# Make sure there is an active document that has been saved once

$doc = Document.active

$hasDoc = Defined $doc

If ! $hasDoc

Prompt "There is no active document to backup."

Exit

End

$path = $doc.filePath

$hasPath = Defined $path

If ! $hasPath

Prompt "Cannot backup an unsaved document."

Exit

End


# construct the path to backup to

$currentName = $path.lastFilePathComponentWithoutExtension

$extension = $path.filePathExtension

$backupName = "$currentName*.$extension"


$folder = $path.filePathByRemovingLastComponent

$backupPath = $folder.filePathByAppendingComponent($backupName)

# save the document

$isSaved = Save To $backupPath

If ! $isSaved

Prompt "Failed to backup the document!"

End

File Object

The File object type commands allow inspecting and modifying files on disk. 

Under macOS sandboxing a macro will not have access to most files. Please see the section “Sandbox” for more.

File Type Commands

File.isEquivalentPaths path, otherPath v2.1.1

Returns @true if the file paths are equivalent, otherwise @false. Two paths are considered equivalent if they describe the same location. For example, if your macOS account user name is eskimo, then these are equivalent:

~/Documents/file.txt

/Users/eskimo/Documents/file.txt

Some other path normalizations are handled, like removing empty path components, but this does not include resolving aliases or symlinks in the path.

File.existsAtPath path v1.1

Returns @true if a file or folder exists at the given path, otherwise @false.

File.isFolderAtPath path v1.1

Returns @true if the file both exists and is a folder, otherwise @false.

File.canReadFromPath path v1.1

Returns @true if the file or folder exists and permissions allow data to be read from it, otherwise @false.

File.canWriteToPath path v1.1

Returns @true if the file or folder exists and permissions allow data to be written to it, otherwise @false.

File.canExecutePath path v1.3

Returns @true if the file exists and permissions allow it to be executed, otherwise @false.

File.namesInFolderAtPath path v1.1

Returns an array of the names of all files and subfolders contained inside the folder at the given path. This list does not include hidden files. If the given path is not a folder or does not exist, returns an empty array.

File.infoAtPath path v1.2

Returns a hash with various pieces of information about the file at the given path. The following pieces of information are set in the returned hash:


Hash Key

Hash Value

"size"

The size of the file, in bytes.

"creationDate"

A Date object for when the file was created.

"modificationDate"

A Date object for when the file was last modified.

"kind"

Returns a string that identifies what general kind of file exists at the path. This string is one of the following:

"file" = A regular file.
"folder" = A regular folder.
"link" = An alias or symlink.
"package" = A package file (a folder that is to be treated as single file, eg: application package).

This key was added in v1.3.

"hfsType"

A string version of the HFS file type, eg: “TEXT”. Note: not all files have HSF types, and some may have non-printing characters. This key was added in v1.3.

"hfsTypeInt"

An integer representation of the HFS file type. This key was added in v1.3.

"hfsCreator"

A string version of the HFS file creator, eg: “NISX”. Note: not all files have HSF creators, and some may have non-printing characters. This key was added in v1.3.

"hfsCreatorInt"

An integer representation of the HFS file creator. This key was added in v1.3.

If no file exists at the given path, the @undefined value is returned.

File.revealPathInFinder path v1.2

Shows and selects the file or folder at the given path in the Finder.

File.createFolderWithPath path v1.1

Creates a new folder at the given path. If any parent folders do not exist, they are also created. Returns @true if the folder was successfully created or the folder already exists, otherwise @false.

File.moveFromPathToPath sourcePath, destinationPath v1.2

Moves the file from the source path to the destination path. If the source is a folder then all files in that folder are copied to the destination (including all nested sub-folders). The destination must not exist. Returns @true if the move was a success, or @false on failure.

Note: this command can also be used to do simple file renames. In that case the folder for the source and destination paths is the same, only the last path component is different, eg:

File.moveFromPathToPath ‘~/Desktop/old.rtf’, ‘~/Desktop/new.rtf’

File.copyFromPathToPath sourcePath, destinationPath v1.1

Copies the file from the source path to the destination path. If the source is a folder then all files in that folder are copied to the destination (including all nested sub-folders). The destination must not exist. Returns @true if the copy was made, or @false on failure.

File.uniqueNameInFolderAtPath name, folderPath v2.0

Returns a possibly modified version of name, so that it is unique in the given folder. If the given folder does not exist, an error is displayed.

File.temporaryPathWithName name v1.1

Returns a full path to a unique temporary file that does not exist at the time the command was executed. The returned path will always have the same file extension as the given name, but the actual name might be different.

If your macro creates a file or folder at the returned location, your macro is also responsible for deleting it.

File.readDataFromPath path v1.1

Returns the contents of the file that exists at the specified path. The contents are read and returned as an uninterpreted Data object. Returns the @undefined value if the command fails.

File.writeDataToPath data, path v1.1

Overwrites the file at the specified path with the given data. If the file does not exist, then creates it. Any intermediate folders that do not exist are also created. Returns @true if the data was written, otherwise @false.

File.appendDataToPath data, path v1.1

Appends the given data to the file at the specified path. If the file does not exist, then creates it. Returns @true if the data was written, otherwise @false.

File.readStringFromPath path, [textEncodingName] v2.1.2

Returns the contents of the file as a plain text string, ignoring the file format. This command returns the @undefined value if the read fails. If you want to read the file as formatted text, use the Document object’s open commands instead. 

On input, the given textEncodingName is used to interpret the file’s data. This should be an IANA text encoding name. If the encoding argument is omitted (or is the empty string), then a text encoding is chosen automatically using a variety of factors (the file’s text encoding xattr, UTF byte order marks, etc).

If a textEncodingName is specified, then upon return it will be updated to contain the actual text encoding that was used to read the data. This allows you to know the encoding used to interpret the bytes. For example:

$encoding = ""

$text = File.readStringFromPath("~/Documents/file.txt", $encoding)

Prompt "Read the file using $encoding. The text:", $text

File.writeStringToPath string, path, [textEncodingName] v2.1.2

Overwrites the file at the specified path with a plain text string. If the file does not exist, then creates it. Any intermediate folders that do not exist are also created. Returns @true if the string was written, otherwise @false.

Optionally an IANA text encoding name may be given, which is used to convert the string to a sequence of bytes. This command returns @false if the string cannot be encoded using the given text encoding. If the encoding argument is omitted, a text encoding is chosen automatically. 

File.trashPath path v1.1

Move the file (or the contents of the entire folder) at the given path to the current users’ Trash folder. Returns @true on success, or @false if the move could not be completed.

File.deletePath path v1.1

Immediately deletes the file (or the contents of the entire folder) at the given path. This operation is not undoable and should be used with great care. Returns @true on success, or @false if the deletion could not be completed.

File.isLinkAtPath path v1.3

Returns @true if the file at the given path is an alias or symlink (symbolic link) file, otherwise returns @false.

File.resolveLinkAtPath path v1.3

If the file at the given path is an alias or symlink (symbolic link), returns the path of the targeted file. If the file is not an alias or symlink, returns the original/given path.

File.createAliasAtPathFromPath destinationPath, sourcePath v1.3

Creates an alias file at the given destination that points to the source file. The source file must exist and the destination must not. Returns @true if the alias was created or @false if not.

File.createSymlinkAtPathFromPath destinationPath, sourcePath v1.3

Creates a symlink (symbolic link file) at the given destination that points to the source file. The source file must exist and the destination must not. Returns @true if the link was created or @false if not.

The Mac Sandbox

As of version v2.1 Nisus Writer Pro runs inside the macOS sandbox, which by default does not permit an application to access any files outside its sandbox. By extension, macros also do not have access to any files outside the sandbox.

There are some ways in which a macro obtains implicit access to files outside the sandbox through user action. For example, when the user selects a file using any file selection commands (eg: Choose File, Choose Save File As, etc). But this access is temporary and is only guaranteed to last as long as the macro is running.

Automatic Access

As of version v2.1.1 the easiest way to grant all your macros permanent access to files and folders is the built-in macro:

Macro > Application > Manage Macro File Access

If you use this macro to grant access, access will be restored automatically by Nisus Writer for any and all subsequent macro execution, without the need for any macro code to explicitly use the commands below. This built-in macro also can list and rescind previously granted access.

Manual Access

Sometimes it may be necessary for a macro to explicitly request access to a file outside the sandbox and persist that access for subsequent runs. The following commands aid the macro author in manually managing that task.

File.requireAccessAtPath path v2.1

If a macro has never requested access to the file with the given path, this command will ask the user to select the file in a standard Open dialog. This will grant macros access to the file and also learn the given file path for later. Any subsequent uses of this command with the same path will automatically restore access to the file without interrupting the user.

If access to the file was not restored or granted, stops the macro.

File.learnAccessAtPath path, [isRestorationAutomatic] v2.1

If a macro already has access to the file with the given path, this command will learn the path so access can be restored using either File.requireAccessAtPath or File.restoreAccessAtPath.

If the optional argument isRestorationAutomatic is true then access will be restored automatically for any future macro execution, across all macros, without the need to use explicit commands like File.requireAccessAtPath. If this argument is not given, the default is false (not automatic). This argument was added for v2.1.1.

Returns @true if access to the file was learned, or @false if the macro does not have such access.

NOTE: in most cases this command is superfluous.

If you want all your macros to automatically always have access to a particular file or folder, it is easier to just use the built-in macro Macro > Application > Manage Macro File Access to grant that access.

If a macro needs to explicitly manually file access, it is still easier to use File.requireAccessAtPath.

File.restoreAccessAtPath path v2.1

If the given file path was learned previously using either the File.requireAccessAtPath or File.learnAccessAtPath commands, restores that access.

Returns @true if access to the file was restored, or @false if the path had not previously been learned (or the file no longer exists).

NOTE: in most cases this command is superfluous. It is easier to use just File.requireAccessAtPath.

File.forgetAccessAtPath path v2.1

Removes access to the file path learned previously using either the File.requireAccessAtPath or File.learnAccessAtPath commands.

Returns @true if access to the file path was forgotten, or @false if the file path had not previously been learned.

File.learnedAccessiblePaths [onlyAutomatic] v2.1

Returns an array of all paths to which access had been previously been learned.

If the optional argument onlyAutomatic is true then this only returns files to which access will be restored automatically by Nisus Writer for all subsequent macro execution. If this argument is not given, the default is false (return all files). This argument was added for v2.1.1.

NOTE: Nisus Writer Pro comes with a macro to help the user manage learned file paths. It lists all file paths that have been learned and allows the user to rescind access to any of them. By default it is located on the menu:

Macro > Application > Manage Macro File Access

Document Manager

The DocumentManager object provides a way to inspect the groups and files in the user’s Document Manager.

DocumentManager Type Commands

DocumentManager.instance v1.3

Returns the single shared DocumentManager object.

DocumentManager Commands

.isVisible v1.3

Returns @true if the Document Manager window is shown on screen, otherwise @false.

.allGroups v1.3

Return an array of DocumentManagerGroup objects, one for each group in the document manager.

.groupWithName name v1.3

Return the DocumentManagerGroup object with the given name, or the @undefined value if no such group exists.

.selectedGroups v1.3

Return an array of DocumentManagerGroup objects, one for each group selected in the Document Manager window.

.selectedFilePaths v1.3

Return an array of file paths, one for each file selected in the Document Manager window.

.addUserGroupWithName name v1.3

Adds a new empty group with the given name to the Document Manager, returning the new DocumentManagerGroup object. If the name is already in use this command does nothing and returns the @undefined value.

.addFolderGroupWithPath folderPath, [name] v1.3

Adds a new folder backed group to the Document Manager, returning the new DocumentManagerGroup object. If a group backed by the given folder already exists, then this command does nothing and returns the @undefined value. 

Optionally a name for the new group may be specified. If omitted the name of the folder is used and updates dynamically as the name changes on disk.

.removeGroup group v1.3

Permanently removes the given DocumentManagerGroup and all associated files from the Document Manager. Any files contained/listed in the group are left on disk, eg: no files are actually deleted.

Document Manager Group Object

DocumentManagerGroup objects collect together sets of files to display to the user.

DocumentManagerGroup Properties

.name v1.3

The name of the group, as displayed to the user. If the group is a folder backed group changing the name of the group has no effect on the name of the folder.

.groupType v1.3

A string indicating how the group is defined and behaves. Read-only. The return value is one of the following:


Returns

For Group Type

'folder'

Folder backed groups always contain exactly the files found in the backing folder on the file system.

'user'

User defined groups store alias records to arbitrary files found anywhere on the file system. Files can be added/removed from the group as the user pleases.

'search'

Search groups filter all managed files and display only those files that match the saved search criteria.

'special'

Special groups are those built-in to Nisus Writer with special behaviors, eg: Open Files or Style Library.

.allowsAddingFiles v1.3

Returns @true if arbitrary files can be added to the group using the addFilePath command, otherwise returns @false. Read-only.

.searchQuery v1.3

If the group is a search group returns the FileQuery object that is used to match files to be displayed in the group. If not a search group, returns the @undefined value. Read-only.

DocumentManagerGroup Commands

.allFilePaths v1.3

Returns an array of paths to all the files that should be displayed in the group. Not all of the returned files may exist and the order of the array is undefined.

Warning: Using this command may not be cheap. Especially if the group is a search group, then this command will start the search query and wait for it to complete, which can take some time. If you want to do other tasks while the search is running, check the searchQuery property and run the search manually.

.addFilePath path, [behavior] v1.3

Adds a file to the group. How the file is added to the group depends on the group type:


Group Type

Behavior

'folder'

By default the source file is moved to the destination backing folder. Optionally this command can take a second argument which is a string that specifies the behavior and should be either 'move', 'copy', or  'link'. Using the link behavior creates a symlink in the destination folder that points to the source file.

'user'

Will always capture an alias record for the added file.

'search'

You cannot add files to search groups and this command is ignored.

'special'

Some special groups allow adding files to them. Those that do are backed by a folder and also accept a second behavior string argument.

FileQuery Object

Specifies search criteria used to match/find files in the document manager.

FileQuery Commands

.startQuery v1.3

Starts running the search in the background. If a query is already running, this has no effect. To check the status of a started query use the isQueryFinished command.

.isQueryRunning v1.3

Returns @true if the previously started query is still underway, otherwise @false.

.stopQuery v1.3

Aborts any query that has not yet finished. Has no effect if a query is not currently running.

.matchingFilePaths v1.3

Returns an array of all file paths that have been found by the query. The array will be sorted and limited if that is specified by the search settings. The order of this array may change if the query is still running.

Note: using this command while a query is running may increase the time it takes to complete the query. Using matchingFileCount instead will not impact performance.

.matchingFileCount v1.3

Returns the number of files that have been found by the query so far.


Previous Chapter
Menus
<<  index  >>
 
Next Chapter
External Interaction