com.intellij.util.LineSeparator Java Examples

The following examples show how to use com.intellij.util.LineSeparator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiffUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static JComponent createSeparatorPanel(@Nonnull LineSeparator separator) {
  JLabel label = new JLabel(separator.name());
  Color color;
  if (separator == LineSeparator.CRLF) {
    color = JBColor.RED;
  }
  else if (separator == LineSeparator.LF) {
    color = JBColor.BLUE;
  }
  else if (separator == LineSeparator.CR) {
    color = JBColor.MAGENTA;
  }
  else {
    color = JBColor.BLACK;
  }
  label.setForeground(color);
  return label;
}
 
Example #2
Source File: HaxeCompilerServices.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
private int recalculateFileOffset(@NotNull PsiFile file, @NotNull PsiElement position, Editor editor) {
    int offset = position.getTextOffset();;

    VirtualFile virtualFile = file.getVirtualFile();
    if (null == virtualFile) {  // In memory file, the position doesn't change.
        return offset;
    }

    // Get the separator, checking the file if we don't know yet.  May still return null.
    String separator = LoadTextUtil.detectLineSeparator(virtualFile, true);

    // IntelliJ IDEA normalizes file line endings, so if file line endings is
    // CRLF - then we have to shift an offset so Haxe compiler could get proper offset
    if (LineSeparator.CRLF.getSeparatorString().equals(separator)) {
        int lineNumber =
            com.intellij.openapi.util.text.StringUtil.offsetToLineNumber(editor.getDocument().getText(), offset);
        offset += lineNumber;
    }
    return offset;
}
 
Example #3
Source File: StorageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static AsyncResult<VirtualFile> writeFileAsync(@Nullable File file,
                                                      @Nonnull Object requestor,
                                                      @Nullable final VirtualFile fileRef,
                                                      @Nonnull byte[] content,
                                                      @Nullable LineSeparator lineSeparatorIfPrependXmlProlog) {
  return AccessRule.writeAsync(() -> {
    VirtualFile virtualFile = fileRef;

    if (file != null && (virtualFile == null || !virtualFile.isValid())) {
      virtualFile = getOrCreateVirtualFile(requestor, file);
    }
    assert virtualFile != null;
    try (OutputStream out = virtualFile.getOutputStream(requestor)) {
      if (lineSeparatorIfPrependXmlProlog != null) {
        out.write(XML_PROLOG);
        out.write(lineSeparatorIfPrependXmlProlog.getSeparatorBytes());
      }
      out.write(content);
    }
    return virtualFile;
  });
}
 
Example #4
Source File: IoFileBasedStorage.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void doSave(@Nullable Element element) throws IOException {
  if (myLineSeparator == null) {
    myLineSeparator = isUseLfLineSeparatorByDefault() ? LineSeparator.LF : LineSeparator.getSystemLineSeparator();
  }

  byte[] content = element == null ? null : StorageUtil.writeToBytes(element, myLineSeparator.getSeparatorString());
  try {
    if (myStreamProvider != null && myStreamProvider.isEnabled()) {
      // stream provider always use LF separator
      saveForProvider(myLineSeparator == LineSeparator.LF ? content : null, element);
    }
  }
  catch (Throwable e) {
    LOG.error(e);
  }

  if (content == null) {
    StorageUtil.deleteFile(myFile);
  }
  else {
    FileUtil.createParentDirs(myFile);

    StorageUtil.writeFile(myFile, content, isUseXmlProlog() ? myLineSeparator : null);
  }
}
 
Example #5
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static DocumentContent createFromBytesImpl(@Nullable Project project,
                                                   @Nonnull byte[] content,
                                                   @Nonnull FileType fileType,
                                                   @Nonnull String fileName,
                                                   @javax.annotation.Nullable VirtualFile highlightFile,
                                                   @Nonnull Charset charset) {
  Charset bomCharset = CharsetToolkit.guessFromBOM(content);
  boolean isBOM = bomCharset != null;
  if (isBOM) charset = bomCharset;

  boolean malformedContent = false;
  String text = CharsetToolkit.tryDecodeString(content, charset);

  LineSeparator separator = StringUtil.detectSeparators(text);
  String correctedContent = StringUtil.convertLineSeparators(text);

  DocumentContent documentContent = createImpl(project, correctedContent, fileType, fileName, highlightFile, charset, isBOM, true, true);

  if (malformedContent) {
    String notificationText = "Content was decoded with errors (using " + "'" + charset.name() + "' charset)";
    DiffUtil.addNotification(DiffNotifications.createNotification(notificationText, LightColors.RED), documentContent);
  }

  return documentContent;
}
 
Example #6
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static DocumentContent createImpl(@javax.annotation.Nullable Project project,
                                          @Nonnull String text,
                                          @Nullable FileType fileType,
                                          @Nullable String fileName,
                                          @Nullable VirtualFile highlightFile,
                                          @javax.annotation.Nullable Charset charset,
                                          @javax.annotation.Nullable Boolean bom,
                                          boolean respectLineSeparators,
                                          boolean readOnly) {
  if (UnknownFileType.INSTANCE == fileType) fileType = PlainTextFileType.INSTANCE;

  // TODO: detect invalid (different across the file) separators ?
  LineSeparator separator = respectLineSeparators ? StringUtil.detectSeparators(text) : null;
  String correctedContent = StringUtil.convertLineSeparators(text);

  Document document = createDocument(project, correctedContent, fileType, fileName, readOnly);
  DocumentContent content = new DocumentContentImpl(project, document, fileType, highlightFile, separator, charset, bom);

  if (fileName != null) content.putUserData(DiffUserDataKeysEx.FILE_NAME, fileName);

  return content;
}
 
Example #7
Source File: DiffUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static JComponent createTitle(@Nonnull String title,
                                     @Nullable Charset charset,
                                     @Nullable LineSeparator separator,
                                     boolean readOnly) {
  if (readOnly) title += " " + DiffBundle.message("diff.content.read.only.content.title.suffix");

  JPanel panel = new JPanel(new BorderLayout());
  panel.setBorder(IdeBorderFactory.createEmptyBorder(0, 4, 0, 4));
  panel.add(new JBLabel(title).setCopyable(true), BorderLayout.CENTER);
  if (charset != null && separator != null) {
    JPanel panel2 = new JPanel();
    panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
    panel2.add(createCharsetPanel(charset));
    panel2.add(Box.createRigidArea(new Dimension(4, 0)));
    panel2.add(createSeparatorPanel(separator));
    panel.add(panel2, BorderLayout.EAST);
  }
  else if (charset != null) {
    panel.add(createCharsetPanel(charset), BorderLayout.EAST);
  }
  else if (separator != null) {
    panel.add(createSeparatorPanel(separator), BorderLayout.EAST);
  }
  return panel;
}
 
Example #8
Source File: DiffPanelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
static JComponent createComponentForTitle(@Nullable String title, @Nullable final LineSeparator sep1, @Nullable final LineSeparator sep2, boolean left) {
  if (sep1 != null && sep2 != null && !sep1.equals(sep2)) {
    LineSeparator separator = left ? sep1 : sep2;
    JPanel bottomPanel = new JPanel(new BorderLayout());
    JLabel sepLabel = new JLabel(separator.name());
    sepLabel.setForeground(separator.equals(LineSeparator.CRLF) ? JBColor.RED : JBColor.BLUE);
    bottomPanel.add(sepLabel, left ? BorderLayout.EAST : BorderLayout.WEST);

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(new JLabel(title == null ? "" : title));
    panel.add(bottomPanel, BorderLayout.SOUTH);
    return panel;
  }
  else {
    return new JBLabel(title == null ? "" : title);
  }
}
 
Example #9
Source File: LineEndingsManager.java    From editorconfig-jetbrains with MIT License 6 votes vote down vote up
private void applySettings(VirtualFile file) {
    if (file == null || !file.isInLocalFileSystem()) return;

    final String filePath = file.getCanonicalPath();
    final List<EditorConfig.OutPair> outPairs = SettingsProviderComponent.getInstance().getOutPairs(filePath);
    final String lineEndings = Utils.configValueForKey(outPairs, lineEndingsKey);
    if (!lineEndings.isEmpty()) {
        try {
            LineSeparator separator = LineSeparator.valueOf(lineEndings.toUpperCase(Locale.US));
            String oldSeparator = file.getDetectedLineSeparator();
            String newSeparator = separator.getSeparatorString();
            if (!StringUtil.equals(oldSeparator, newSeparator)) {
                file.setDetectedLineSeparator(newSeparator);
                if (!statusBarUpdated) {
                    statusBarUpdated = true;
                    updateStatusBar();
                }
                LOG.debug(Utils.appliedConfigMessage(lineEndings, lineEndingsKey, filePath));
            }
        } catch (IllegalArgumentException e) {
            LOG.warn(Utils.invalidConfigMessage(lineEndings, lineEndingsKey, filePath));
        }
    }
}
 
Example #10
Source File: LineSeparatorPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
protected WidgetState getWidgetState(@Nullable VirtualFile file) {
  if (file == null) {
    return WidgetState.HIDDEN;
  }
  String lineSeparator = LoadTextUtil.detectLineSeparator(file, true);
  if (lineSeparator == null) {
    return WidgetState.HIDDEN;
  }
  String toolTipText = String.format("Line Separator: %s", StringUtil.escapeLineBreak(lineSeparator));
  String panelText = LineSeparator.fromString(lineSeparator).toString();
  return new WidgetState(toolTipText, panelText, true);
}
 
Example #11
Source File: VirtualFileImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public String getDetectedLineSeparator() {
  if (getFlagInt(SYSTEM_LINE_SEPARATOR_DETECTED)) {
    return LineSeparator.getSystemLineSeparator().getSeparatorString();
  }
  return super.getDetectedLineSeparator();
}
 
Example #12
Source File: Platform.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
default LineSeparator getLineSeparator() {
  if(isWindows()) {
    return LineSeparator.CRLF;
  }
  return LineSeparator.LF;
}
 
Example #13
Source File: DiffPanelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void setFileContentsAreIdentical() {
  if (myTopMessageDiffPanel == null || myTopMessageDiffPanel instanceof FileContentsAreIdenticalDiffPanel) {
    LineSeparator sep1 = myData.getContent1() == null ? null : myData.getContent1().getLineSeparator();
    LineSeparator sep2 = myData.getContent2() == null ? null : myData.getContent2().getLineSeparator();

    if (LineSeparator.knownAndDifferent(sep1, sep2)) {
      myTopMessageDiffPanel = new LineSeparatorsOnlyDiffPanel();
    }
    else {
      myTopMessageDiffPanel = new FileContentsAreIdenticalDiffPanel();
    }
    myPanel.insertTopComponent(myTopMessageDiffPanel);
  }
}
 
Example #14
Source File: VfsFileBasedStorage.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doSave(@Nullable Element element) throws IOException {
  if (myLineSeparator == null) {
    myLineSeparator = isUseLfLineSeparatorByDefault() ? LineSeparator.LF : LineSeparator.getSystemLineSeparator();
  }

  byte[] content = element == null ? null : StorageUtil.writeToBytes(element, myLineSeparator.getSeparatorString());
  try {
    if (myStreamProvider != null && myStreamProvider.isEnabled()) {
      // stream provider always use LF separator
      saveForProvider(myLineSeparator == LineSeparator.LF ? content : null, element);
    }
  }
  catch (Throwable e) {
    LOG.error(e);
  }

  if (content == null) {
    StorageUtil.deleteFile(myFile, this, getVirtualFile());
    myCachedVirtualFile = null;
  }
  else {
    VirtualFile file = getVirtualFile();
    if (file == null || !file.exists()) {
      FileUtil.createParentDirs(myFile);
      file = null;
    }
    myCachedVirtualFile = StorageUtil.writeFile(myFile, this, file, content, isUseXmlProlog() ? myLineSeparator : null);
  }
}
 
Example #15
Source File: DiffPanelImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void setTitles(@Nonnull DiffRequest data) {
  LineSeparator sep1 = data.getContents()[0].getLineSeparator();
  LineSeparator sep2 = data.getContents()[1].getLineSeparator();

  String title1 = addReadOnly(data.getContentTitles()[0], myLeftSide.getEditor());
  String title2 = addReadOnly(data.getContentTitles()[1], myRightSide.getEditor());

  setTitle1(createComponentForTitle(title1, sep1, sep2, true));
  setTitle2(createComponentForTitle(title2, sep1, sep2, false));
}
 
Example #16
Source File: StorageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static LineSeparator detectLineSeparators(@Nonnull CharSequence chars, @Nullable LineSeparator defaultSeparator) {
  for (int i = 0, n = chars.length(); i < n; i++) {
    char c = chars.charAt(i);
    if (c == '\r') {
      return LineSeparator.CRLF;
    }
    else if (c == '\n') {
      // if we are here, there was no \r before
      return LineSeparator.LF;
    }
  }
  return defaultSeparator == null ? LineSeparator.getSystemLineSeparator() : defaultSeparator;
}
 
Example #17
Source File: AbstractConvertLineSeparatorsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void changeLineSeparators(@Nonnull final Project project,
                                        @Nonnull final VirtualFile virtualFile,
                                        @Nonnull final String newSeparator) {
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  Document document = fileDocumentManager.getCachedDocument(virtualFile);
  if (document != null) {
    fileDocumentManager.saveDocument(document);
  }

  String currentSeparator = LoadTextUtil.detectLineSeparator(virtualFile, false);
  final String commandText;
  if (StringUtil.isEmpty(currentSeparator)) {
    commandText = "Changed line separators to " + LineSeparator.fromString(newSeparator);
  }
  else {
    commandText = String.format("Changed line separators from %s to %s", LineSeparator.fromString(currentSeparator),
                                LineSeparator.fromString(newSeparator));
  }

  new WriteCommandAction(project, commandText) {
    @Override
    protected void run(@Nonnull Result result) throws Throwable {
      try {
        LoadTextUtil.changeLineSeparators(project, virtualFile, newSeparator, this);
      }
      catch (IOException e) {
        LOG.info(e);
      }
    }
  }.execute();
}
 
Example #18
Source File: StorageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void writeFile(@Nullable File file, @Nonnull byte[] content, @Nullable LineSeparator lineSeparatorIfPrependXmlProlog) throws IOException {
  try {

    try (OutputStream out = new FileOutputStream(file)) {
      if (lineSeparatorIfPrependXmlProlog != null) {
        out.write(XML_PROLOG);
        out.write(lineSeparatorIfPrependXmlProlog.getSeparatorBytes());
      }
      out.write(content);
    }
  }
  catch (FileNotFoundException e) {
    throw new ReadOnlyModificationException(file);
  }
}
 
Example #19
Source File: StorageUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static VirtualFile writeFile(@Nullable File file,
                                    @Nonnull Object requestor,
                                    @Nullable VirtualFile virtualFile,
                                    @Nonnull byte[] content,
                                    @Nullable LineSeparator lineSeparatorIfPrependXmlProlog) throws IOException {
  AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(StorageUtil.class);
  try {
    if (file != null && (virtualFile == null || !virtualFile.isValid())) {
      virtualFile = getOrCreateVirtualFile(requestor, file);
    }
    assert virtualFile != null;
    try (OutputStream out = virtualFile.getOutputStream(requestor)) {
      if (lineSeparatorIfPrependXmlProlog != null) {
        out.write(XML_PROLOG);
        out.write(lineSeparatorIfPrependXmlProlog.getSeparatorBytes());
      }
      out.write(content);
    }
    return virtualFile;
  }
  catch (FileNotFoundException e) {
    if (virtualFile == null) {
      throw e;
    }
    else {
      throw new ReadOnlyModificationException(file);
    }
  }
  finally {
    token.finish();
  }
}
 
Example #20
Source File: DiffUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static JComponent createTitle(@Nonnull String title,
                                      @Nonnull DiffContent content,
                                      boolean equalCharsets,
                                      boolean equalSeparators,
                                      @Nullable Editor editor) {
  if (content instanceof EmptyContent) return null;

  Charset charset = equalCharsets ? null : ((DocumentContent)content).getCharset();
  LineSeparator separator = equalSeparators ? null : ((DocumentContent)content).getLineSeparator();
  boolean isReadOnly = editor == null || editor.isViewer() || !canMakeWritable(editor.getDocument());

  return createTitle(title, charset, separator, isReadOnly);
}
 
Example #21
Source File: ExternalDiffToolUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static File createTempFile(@Nonnull final DocumentContent content, @Nonnull FileNameInfo fileName) throws IOException {
  FileDocumentManager.getInstance().saveDocument(content.getDocument());

  LineSeparator separator = content.getLineSeparator();
  if (separator == null) separator = LineSeparator.getSystemLineSeparator();

  Charset charset = content.getCharset();
  if (charset == null) charset = Charset.defaultCharset();

  Boolean hasBom = content.hasBom();
  if (hasBom == null) hasBom = CharsetToolkit.getMandatoryBom(charset) != null;

  ThrowableComputable<String,RuntimeException> action = () -> {
    return content.getDocument().getText();
  };
  String contentData = AccessRule.read(action);
  if (separator != LineSeparator.LF) {
    contentData = StringUtil.convertLineSeparators(contentData, separator.getSeparatorString());
  }

  byte[] bytes = contentData.getBytes(charset);

  byte[] bom = hasBom ? CharsetToolkit.getPossibleBom(charset) : null;
  if (bom != null) {
    bytes = ArrayUtil.mergeArrays(bom, bytes);
  }

  return createFile(bytes, fileName);
}
 
Example #22
Source File: DocumentContentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public DocumentContentImpl(@Nullable Project project,
                           @Nonnull Document document,
                           @javax.annotation.Nullable FileType type,
                           @javax.annotation.Nullable VirtualFile highlightFile,
                           @javax.annotation.Nullable LineSeparator separator,
                           @javax.annotation.Nullable Charset charset,
                           @Nullable Boolean bom) {
  myProject = project;
  myDocument = document;
  myType = type;
  myHighlightFile = highlightFile;
  mySeparator = separator;
  myCharset = charset;
  myBOM = bom;
}
 
Example #23
Source File: VirtualFileImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void setDetectedLineSeparator(String separator) {
  boolean hasSystemSeparator = LineSeparator.getSystemLineSeparator().getSeparatorString().equals(separator);
  setFlagInt(SYSTEM_LINE_SEPARATOR_DETECTED, hasSystemSeparator);
  super.setDetectedLineSeparator(hasSystemSeparator ? null : separator);
}
 
Example #24
Source File: ConvertToUnixLineSeparatorsAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ConvertToUnixLineSeparatorsAction() {
  super(ApplicationBundle.message("combobox.crlf.unix"), LineSeparator.LF);
}
 
Example #25
Source File: DocumentFragmentContent.java    From consulo with Apache License 2.0 4 votes vote down vote up
@javax.annotation.Nullable
@Override
public LineSeparator getLineSeparator() {
  return null;
}
 
Example #26
Source File: AbstractConvertLineSeparatorsAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected AbstractConvertLineSeparatorsAction(@Nullable String text, @Nonnull LineSeparator separator) {
  this(separator + " - " + text, separator.getSeparatorString());
}
 
Example #27
Source File: ConvertToWindowsLineSeparatorsAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ConvertToWindowsLineSeparatorsAction() {
  super(ApplicationBundle.message("combobox.crlf.windows"), LineSeparator.CRLF);
}
 
Example #28
Source File: ConvertToMacLineSeparatorsAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public ConvertToMacLineSeparatorsAction() {
  super(ApplicationBundle.message("combobox.crlf.mac"), LineSeparator.CR);
}
 
Example #29
Source File: FileDocumentContentImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@javax.annotation.Nullable
private static LineSeparator getSeparator(@Nonnull VirtualFile file) {
  String s = LoadTextUtil.detectLineSeparator(file, true);
  if (s == null) return null;
  return LineSeparator.fromString(s);
}
 
Example #30
Source File: DocumentContentImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public LineSeparator getLineSeparator() {
  return mySeparator;
}