11/*******************************************************************************
2- * Copyright (c) 2000, 2021 IBM Corporation and others.
2+ * Copyright (c) 2000, 2024 IBM Corporation and others.
33 *
44 * This program and the accompanying materials
55 * are made available under the terms of the Eclipse Public License 2.0
4545
4646import org .eclipse .jface .viewers .ISelection ;
4747
48+ import org .eclipse .jface .text .BadLocationException ;
49+ import org .eclipse .jface .text .BadPartitioningException ;
50+ import org .eclipse .jface .text .IDocument ;
51+ import org .eclipse .jface .text .IDocumentExtension3 ;
4852import org .eclipse .jface .text .IRewriteTarget ;
4953import org .eclipse .jface .text .ITextOperationTarget ;
5054import org .eclipse .jface .text .ITextSelection ;
55+ import org .eclipse .jface .text .ITypedRegion ;
5156import org .eclipse .jface .text .Region ;
5257
5358import org .eclipse .ui .IEditorPart ;
8691import org .eclipse .jdt .ui .JavaUI ;
8792import org .eclipse .jdt .ui .PreferenceConstants ;
8893import org .eclipse .jdt .ui .actions .IJavaEditorActionDefinitionIds ;
94+ import org .eclipse .jdt .ui .text .IJavaPartitions ;
8995
9096import org .eclipse .jdt .internal .ui .IJavaStatusConstants ;
9197import org .eclipse .jdt .internal .ui .JavaPlugin ;
@@ -563,7 +569,9 @@ private void doPasteWithImportsOperation() {
563569 }
564570 try {
565571 fOperationTarget .doOperation (fOperationCode );
566- addImports ((ICompilationUnit )inputElement , importsData );
572+ if (!targetIsInString ()) {
573+ addImports ((ICompilationUnit )inputElement , importsData );
574+ }
567575 } catch (CoreException e ) {
568576 JavaPlugin .log (e );
569577 } finally {
@@ -579,6 +587,25 @@ private void doPasteWithImportsOperation() {
579587 }
580588 }
581589
590+ private boolean targetIsInString () {
591+ ITextEditor editor = getTextEditor ();
592+ IDocument document = editor .getDocumentProvider ().getDocument (editor .getEditorInput ());
593+ if (document != null ) {
594+ int offset = ((ITextSelection )editor .getSelectionProvider ().getSelection ()).getOffset ();
595+ try {
596+ IDocumentExtension3 extension = (IDocumentExtension3 ) document ;
597+ ITypedRegion region = extension .getPartition (IJavaPartitions .JAVA_PARTITIONING , offset , false );
598+ String partitionType = region .getType ();
599+ if (partitionType .equals (IJavaPartitions .JAVA_STRING ) ||
600+ partitionType .equals (IJavaPartitions .JAVA_MULTI_LINE_STRING )) {
601+ return true ;
602+ }
603+ } catch (BadLocationException | BadPartitioningException e ) {
604+ }
605+ }
606+ return false ;
607+ }
608+
582609 private void addImports (final ICompilationUnit unit , ClipboardData data ) throws CoreException {
583610 final ImportRewrite rewrite = StubUtility .createImportRewrite (unit , true );
584611 for (String type : data .getTypeImports ()) {
0 commit comments