Emacs Extensions for
GE Smallworld Magik Development

Screen-casts, tutorials, and productivity tools for Magik programmers who use Emacs. From tab-mode and code folding to the Magik Debugger and object inspector — explore features built by a developer, for developers.

Learn More
HydePark Consulting Screen-casts on YouTube RSS via FeedBurner

Nine screen-casts published between November 2010 and January 2011 — covering everything from ECB mode to the Tree Item GUI control. Read the story behind the project →

Get in Touch

Exporting Magik Collections to CSV with Emacs

Magik applications often hold their most useful evidence inside collections: records returned from a query, objects grouped by category, geometry summaries, or lists of values gathered during a debugging session. When that information stays inside the image, analysis can be slow and difficult to share. A CSV export creates a practical bridge between Magik, Emacs, spreadsheets, scripts, and reporting tools.

Emacs is well suited to this workflow because it can inspect the generated file, align fields, search large exports, and run small transformations without leaving the development environment. For teams working in Australian utilities, transport, planning, or asset management, this makes collection analysis easier to review across offices in Sydney, Melbourne, Brisbane, Perth, and regional locations.

Decide What the Collection Represents

Before exporting anything, establish whether the Magik collection contains simple values, objects, or nested collections. A list of strings can usually become one CSV column with little preparation. A collection of records needs a deliberate column model, such as id, status, owner, created_date, and geometry_type.

Object collections require a second decision: which attributes should be exported? Calling a broad inspection method may produce output that is useful at the Magik prompt but unsuitable for a spreadsheet. Select stable attributes with clear meanings and consistent types. For instance, an asset collection might expose its identifier, class name, operational state, and the date of the last inspection rather than every internal slot.

A useful export design is rectangular. Each row should describe one item, while each column should have a predictable heading. If a collection contains one-to-many data, consider a second CSV file instead of placing several values in one cell. This keeps filtering and later analysis reliable.

Inspect Values Inside Emacs

Emacs can act as the working surface for collection analysis. Paste a small Magik result into a buffer, use search commands to locate unusual values, and compare object representations before writing an exporter. Code folding is useful when a method contains several branches for different collection types; method navigation helps move between the collector and the formatting routine.

The Magik core features covered by Magik Emacs are particularly relevant here. An editor that understands Magik makes it easier to inspect methods, follow send chains, and debug the code that prepares each row. That reduces the risk of treating a display representation as though it were a stable data interface.

For large collections, inspect a sample first. Check empty values, duplicate identifiers, unexpected object classes, and fields containing commas or line breaks. A five-minute sample review can prevent a full export from producing thousands of misleading rows.

Build a Predictable Magik Exporter

A Magik exporter generally needs four stages: write the header, iterate over the collection, convert each field to text, and escape the resulting values. The exact collection iteration syntax depends on the Magik version and the collection class, so the routine should follow the conventions already used in the local codebase.

Conceptually, the routine looks like this:

_proc export_assets(collection, path)
  _local stream
  stream << write_file(path)
  stream.write("id,status,owner,updated_at\n")

  _loop
    _for asset _over collection.fast_elements()
    _loop
      stream.write(csv_row({
        asset.id,
        asset.status,
        asset.owner,
        asset.updated_at
      }))
    _endloop
  _endloop

  stream.close()
_endproc

The example is intentionally schematic. In a production method, use the project’s supported file API and collection traversal idiom. The important design is that csv_row receives field values rather than a pre-joined string. That gives one place to handle quoting, missing values, dates, and line endings.

Choose whether the exporter should preserve collection order. If users compare two files over time, deterministic ordering is valuable. Sorting by an identifier or business key makes differences easier to review in Emacs and reduces noise in versioned exports.

Escape CSV Fields Correctly

CSV is simple until a value contains a comma, quotation mark, carriage return, or newline. A safe field encoder converts the value to text, doubles every internal quotation mark, and surrounds the complete field with quotation marks when required. Many teams choose to quote every field because the rule is easy to test and produces consistent output.

The core transformation is:

value       -> text(value)
quotation   -> replace " with ""
field       -> "escaped value" when special characters exist

An empty Magik value needs an explicit policy. It may become an empty CSV field, the text NULL, or a controlled marker such as unknown. Pick one convention and document it. Empty strings and missing values often have different operational meanings, especially when a later process imports the file into a database.

Dates and numbers deserve equal care. Use an unambiguous date format such as ISO 8601, and avoid locale-dependent decimal formatting. A timestamp exported on a workstation configured for Australian conventions should still be understandable to a service running in UTC. If the data represents local time, include the offset or state the timezone in the export documentation.

Use Emacs CSV Tools for Review

Once the file is open in Emacs, activate CSV mode so fields can be aligned and navigated as columns. Alignment is helpful for a quick visual inspection, while narrowing the buffer or searching for a specific identifier keeps large exports manageable. CSV mode can also transpose fields, which is useful when a short collection summary is easier to read vertically.

Emacs is a good place to add lightweight validation. A keyboard macro or a small Emacs Lisp command can search for rows with the wrong number of separators, blank identifiers, or unexpected status values. This is valuable when a Magik method has been changed and the export is being used as a regression check.

For repeatable transformations, keep a small Emacs Lisp helper beside the project. It might open the latest export, remove temporary columns, sort records, or create a review buffer. Teams already using task and delivery tooling may find project tracking habits useful when assigning ownership for export checks, data fixes, and recurring reports.

Handle Australian Data Conditions

Australian organisations often move data between systems used by councils, utilities, engineering firms, and state agencies. A collection exported in Brisbane may be reviewed in Melbourne and loaded into a service hosted in Sydney. Define encoding, line endings, date formats, and timezone behaviour so the file does not change meaning as it crosses systems.

Privacy obligations matter when collections contain names, contact details, addresses, employee identifiers, or location information. The Privacy Act 1988 and the Australian Privacy Principles may apply depending on the organisation and the data involved. An export intended for debugging should use the minimum necessary fields, and sensitive values should be masked or removed before the file leaves a controlled environment.

Australian operational habits can affect the result as well. A team may open a CSV in Excel with regional settings that interpret dates or delimiters differently. Some users expect a comma-separated file, while a downstream process may prefer tab-separated text. State the delimiter and encoding in the handover notes, and test the file with the actual application used by the recipient.

For field assets, location data can be particularly sensitive. A road, water, rail, or electricity dataset may identify critical infrastructure. Store exports according to the organisation’s security policy, limit access, and remove files from temporary directories when analysis is complete.

Validate the Export Against Magik

Validation should compare the CSV with the source collection rather than relying on whether the file opens successfully. Count the source elements, count the output rows, and report records that fail conversion. A file can be syntactically valid while silently omitting objects or turning a failed attribute lookup into an empty field.

A practical validation report might include the collection size, rows written, rows skipped, duplicate keys, and the time of export. Write this information to a log or return it from the exporter so an operator can see what happened without examining the whole file.

Test special values deliberately. Include a name with an apostrophe, an address with a comma, a note containing a newline, and a value containing quotation marks. Add empty and very long strings as well. Open the result in Emacs CSV mode and in the target spreadsheet or import utility; both tests reveal different problems.

For collections containing database results, consider whether the export should represent the query snapshot or the current state of each object. A long-running export can cross transaction boundaries or encounter deleted records. If repeatability matters, record the query criteria, application version, database context, and export timestamp.

Automate Reusable Collection Analysis

Once a reliable row encoder and field policy exist, reuse them across collection types. A generic CSV writer can accept a header collection and a row-producing procedure. Specific exporters then decide which attributes to extract, while the shared writer handles quoting, encoding, file creation, and errors.

Keep exploratory commands separate from operational exports. A quick method written during debugging may be perfect for examining a collection at the Magik prompt, yet unsuitable for scheduled use. Production routines should validate their arguments, close files on failure, and avoid leaving partial files with the expected final name. Writing to a temporary path and renaming it after success prevents consumers from reading incomplete output.

Large collections may require batching. Instead of building every row in memory, write each row as it is processed and flush periodically according to the file API’s behaviour. This reduces memory pressure and provides a clear place to log progress. For an overnight export from a Perth or regional operations system, progress and failure reporting can be as important as the final CSV.

Finally, keep a small sample file under test. Whenever a Magik method, schema, or Emacs helper changes, run the exporter against that sample and compare the headings, row count, escaping, and representative values. A disciplined CSV workflow turns collection analysis from an ad hoc debugging trick into a dependable part of Magik development.

Add a tested exporter to your Magik toolkit, open its output in Emacs CSV mode, and document the fields, privacy handling, and validation checks your team uses. That small investment makes collection data easier to inspect, share, and trust.

Core Features

Tab Mode & ECB

Quick tab switching and Emacs Code Browsing mode for navigating Magik codebases efficiently.

Magik Smeller

Code analysis tool that helps identify potential issues in Magik source files.

Code Folding

Hide/Show mode for collapsing and expanding Magik code blocks to focus on what matters.

Visual Bookmarks

Quick visual bookmarks for jumping between key locations in your Smallworld session buffers.

Object Inspector

Inspect Magik objects and display them in an Emacs Deep Print buffer for detailed examination.

Magik Debugger

Set breakpoints and monitor slots and variables directly from within Emacs.

Development Tools

Direct links between Emacs and the Smallworld Development Tools application, including Click Monitor.

Screen-casts & Tutorials

Dark code editor window with syntax-highlighted Magik source code in muted blues and greys, conveying a focused development environment

Screen-cast 1: Tab Mode, ECB & More

Covers tab-mode, ECB, Magik Smeller, code folding, visual bookmarks, pragma toggling, moving code, external editor, and MS Explorer.

November 7, 2010
Split-pane Emacs interface with multiple buffers open, warm amber and navy tones against a dark background

Screen-cast 5: Object Inspection & Deep Print

Inspect a Magik object, prompt for an expression evaluated within a Smallworld session, and display results in a Deep Print buffer.

January 16, 2011
Debugging interface with breakpoint markers and variable watch panels in subdued teal and charcoal tones

Screen-cast 7: Magik Debugger

Useful tools for application developers: Object Inspector and Magik Debugger with breakpoints and slot/variable monitoring.

January 2011
Tree control GUI element with expandable branches rendered in clean greys and muted blues on a light background

Screen-cast 9: Tree Item GUI Control

Tree Item is a GUI control providing extensive facilities for displaying lists with rows, columns, trees, and in-place editing.

January 20, 2011