summaryrefslogtreecommitdiff
path: root/xml/xml-psi-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/manipulators/XmlTextManipulator.java
blob: e160ba4c14dbc601347b358f4c1391e82b7562a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.psi.impl.source.resolve.reference.impl.manipulators;

import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.AbstractElementManipulator;
import com.intellij.psi.xml.XmlText;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

/**
 * @author Gregory.Shrago
 */
public class XmlTextManipulator extends AbstractElementManipulator<XmlText> {

  @Override
  public XmlText handleContentChange(@NotNull XmlText text, @NotNull TextRange range, String newContent) throws IncorrectOperationException {
    final String newValue;
    final String value = text.getValue();
    if (range.equals(getRangeInElement(text))) {
      newValue = newContent;
    }
    else {
      final StringBuilder replacement = new StringBuilder(value);
      replacement.replace(
        range.getStartOffset(),
        range.getEndOffset(),
        newContent
      );
      newValue = replacement.toString();
    }
    if (Comparing.equal(value, newValue)) return text;
    if (!newValue.isEmpty()) {
      text.setValue(newValue);
    }
    else {
      text.deleteChildRange(text.getFirstChild(), text.getLastChild());
    }
    //String oldText = text.getText();
    //((PsiLanguageInjectionHost)text).updateText(
    //  oldText.substring(0, range.getStartOffset()) + newContent + oldText.substring(range.getEndOffset()));
    return text;
  }

  @Override
  @NotNull
  public TextRange getRangeInElement(@NotNull final XmlText text) {
    return getValueRange(text);
  }

  private static TextRange getValueRange(final XmlText xmlText) {
    final String value = xmlText.getValue();
    final int i = value.indexOf(value);
    final int start = xmlText.displayToPhysical(i);
    return value.isEmpty() ? new TextRange(start, start) : new TextRange(start, xmlText.displayToPhysical(i + value.length() - 1) + 1);
  }
}