EditorFormattingAPIUpgrade

Revision as of 12:44, 19 August 2010 by Vstejskal (Talk | contribs)

Migrating Modules From The Old Formatting API

Contents


This page describes common situations that module owners are likely to encounter when migrating their modules from the old editor formatting API. Please note that the vast majority of Netbeans modules from trunk and contrib repositories has already been migrated and use the new formatting API. The few modules that still need to be migrated may find the information here useful.

If you are a module owner and have problems with rewriting your module and this page doesn't help you, please send a question to dev (at) editor (dot) netbeans (dot) org.

The code examples in the sections below that show the usage of the new formatting API may seem to be much more complex than the code snippets with the old formatting API code. This is because the new formatting API examples show the full and correct usage of the API including the locking mechanism. In fact if your old code was written correctly it must contain similar locking as well.


Getting a formatter/indenter for a document

  • Typical old API usage:
  BaseDocument doc = ...
  Formatter f = doc.getFormatter();
  f.reformat(...);
  • New API usage:
  BaseDocument doc = ...
  Reformat f = Reformat.get(doc);
  ...

  // Or when you just need to indent lines
  Indent i = Indent.get(doc);
  ...


Calculating the formatted area length

  • Typical old API usage:
  int formatLength = doc.getFormatter().reformat(doc, startOffset, endOffset);
  • New API usage:
  final int [] formatLength = new int[1];
  final Reformat reformat = Reformat.get(doc);
  reformat.lock();
  try {
    doc.runAtomic(new Runnable() {
      public void run() {
        try {
          Position endPos = doc.createPosition(endOffset);
          reformat.reformat(startOffset, endOffset);
          formatLength[0] = Math.max(0, endPos.getOffset() - startOffset);
        } catch (BadLocationException ble) {
          Exceptions.printStackTrace(ble);
        }
      }
    });
  } finally {
    reformat.unlock();
  }


Getting the caret offset for a new indented line

  • Typical old API usage:
int newCaretOffset = formatter.indentNewLine(doc, offset);
  • New API usage:
  final int [] newCaretOffset = new int[1];
  final Indent indenter = Indent.get(doc);
  indenter.lock();
  try {
    doc.runAtomic(new Runnable() {
      public void run() {
        try {
          newCaretOffset[0] = indenter.indentNewLine(offset);
        } catch (BadLocationException ble) {
          Exceptions.printStackTrace(ble);
        }
      }
    });
  } finally {
    indenter.unlock();
  }
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo