id
int64
0
886
original_context
stringlengths
648
56.6k
modified_context
stringlengths
587
47.6k
omitted_context
sequencelengths
0
19
omitted_index
sequencelengths
0
19
metadata
dict
300
diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index cda03c0e89a47..62f492451b6f6 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -1981,10 +1981,23 @@ export default async function build( // check that dynamic pages won't error when they // enable PPR. else if (config.experimental.dynamicIO && isDynamic) { - prospectiveRenders.set(originalAppPath, { - page, - originalAppPath, - }) + // If there's a page with a more specific render + // available, then we should skip the prospective + // render because it'll be done as a part of the + // that render to validate the dynamic state. + if ( + // The existence of any prerendered routes when + // PPR is disabled means that the route has more + // specific prerendered routes that should be + // used for the diagnostic render anyways. + !workerResult.prerenderedRoutes || + workerResult.prerenderedRoutes.length === 0 + ) { + prospectiveRenders.set(originalAppPath, { + page, + originalAppPath, + }) + } } if (workerResult.prerenderedRoutes) {
diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index cda03c0e89a47..62f492451b6f6 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -1981,10 +1981,23 @@ export default async function build( // check that dynamic pages won't error when they // enable PPR. else if (config.experimental.dynamicIO && isDynamic) { - prospectiveRenders.set(originalAppPath, { - page, - }) + // If there's a page with a more specific render + // available, then we should skip the prospective + // that render to validate the dynamic state. + if ( + // The existence of any prerendered routes when + // PPR is disabled means that the route has more + // specific prerendered routes that should be + // used for the diagnostic render anyways. + workerResult.prerenderedRoutes.length === 0 + ) { + prospectiveRenders.set(originalAppPath, { + page, + originalAppPath, + }) + } } if (workerResult.prerenderedRoutes) {
[ "- originalAppPath,", "+ // render because it'll be done as a part of the", "+ !workerResult.prerenderedRoutes ||" ]
[ 10, 14, 21 ]
{ "additions": 17, "author": "wyattjoh", "deletions": 4, "html_url": "https://github.com/vercel/next.js/pull/78555", "issue_id": 78555, "merged_at": "2025-04-25T20:13:55Z", "omission_probability": 0.1, "pr_number": 78555, "repo": "vercel/next.js", "title": "refactor: skip the prospective render when there's a more specific route to be rendered", "total_changes": 21 }
301
diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index e1f11e713e665..cda03c0e89a47 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -387,13 +387,11 @@ export type RoutesManifest = { pages404: boolean basePath: string redirects: Array<Redirect> - rewrites?: - | Array<ManifestRewriteRoute> - | { - beforeFiles: Array<ManifestRewriteRoute> - afterFiles: Array<ManifestRewriteRoute> - fallback: Array<ManifestRewriteRoute> - } + rewrites: { + beforeFiles: Array<ManifestRewriteRoute> + afterFiles: Array<ManifestRewriteRoute> + fallback: Array<ManifestRewriteRoute> + } headers: Array<ManifestHeaderRoute> staticRoutes: Array<ManifestRoute> dynamicRoutes: Array<ManifestRoute> @@ -1345,6 +1343,11 @@ export default async function build( pathHeader: NEXT_REWRITTEN_PATH_HEADER, queryHeader: NEXT_REWRITTEN_QUERY_HEADER, }, + rewrites: { + beforeFiles: [], + afterFiles: [], + fallback: [], + }, skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize, ppr: isAppPPREnabled ? { @@ -1358,23 +1361,16 @@ export default async function build( } satisfies RoutesManifest }) - if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) { - routesManifest.rewrites = rewrites.afterFiles.map((r) => + routesManifest.rewrites = { + beforeFiles: rewrites.beforeFiles.map((r) => buildCustomRoute('rewrite', r) - ) - } else { - routesManifest.rewrites = { - beforeFiles: rewrites.beforeFiles.map((r) => - buildCustomRoute('rewrite', r) - ), - afterFiles: rewrites.afterFiles.map((r) => - buildCustomRoute('rewrite', r) - ), - fallback: rewrites.fallback.map((r) => - buildCustomRoute('rewrite', r) - ), - } + ), + afterFiles: rewrites.afterFiles.map((r) => + buildCustomRoute('rewrite', r) + ), + fallback: rewrites.fallback.map((r) => buildCustomRoute('rewrite', r)), } + let clientRouterFilters: | undefined | ReturnType<typeof createClientRouterFilter> diff --git a/packages/next/src/build/templates/pages-api.ts b/packages/next/src/build/templates/pages-api.ts index 20f74375a0146..2d9fbc5f263bc 100644 --- a/packages/next/src/build/templates/pages-api.ts +++ b/packages/next/src/build/templates/pages-api.ts @@ -1,12 +1,10 @@ import type { NextApiResponse } from '../../types' import type { IncomingMessage, ServerResponse } from 'node:http' +import { parse } from 'node:url' import { RouteKind } from '../../server/route-kind' import { sendError } from '../../server/api-utils' import { PagesAPIRouteModule } from '../../server/route-modules/pages-api/module.compiled' -import fs from 'node:fs' -import path from 'node:path' -import { parse } from 'node:url' import { hoist } from './helpers' @@ -31,6 +29,7 @@ import { import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path' import type { PrerenderManifest, RoutesManifest } from '..' +import { loadManifestFromRelativePath } from '../../server/load-manifest.external' // Re-export the handler (should be the default export). export default hoist(userland, 'default') @@ -51,19 +50,6 @@ const routeModule = new PagesAPIRouteModule({ userland, }) -const loadedManifests = new Map<string, any>() - -async function loadManifest(key: string, loader: () => Promise<any>) { - const cached = loadedManifests.get(key) - - if (cached) { - return cached - } - const currentManifest = await loader() - loadedManifests.set(key, currentManifest) - return currentManifest -} - export async function handler( req: IncomingMessage, res: ServerResponse, @@ -71,31 +57,22 @@ export async function handler( waitUntil?: (prom: Promise<void>) => void } ): Promise<void> { - const dir = + const projectDir = routerServerGlobal[RouterServerContextSymbol]?.dir || process.cwd() const distDir = process.env.__NEXT_RELATIVE_DIST_DIR || '' const isDev = process.env.NODE_ENV === 'development' - const routesManifest: RoutesManifest = await loadManifest( - ROUTES_MANIFEST, - async () => - JSON.parse( - await fs.promises.readFile( - path.join(dir, distDir, ROUTES_MANIFEST), - 'utf8' - ) - ) - ) - const prerenderManifest: PrerenderManifest = await loadManifest( - PRERENDER_MANIFEST, - async () => - JSON.parse( - await fs.promises.readFile( - path.join(dir, distDir, PRERENDER_MANIFEST), - 'utf8' - ) - ) + const routesManifest = await loadManifestFromRelativePath<RoutesManifest>( + projectDir, + distDir, + ROUTES_MANIFEST ) + const prerenderManifest = + await loadManifestFromRelativePath<PrerenderManifest>( + projectDir, + distDir, + PRERENDER_MANIFEST + ) let srcPage = 'VAR_DEFINITION_PAGE' // turbopack doesn't normalize `/index` in the page name @@ -131,13 +108,7 @@ export async function handler( page: srcPage, i18n, basePath, - rewrites: Array.isArray(rewrites) - ? { beforeFiles: [], afterFiles: rewrites, fallback: [] } - : rewrites || { - beforeFiles: [], - afterFiles: [], - fallback: [], - }, + rewrites, pageIsDynamic, trailingSlash: process.env.__NEXT_TRAILING_SLASH as any as boolean, caseSensitive: Boolean(routesManifest.caseSensitive), @@ -171,8 +142,7 @@ export async function handler( // ensure instrumentation is registered and pass // onRequestError below - const absoluteDistDir = path.join(dir, distDir) - await ensureInstrumentationRegistered(absoluteDistDir) + await ensureInstrumentationRegistered(projectDir, distDir) try { const method = req.method || 'GET' @@ -198,7 +168,7 @@ export async function handler( page: 'VAR_DEFINITION_PAGE', onError: (...args: Parameters<InstrumentationOnRequestError>) => - instrumentationOnRequestError(absoluteDistDir, ...args), + instrumentationOnRequestError(projectDir, distDir, ...args), }) .finally(() => { if (!span) return diff --git a/packages/next/src/server/dev/require-cache.ts b/packages/next/src/server/dev/require-cache.ts index 37454f62b69b8..9e7967def0f93 100644 --- a/packages/next/src/server/dev/require-cache.ts +++ b/packages/next/src/server/dev/require-cache.ts @@ -1,6 +1,6 @@ import isError from '../../lib/is-error' import { realpathSync } from '../../lib/realpath' -import { clearManifestCache } from '../load-manifest' +import { clearManifestCache } from '../load-manifest.external' export function deleteFromRequireCache(filePath: string) { try { diff --git a/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts b/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts index 6c19dfd47335e..fd78a673e6c9d 100644 --- a/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts +++ b/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts @@ -10,6 +10,7 @@ import { interopDefault } from '../../../lib/interop-default' let cachedInstrumentationModule: InstrumentationModule export async function getInstrumentationModule( + projectDir: string, distDir: string ): Promise<InstrumentationModule | undefined> { if (cachedInstrumentationModule && process.env.NODE_ENV === 'production') { @@ -19,7 +20,12 @@ export async function getInstrumentationModule( try { cachedInstrumentationModule = interopDefault( await require( - path.join(distDir, 'server', `${INSTRUMENTATION_HOOK_FILENAME}.js`) + path.join( + projectDir, + distDir, + 'server', + `${INSTRUMENTATION_HOOK_FILENAME}.js` + ) ) ) return cachedInstrumentationModule @@ -36,11 +42,11 @@ export async function getInstrumentationModule( } let instrumentationModulePromise: Promise<any> | null = null -async function registerInstrumentation(distDir: string) { +async function registerInstrumentation(projectDir: string, distDir: string) { // Ensure registerInstrumentation is not called in production build if (process.env.NEXT_PHASE === 'phase-production-build') return if (!instrumentationModulePromise) { - instrumentationModulePromise = getInstrumentationModule(distDir) + instrumentationModulePromise = getInstrumentationModule(projectDir, distDir) } const instrumentation = await instrumentationModulePromise if (instrumentation?.register) { @@ -54,10 +60,11 @@ async function registerInstrumentation(distDir: string) { } export async function instrumentationOnRequestError( + projectDir: string, distDir: string, ...args: Parameters<InstrumentationOnRequestError> ) { - const instrumentation = await getInstrumentationModule(distDir) + const instrumentation = await getInstrumentationModule(projectDir, distDir) try { await instrumentation?.onRequestError?.(...args) } catch (err) { @@ -67,9 +74,15 @@ export async function instrumentationOnRequestError( } let registerInstrumentationPromise: Promise<void> | null = null -export function ensureInstrumentationRegistered(distDir: string) { +export function ensureInstrumentationRegistered( + projectDir: string, + distDir: string +) { if (!registerInstrumentationPromise) { - registerInstrumentationPromise = registerInstrumentation(distDir) + registerInstrumentationPromise = registerInstrumentation( + projectDir, + distDir + ) } return registerInstrumentationPromise } diff --git a/packages/next/src/server/load-components.ts b/packages/next/src/server/load-components.ts index 00cfba7f2c2ba..83b9483e82eb8 100644 --- a/packages/next/src/server/load-components.ts +++ b/packages/next/src/server/load-components.ts @@ -27,7 +27,7 @@ import { requirePage } from './require' import { interopDefault } from '../lib/interop-default' import { getTracer } from './lib/trace/tracer' import { LoadComponentsSpan } from './lib/trace/constants' -import { evalManifest, loadManifest } from './load-manifest' +import { evalManifest, loadManifest } from './load-manifest.external' import { wait } from '../lib/wait' import { setReferenceManifestsSingleton } from './app-render/encryption-utils' import { createServerModuleMap } from './app-render/action-utils' diff --git a/packages/next/src/server/load-manifest.ts b/packages/next/src/server/load-manifest.external.ts similarity index 83% rename from packages/next/src/server/load-manifest.ts rename to packages/next/src/server/load-manifest.external.ts index 59a724e84b0e3..652d031925a20 100644 --- a/packages/next/src/server/load-manifest.ts +++ b/packages/next/src/server/load-manifest.external.ts @@ -1,5 +1,6 @@ import type { DeepReadonly } from '../shared/lib/deep-readonly' +import { join } from 'path' import { readFileSync } from 'fs' import { runInNewContext } from 'vm' import { deepFreeze } from '../shared/lib/deep-freeze' @@ -41,7 +42,9 @@ export function loadManifest<T extends object>( return cached as T } - let manifest = JSON.parse(readFileSync(path, 'utf8')) + let manifest = JSON.parse( + readFileSync(/* turbopackIgnore: true */ path, 'utf8') + ) // Freeze the manifest so it cannot be modified if we're caching it. if (shouldCache) { @@ -79,7 +82,7 @@ export function evalManifest<T extends object>( return cached as T } - const content = readFileSync(path, 'utf8') + const content = readFileSync(/* turbopackIgnore: true */ path, 'utf8') if (content.length === 0) { throw new Error('Manifest file is empty') } @@ -99,6 +102,20 @@ export function evalManifest<T extends object>( return contextObject as T } +export function loadManifestFromRelativePath<T extends object>( + projectDir: string, + distDir: string, + manifest: string, + shouldCache = true, + cache?: Map<string, unknown> +): DeepReadonly<T> { + return loadManifest<T>( + join(/* turbopackIgnore: true */ projectDir, distDir, manifest), + shouldCache, + cache + ) +} + export function clearManifestCache(path: string, cache = sharedCache): boolean { return cache.delete(path) } diff --git a/packages/next/src/server/load-manifest.test.ts b/packages/next/src/server/load-manifest.test.ts index 32e77fa81c8aa..5e79c061782ae 100644 --- a/packages/next/src/server/load-manifest.test.ts +++ b/packages/next/src/server/load-manifest.test.ts @@ -1,4 +1,4 @@ -import { loadManifest } from './load-manifest' +import { loadManifest } from './load-manifest.external' import { readFileSync } from 'fs' jest.mock('fs') diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index f0b47dd480b72..ab89dad6e3f5c 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -94,7 +94,7 @@ import { pipeToNodeResponse } from './pipe-readable' import { createRequestResponseMocks } from './lib/mock-request' import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers' import { signalFromNodeResponse } from './web/spec-extension/adapters/next-request' -import { loadManifest } from './load-manifest' +import { loadManifest } from './load-manifest.external' import { lazyRenderAppPage } from './route-modules/app-page/module.render' import { lazyRenderPagesPage } from './route-modules/pages/module.render' import { interopDefault } from '../lib/interop-default' diff --git a/packages/next/src/server/require.ts b/packages/next/src/server/require.ts index 23bfb9352df53..82f96fad6c3ad 100644 --- a/packages/next/src/server/require.ts +++ b/packages/next/src/server/require.ts @@ -10,7 +10,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils' import { LRUCache } from '../server/lib/lru-cache' -import { loadManifest } from './load-manifest' +import { loadManifest } from './load-manifest.external' import { promises } from 'fs' const isDev = process.env.NODE_ENV === 'development' diff --git a/packages/next/src/server/server-utils.ts b/packages/next/src/server/server-utils.ts index 25822ab35632e..3f24743a81d7f 100644 --- a/packages/next/src/server/server-utils.ts +++ b/packages/next/src/server/server-utils.ts @@ -25,6 +25,7 @@ import { import { normalizeNextQueryParam } from './web/utils' import type { IncomingHttpHeaders } from 'http' import { decodeQueryPathParameter } from './lib/decode-query-path-parameter' +import type { DeepReadonly } from '../shared/lib/deep-readonly' export function normalizeCdnUrl( req: BaseNextRequest, @@ -176,11 +177,11 @@ export function getUtils({ page: string i18n?: NextConfig['i18n'] basePath: string - rewrites: { + rewrites: DeepReadonly<{ fallback?: ReadonlyArray<Rewrite> afterFiles?: ReadonlyArray<Rewrite> beforeFiles?: ReadonlyArray<Rewrite> - } + }> pageIsDynamic: boolean trailingSlash?: boolean caseSensitive: boolean @@ -209,7 +210,7 @@ export function getUtils({ ) } - const checkRewrite = (rewrite: Rewrite): boolean => { + const checkRewrite = (rewrite: DeepReadonly<Rewrite>): boolean => { const matcher = getPathMatch( rewrite.source + (trailingSlash ? '(/)?' : ''), { @@ -227,8 +228,8 @@ export function getUtils({ const hasParams = matchHas( req, parsedUrl.query, - rewrite.has, - rewrite.missing + rewrite.has as Rewrite['has'], + rewrite.missing as Rewrite['missing'] ) if (hasParams) { diff --git a/test/integration/dynamic-routing/test/index.test.js b/test/integration/dynamic-routing/test/index.test.js index c7d6b9aa260cf..b6be113ce580c 100644 --- a/test/integration/dynamic-routing/test/index.test.js +++ b/test/integration/dynamic-routing/test/index.test.js @@ -1256,7 +1256,11 @@ function runTests({ dev }) { caseSensitive: false, basePath: '', headers: [], - rewrites: [], + rewrites: { + beforeFiles: [], + afterFiles: [], + fallback: [], + }, staticRoutes: [ { namedRegex: '^/(?:/)?$',
diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index e1f11e713e665..cda03c0e89a47 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -387,13 +387,11 @@ export type RoutesManifest = { pages404: boolean redirects: Array<Redirect> - | Array<ManifestRewriteRoute> - | { - beforeFiles: Array<ManifestRewriteRoute> - afterFiles: Array<ManifestRewriteRoute> - fallback: Array<ManifestRewriteRoute> - } + rewrites: { + beforeFiles: Array<ManifestRewriteRoute> + afterFiles: Array<ManifestRewriteRoute> + fallback: Array<ManifestRewriteRoute> + } headers: Array<ManifestHeaderRoute> staticRoutes: Array<ManifestRoute> dynamicRoutes: Array<ManifestRoute> @@ -1345,6 +1343,11 @@ export default async function build( pathHeader: NEXT_REWRITTEN_PATH_HEADER, queryHeader: NEXT_REWRITTEN_QUERY_HEADER, }, + rewrites: { + beforeFiles: [], + afterFiles: [], + fallback: [], + }, skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize, ppr: isAppPPREnabled ? { @@ -1358,23 +1361,16 @@ export default async function build( } satisfies RoutesManifest - if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) { - routesManifest.rewrites = rewrites.afterFiles.map((r) => + routesManifest.rewrites = { + beforeFiles: rewrites.beforeFiles.map((r) => buildCustomRoute('rewrite', r) - } else { - routesManifest.rewrites = { - beforeFiles: rewrites.beforeFiles.map((r) => - afterFiles: rewrites.afterFiles.map((r) => - fallback: rewrites.fallback.map((r) => - } + afterFiles: rewrites.afterFiles.map((r) => + buildCustomRoute('rewrite', r) } let clientRouterFilters: | undefined | ReturnType<typeof createClientRouterFilter> diff --git a/packages/next/src/build/templates/pages-api.ts b/packages/next/src/build/templates/pages-api.ts index 20f74375a0146..2d9fbc5f263bc 100644 --- a/packages/next/src/build/templates/pages-api.ts +++ b/packages/next/src/build/templates/pages-api.ts @@ -1,12 +1,10 @@ import type { NextApiResponse } from '../../types' import type { IncomingMessage, ServerResponse } from 'node:http' +import { parse } from 'node:url' import { RouteKind } from '../../server/route-kind' import { sendError } from '../../server/api-utils' import { PagesAPIRouteModule } from '../../server/route-modules/pages-api/module.compiled' -import fs from 'node:fs' -import path from 'node:path' -import { parse } from 'node:url' import { hoist } from './helpers' @@ -31,6 +29,7 @@ import { import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path' import type { PrerenderManifest, RoutesManifest } from '..' +import { loadManifestFromRelativePath } from '../../server/load-manifest.external' // Re-export the handler (should be the default export). export default hoist(userland, 'default') @@ -51,19 +50,6 @@ const routeModule = new PagesAPIRouteModule({ userland, }) -const loadedManifests = new Map<string, any>() -async function loadManifest(key: string, loader: () => Promise<any>) { - const cached = loadedManifests.get(key) - if (cached) { - return cached - const currentManifest = await loader() - loadedManifests.set(key, currentManifest) - return currentManifest -} export async function handler( req: IncomingMessage, res: ServerResponse, @@ -71,31 +57,22 @@ export async function handler( waitUntil?: (prom: Promise<void>) => void ): Promise<void> { - const dir = + const projectDir = routerServerGlobal[RouterServerContextSymbol]?.dir || process.cwd() const distDir = process.env.__NEXT_RELATIVE_DIST_DIR || '' const isDev = process.env.NODE_ENV === 'development' - const routesManifest: RoutesManifest = await loadManifest( - ROUTES_MANIFEST, - path.join(dir, distDir, ROUTES_MANIFEST), - ) - const prerenderManifest: PrerenderManifest = await loadManifest( - PRERENDER_MANIFEST, + const routesManifest = await loadManifestFromRelativePath<RoutesManifest>( + projectDir, + distDir, + ROUTES_MANIFEST ) + const prerenderManifest = + await loadManifestFromRelativePath<PrerenderManifest>( + distDir, let srcPage = 'VAR_DEFINITION_PAGE' // turbopack doesn't normalize `/index` in the page name @@ -131,13 +108,7 @@ export async function handler( page: srcPage, i18n, basePath, - rewrites: Array.isArray(rewrites) - ? { beforeFiles: [], afterFiles: rewrites, fallback: [] } - : rewrites || { - afterFiles: [], - fallback: [], - }, + rewrites, pageIsDynamic, trailingSlash: process.env.__NEXT_TRAILING_SLASH as any as boolean, caseSensitive: Boolean(routesManifest.caseSensitive), @@ -171,8 +142,7 @@ export async function handler( // ensure instrumentation is registered and pass // onRequestError below - const absoluteDistDir = path.join(dir, distDir) - await ensureInstrumentationRegistered(absoluteDistDir) + await ensureInstrumentationRegistered(projectDir, distDir) const method = req.method || 'GET' @@ -198,7 +168,7 @@ export async function handler( page: 'VAR_DEFINITION_PAGE', onError: (...args: Parameters<InstrumentationOnRequestError>) => - instrumentationOnRequestError(absoluteDistDir, ...args), + instrumentationOnRequestError(projectDir, distDir, ...args), .finally(() => { if (!span) return diff --git a/packages/next/src/server/dev/require-cache.ts b/packages/next/src/server/dev/require-cache.ts index 37454f62b69b8..9e7967def0f93 100644 --- a/packages/next/src/server/dev/require-cache.ts +++ b/packages/next/src/server/dev/require-cache.ts @@ -1,6 +1,6 @@ import isError from '../../lib/is-error' import { realpathSync } from '../../lib/realpath' -import { clearManifestCache } from '../load-manifest' +import { clearManifestCache } from '../load-manifest.external' export function deleteFromRequireCache(filePath: string) { diff --git a/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts b/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts index 6c19dfd47335e..fd78a673e6c9d 100644 --- a/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts +++ b/packages/next/src/server/lib/router-utils/instrumentation-globals.external.ts @@ -10,6 +10,7 @@ import { interopDefault } from '../../../lib/interop-default' let cachedInstrumentationModule: InstrumentationModule export async function getInstrumentationModule( distDir: string ): Promise<InstrumentationModule | undefined> { if (cachedInstrumentationModule && process.env.NODE_ENV === 'production') { @@ -19,7 +20,12 @@ export async function getInstrumentationModule( cachedInstrumentationModule = interopDefault( await require( + path.join( + projectDir, + distDir, + 'server', + `${INSTRUMENTATION_HOOK_FILENAME}.js` + ) ) return cachedInstrumentationModule @@ -36,11 +42,11 @@ export async function getInstrumentationModule( let instrumentationModulePromise: Promise<any> | null = null -async function registerInstrumentation(distDir: string) { +async function registerInstrumentation(projectDir: string, distDir: string) { // Ensure registerInstrumentation is not called in production build if (process.env.NEXT_PHASE === 'phase-production-build') return if (!instrumentationModulePromise) { - instrumentationModulePromise = getInstrumentationModule(distDir) + instrumentationModulePromise = getInstrumentationModule(projectDir, distDir) const instrumentation = await instrumentationModulePromise if (instrumentation?.register) { @@ -54,10 +60,11 @@ async function registerInstrumentation(distDir: string) { export async function instrumentationOnRequestError( distDir: string, ...args: Parameters<InstrumentationOnRequestError> ) { - const instrumentation = await getInstrumentationModule(distDir) + const instrumentation = await getInstrumentationModule(projectDir, distDir) await instrumentation?.onRequestError?.(...args) } catch (err) { @@ -67,9 +74,15 @@ export async function instrumentationOnRequestError( let registerInstrumentationPromise: Promise<void> | null = null -export function ensureInstrumentationRegistered(distDir: string) { +export function ensureInstrumentationRegistered( + distDir: string +) { if (!registerInstrumentationPromise) { - registerInstrumentationPromise = registerInstrumentation(distDir) + registerInstrumentationPromise = registerInstrumentation( + distDir return registerInstrumentationPromise diff --git a/packages/next/src/server/load-components.ts b/packages/next/src/server/load-components.ts index 00cfba7f2c2ba..83b9483e82eb8 100644 --- a/packages/next/src/server/load-components.ts +++ b/packages/next/src/server/load-components.ts @@ -27,7 +27,7 @@ import { requirePage } from './require' import { getTracer } from './lib/trace/tracer' import { LoadComponentsSpan } from './lib/trace/constants' -import { evalManifest, loadManifest } from './load-manifest' +import { evalManifest, loadManifest } from './load-manifest.external' import { wait } from '../lib/wait' import { setReferenceManifestsSingleton } from './app-render/encryption-utils' import { createServerModuleMap } from './app-render/action-utils' diff --git a/packages/next/src/server/load-manifest.ts b/packages/next/src/server/load-manifest.external.ts similarity index 83% rename from packages/next/src/server/load-manifest.ts rename to packages/next/src/server/load-manifest.external.ts index 59a724e84b0e3..652d031925a20 100644 --- a/packages/next/src/server/load-manifest.ts +++ b/packages/next/src/server/load-manifest.external.ts @@ -1,5 +1,6 @@ import type { DeepReadonly } from '../shared/lib/deep-readonly' +import { join } from 'path' import { runInNewContext } from 'vm' import { deepFreeze } from '../shared/lib/deep-freeze' @@ -41,7 +42,9 @@ export function loadManifest<T extends object>( - let manifest = JSON.parse(readFileSync(path, 'utf8')) + let manifest = JSON.parse( + readFileSync(/* turbopackIgnore: true */ path, 'utf8') // Freeze the manifest so it cannot be modified if we're caching it. if (shouldCache) { @@ -79,7 +82,7 @@ export function evalManifest<T extends object>( - const content = readFileSync(path, 'utf8') + const content = readFileSync(/* turbopackIgnore: true */ path, 'utf8') if (content.length === 0) { throw new Error('Manifest file is empty') @@ -99,6 +102,20 @@ export function evalManifest<T extends object>( return contextObject as T +export function loadManifestFromRelativePath<T extends object>( + distDir: string, + manifest: string, + shouldCache = true, + cache?: Map<string, unknown> +): DeepReadonly<T> { + return loadManifest<T>( + join(/* turbopackIgnore: true */ projectDir, distDir, manifest), + shouldCache, + cache +} export function clearManifestCache(path: string, cache = sharedCache): boolean { return cache.delete(path) diff --git a/packages/next/src/server/load-manifest.test.ts b/packages/next/src/server/load-manifest.test.ts index 32e77fa81c8aa..5e79c061782ae 100644 --- a/packages/next/src/server/load-manifest.test.ts +++ b/packages/next/src/server/load-manifest.test.ts @@ -1,4 +1,4 @@ jest.mock('fs') diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index f0b47dd480b72..ab89dad6e3f5c 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -94,7 +94,7 @@ import { pipeToNodeResponse } from './pipe-readable' import { createRequestResponseMocks } from './lib/mock-request' import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers' import { signalFromNodeResponse } from './web/spec-extension/adapters/next-request' import { lazyRenderAppPage } from './route-modules/app-page/module.render' import { lazyRenderPagesPage } from './route-modules/pages/module.render' diff --git a/packages/next/src/server/require.ts b/packages/next/src/server/require.ts index 23bfb9352df53..82f96fad6c3ad 100644 --- a/packages/next/src/server/require.ts +++ b/packages/next/src/server/require.ts @@ -10,7 +10,7 @@ import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-pa import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import { PageNotFoundError, MissingStaticPage } from '../shared/lib/utils' import { LRUCache } from '../server/lib/lru-cache' import { promises } from 'fs' const isDev = process.env.NODE_ENV === 'development' diff --git a/packages/next/src/server/server-utils.ts b/packages/next/src/server/server-utils.ts index 25822ab35632e..3f24743a81d7f 100644 --- a/packages/next/src/server/server-utils.ts +++ b/packages/next/src/server/server-utils.ts @@ -25,6 +25,7 @@ import { import { normalizeNextQueryParam } from './web/utils' import type { IncomingHttpHeaders } from 'http' import { decodeQueryPathParameter } from './lib/decode-query-path-parameter' +import type { DeepReadonly } from '../shared/lib/deep-readonly' export function normalizeCdnUrl( req: BaseNextRequest, @@ -176,11 +177,11 @@ export function getUtils({ page: string i18n?: NextConfig['i18n'] - rewrites: { + rewrites: DeepReadonly<{ fallback?: ReadonlyArray<Rewrite> afterFiles?: ReadonlyArray<Rewrite> beforeFiles?: ReadonlyArray<Rewrite> + }> pageIsDynamic: boolean trailingSlash?: boolean caseSensitive: boolean @@ -209,7 +210,7 @@ export function getUtils({ } - const checkRewrite = (rewrite: Rewrite): boolean => { + const checkRewrite = (rewrite: DeepReadonly<Rewrite>): boolean => { const matcher = getPathMatch( rewrite.source + (trailingSlash ? '(/)?' : ''), { @@ -227,8 +228,8 @@ export function getUtils({ const hasParams = matchHas( req, parsedUrl.query, - rewrite.has, - rewrite.missing + rewrite.has as Rewrite['has'], + rewrite.missing as Rewrite['missing'] ) if (hasParams) { diff --git a/test/integration/dynamic-routing/test/index.test.js b/test/integration/dynamic-routing/test/index.test.js index c7d6b9aa260cf..b6be113ce580c 100644 --- a/test/integration/dynamic-routing/test/index.test.js +++ b/test/integration/dynamic-routing/test/index.test.js @@ -1256,7 +1256,11 @@ function runTests({ dev }) { caseSensitive: false, basePath: '', headers: [], - rewrites: [], + beforeFiles: [], + afterFiles: [], + fallback: [], + }, staticRoutes: [ { namedRegex: '^/(?:/)?$',
[ "- rewrites?:", "+ fallback: rewrites.fallback.map((r) => buildCustomRoute('rewrite', r)),", "- path.join(dir, distDir, PRERENDER_MANIFEST),", "+ PRERENDER_MANIFEST", "- beforeFiles: [],", "- path.join(distDir, 'server', `${INSTRUMENTATION_HOOK_FILENAME}.js`)", "+ rewrites: {" ]
[ 8, 61, 138, 151, 163, 218, 432 ]
{ "additions": 88, "author": "ijjk", "deletions": 87, "html_url": "https://github.com/vercel/next.js/pull/78358", "issue_id": 78358, "merged_at": "2025-04-25T18:35:54Z", "omission_probability": 0.1, "pr_number": 78358, "repo": "vercel/next.js", "title": "Externalize manifest loading in pages-api", "total_changes": 175 }
302
diff --git a/turbopack/crates/turbopack-core/src/resolve/pattern.rs b/turbopack/crates/turbopack-core/src/resolve/pattern.rs index d44575028a55f..6abf9dde68bf7 100644 --- a/turbopack/crates/turbopack-core/src/resolve/pattern.rs +++ b/turbopack/crates/turbopack-core/src/resolve/pattern.rs @@ -122,9 +122,11 @@ impl Pattern { } } + /// Whether the pattern has any significant constant parts (everything except `/`). + /// E.g. `<dynamic>/<dynamic>` doesn't really have constant parts pub fn has_constant_parts(&self) -> bool { match self { - Pattern::Constant(_) => true, + Pattern::Constant(str) => str != "/", Pattern::Dynamic => false, Pattern::Alternatives(list) | Pattern::Concatenation(list) => { list.iter().any(|p| p.has_constant_parts()) diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs index ad05241f498ba..f0c0d47bacbe6 100644 --- a/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs +++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs @@ -697,14 +697,11 @@ impl Visit for Analyzer<'_> { // we could actually unwrap thanks to the optimisation above but it can't hurt to be safe... if let Some(comments) = self.comments { let callee_span = match &n.callee { - Callee::Import(Import { span, .. }) => Some(span), - Callee::Expr(box Expr::Ident(Ident { span, sym, .. })) if sym == "require" => { - Some(span) - } + Callee::Import(Import { span, .. }) => Some(*span), + Callee::Expr(e) => Some(e.span()), _ => None, }; - // we are interested here in the last comment with a valid directive let ignore_directive = parse_ignore_directive(comments, n.args.first()); if let Some((callee_span, ignore_directive)) = callee_span.zip(ignore_directive) { diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs index 6cef454f24274..41fb93371d285 100644 --- a/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs @@ -1820,7 +1820,7 @@ impl JsValue { "The Node.js process.cwd method: https://nodejs.org/api/process.html#processcwd", ), WellKnownFunctionKind::NodePreGypFind => ( - "find".to_string(), + "binary.find".to_string(), "The Node.js @mapbox/node-pre-gyp module: https://github.com/mapbox/node-pre-gyp", ), WellKnownFunctionKind::NodeGypBuild => ( diff --git a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs index 435af2b74add5..d5fcf4375117d 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs @@ -1312,7 +1312,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( let func = analysis_state .link_value( JsValue::member(Box::new(obj.clone()), Box::new(prop)), - ImportAttributes::empty_ref(), + eval_context.imports.get_attributes(span), ) .await?; @@ -2875,7 +2875,7 @@ async fn value_visitor_inner( ), _, ) => { - // TODO: figure out how to do static analysis without invalidating the while + // TODO: figure out how to do static analysis without invalidating the whole // analysis when a new file gets added v.into_unknown( true, @@ -2903,6 +2903,20 @@ async fn value_visitor_inner( v.into_unknown(true, "new non constant") } } + JsValue::WellKnownFunction( + WellKnownFunctionKind::PathJoin + | WellKnownFunctionKind::PathResolve(_) + | WellKnownFunctionKind::FsReadMethod(_), + ) => { + if ignore { + return Ok(( + JsValue::unknown(v, true, "ignored well known function"), + true, + )); + } else { + return Ok((v, false)); + } + } JsValue::FreeVar(ref kind) => match &**kind { "__dirname" => as_abs_path(origin.origin_path().parent()).await?, "__filename" => as_abs_path(origin.origin_path()).await?, diff --git a/turbopack/crates/turbopack-ecmascript/src/utils.rs b/turbopack/crates/turbopack-ecmascript/src/utils.rs index 2e83eb5a654dd..d6547b6e7cb0a 100644 --- a/turbopack/crates/turbopack-ecmascript/src/utils.rs +++ b/turbopack/crates/turbopack-ecmascript/src/utils.rs @@ -184,7 +184,9 @@ pub fn module_value_to_well_known_object(module_value: &ModuleValue) -> Option<J } "node:os" | "os" => JsValue::WellKnownObject(WellKnownObjectKind::OsModule), "node:process" | "process" => JsValue::WellKnownObject(WellKnownObjectKind::NodeProcess), - "@mapbox/node-pre-gyp" => JsValue::WellKnownObject(WellKnownObjectKind::NodePreGyp), + "node-pre-gyp" | "@mapbox/node-pre-gyp" => { + JsValue::WellKnownObject(WellKnownObjectKind::NodePreGyp) + } "node-gyp-build" => JsValue::WellKnownFunction(WellKnownFunctionKind::NodeGypBuild), "node:bindings" | "bindings" => { JsValue::WellKnownFunction(WellKnownFunctionKind::NodeBindings) diff --git a/turbopack/crates/turbopack/src/lib.rs b/turbopack/crates/turbopack/src/lib.rs index ddbb07d5bf82d..22d3095a1820e 100644 --- a/turbopack/crates/turbopack/src/lib.rs +++ b/turbopack/crates/turbopack/src/lib.rs @@ -668,6 +668,9 @@ async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleA Ok(ModuleAssetContext::new_without_replace_externals( Default::default(), CompileTimeInfo::builder(env).cell().await?, + // Keep these options more or less in sync with + // turbopack/crates/turbopack/tests/node-file-trace.rs to ensure that the NFT unit tests + // are actually representative of what Turbopack does. ModuleOptionsContext { ecmascript: EcmascriptOptionsContext { source_maps: SourceMapsType::None,
diff --git a/turbopack/crates/turbopack-core/src/resolve/pattern.rs b/turbopack/crates/turbopack-core/src/resolve/pattern.rs index d44575028a55f..6abf9dde68bf7 100644 --- a/turbopack/crates/turbopack-core/src/resolve/pattern.rs +++ b/turbopack/crates/turbopack-core/src/resolve/pattern.rs @@ -122,9 +122,11 @@ impl Pattern { } + /// Whether the pattern has any significant constant parts (everything except `/`). + /// E.g. `<dynamic>/<dynamic>` doesn't really have constant parts pub fn has_constant_parts(&self) -> bool { match self { - Pattern::Constant(_) => true, + Pattern::Constant(str) => str != "/", Pattern::Dynamic => false, Pattern::Alternatives(list) | Pattern::Concatenation(list) => { list.iter().any(|p| p.has_constant_parts()) diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs index ad05241f498ba..f0c0d47bacbe6 100644 --- a/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs +++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/imports.rs @@ -697,14 +697,11 @@ impl Visit for Analyzer<'_> { // we could actually unwrap thanks to the optimisation above but it can't hurt to be safe... if let Some(comments) = self.comments { let callee_span = match &n.callee { - Callee::Import(Import { span, .. }) => Some(span), - Some(span) - } + Callee::Import(Import { span, .. }) => Some(*span), + Callee::Expr(e) => Some(e.span()), _ => None, }; - // we are interested here in the last comment with a valid directive let ignore_directive = parse_ignore_directive(comments, n.args.first()); if let Some((callee_span, ignore_directive)) = callee_span.zip(ignore_directive) { diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs index 6cef454f24274..41fb93371d285 100644 --- a/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs @@ -1820,7 +1820,7 @@ impl JsValue { "The Node.js process.cwd method: https://nodejs.org/api/process.html#processcwd", WellKnownFunctionKind::NodePreGypFind => ( + "binary.find".to_string(), "The Node.js @mapbox/node-pre-gyp module: https://github.com/mapbox/node-pre-gyp", WellKnownFunctionKind::NodeGypBuild => ( diff --git a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs index 435af2b74add5..d5fcf4375117d 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs @@ -1312,7 +1312,7 @@ pub(crate) async fn analyse_ecmascript_module_internal( let func = analysis_state .link_value( JsValue::member(Box::new(obj.clone()), Box::new(prop)), - ImportAttributes::empty_ref(), + eval_context.imports.get_attributes(span), ) .await?; @@ -2875,7 +2875,7 @@ async fn value_visitor_inner( ), _, ) => { - // TODO: figure out how to do static analysis without invalidating the while + // TODO: figure out how to do static analysis without invalidating the whole // analysis when a new file gets added v.into_unknown( true, @@ -2903,6 +2903,20 @@ async fn value_visitor_inner( v.into_unknown(true, "new non constant") } + JsValue::WellKnownFunction( + WellKnownFunctionKind::PathJoin + | WellKnownFunctionKind::PathResolve(_) + | WellKnownFunctionKind::FsReadMethod(_), + ) => { + if ignore { + return Ok(( + JsValue::unknown(v, true, "ignored well known function"), + true, + )); + } else { + return Ok((v, false)); + } JsValue::FreeVar(ref kind) => match &**kind { "__dirname" => as_abs_path(origin.origin_path().parent()).await?, "__filename" => as_abs_path(origin.origin_path()).await?, diff --git a/turbopack/crates/turbopack-ecmascript/src/utils.rs b/turbopack/crates/turbopack-ecmascript/src/utils.rs index 2e83eb5a654dd..d6547b6e7cb0a 100644 --- a/turbopack/crates/turbopack-ecmascript/src/utils.rs +++ b/turbopack/crates/turbopack-ecmascript/src/utils.rs @@ -184,7 +184,9 @@ pub fn module_value_to_well_known_object(module_value: &ModuleValue) -> Option<J "node:os" | "os" => JsValue::WellKnownObject(WellKnownObjectKind::OsModule), "node:process" | "process" => JsValue::WellKnownObject(WellKnownObjectKind::NodeProcess), - "@mapbox/node-pre-gyp" => JsValue::WellKnownObject(WellKnownObjectKind::NodePreGyp), + JsValue::WellKnownObject(WellKnownObjectKind::NodePreGyp) "node-gyp-build" => JsValue::WellKnownFunction(WellKnownFunctionKind::NodeGypBuild), "node:bindings" | "bindings" => { JsValue::WellKnownFunction(WellKnownFunctionKind::NodeBindings) diff --git a/turbopack/crates/turbopack/src/lib.rs b/turbopack/crates/turbopack/src/lib.rs index ddbb07d5bf82d..22d3095a1820e 100644 --- a/turbopack/crates/turbopack/src/lib.rs +++ b/turbopack/crates/turbopack/src/lib.rs @@ -668,6 +668,9 @@ async fn externals_tracing_module_context(ty: ExternalType) -> Result<Vc<ModuleA Ok(ModuleAssetContext::new_without_replace_externals( Default::default(), CompileTimeInfo::builder(env).cell().await?, + // turbopack/crates/turbopack/tests/node-file-trace.rs to ensure that the NFT unit tests + // are actually representative of what Turbopack does. ModuleOptionsContext { ecmascript: EcmascriptOptionsContext { source_maps: SourceMapsType::None,
[ "- Callee::Expr(box Expr::Ident(Ident { span, sym, .. })) if sym == \"require\" => {", "- \"find\".to_string(),", "+ \"node-pre-gyp\" | \"@mapbox/node-pre-gyp\" => {", "+ // Keep these options more or less in sync with" ]
[ 26, 46, 103, 117 ]
{ "additions": 28, "author": "mischnic", "deletions": 10, "html_url": "https://github.com/vercel/next.js/pull/78460", "issue_id": 78460, "merged_at": "2025-04-25T17:49:33Z", "omission_probability": 0.1, "pr_number": 78460, "repo": "vercel/next.js", "title": "Turbopack: support ignore comments for NFT fs access tracing", "total_changes": 38 }
303
diff --git a/docs/01-app/02-guides/production-checklist.mdx b/docs/01-app/02-guides/production-checklist.mdx index 3a25354a9fcc2..0c330c6415fad 100644 --- a/docs/01-app/02-guides/production-checklist.mdx +++ b/docs/01-app/02-guides/production-checklist.mdx @@ -18,7 +18,7 @@ These Next.js optimizations are enabled by default and require no configuration: - **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. - **[Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Static Rendering](/docs/app/building-your-application/rendering/server-components#static-rendering-default):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} -- **[Caching](/docs/app/building-your-application/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. +- **[Caching](/docs/app/deep-dive/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. </AppOnly> @@ -65,7 +65,7 @@ While building your application, we recommend using the following features to en - **[Route Handlers](/docs/app/building-your-application/routing/route-handlers):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request. - **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Parallel Data Fetching](/docs/app/building-your-application/data-fetching/fetching#parallel-and-sequential-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/building-your-application/data-fetching/fetching#preloading-data) where appropriate. -- **[Data Caching](/docs/app/building-your-application/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). +- **[Data Caching](/docs/app/deep-dive/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). - **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. </AppOnly> diff --git a/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx b/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx index a8f999147870a..4eb221aa008bb 100644 --- a/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx +++ b/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx @@ -136,7 +136,7 @@ The two layouts would be nested as such: > - When a `layout.js` and `page.js` file are defined in the same folder, the layout will wrap the page. > - Layouts are [Server Components](/docs/app/building-your-application/rendering/server-components) by default but can be set to a [Client Component](/docs/app/building-your-application/rendering/client-components). > - Layouts can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information. -> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/building-your-application/caching#request-memoization) without affecting performance. +> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/deep-dive/caching#request-memoization) without affecting performance. > - Layouts do not have access to `pathname` ([learn more](/docs/app/api-reference/file-conventions/layout)). But imported Client Components can access the pathname using [`usePathname`](/docs/app/api-reference/functions/use-pathname) hook. > - Layouts do not have access to the route segments below itself. To access all route segments, you can use [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) or [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) in a Client Component. > - You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to opt specific route segments in and out of shared layouts. diff --git a/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx index 092386dcf1bac..d769c5d9de776 100644 --- a/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ b/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx @@ -3,7 +3,7 @@ title: Linking and Navigating description: Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook. related: links: - - app/building-your-application/caching + - app/deep-dive/caching - app/api-reference/config/typescript --- @@ -283,11 +283,11 @@ See the [`<Link>` API reference](/docs/app/api-reference/components/link) for mo ### 3. Caching -Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. +Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred. -Learn more about how the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) works and how to configure it. +Learn more about how the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) works and how to configure it. ### 4. Partial Rendering @@ -311,7 +311,7 @@ Browsers perform a "hard navigation" when navigating between pages. The Next.js ### 6. Back and Forward Navigation -By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). +By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). ### 7. Routing between `pages/` and `app/` diff --git a/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx b/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx index 5bc44c9b3fb8f..bd188d9310f31 100644 --- a/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx +++ b/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx @@ -77,7 +77,7 @@ export async function generateStaticParams() { } ``` -The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically memoized](/docs/app/building-your-application/caching#request-memoization). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times. +The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically memoized](/docs/app/deep-dive/caching#request-memoization). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times. Use the [migration guide](/docs/app/guides/migrating/app-router-migration#dynamic-paths-getstaticpaths) if you are migrating from the `pages` directory. diff --git a/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx b/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx index 7e57a020d6111..f8e17576132c8 100644 --- a/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx +++ b/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx @@ -265,7 +265,7 @@ This example caches the result of the database query for 1 hour (3600 seconds). Next.js uses APIs like `generateMetadata` and `generateStaticParams` where you will need to use the same data fetched in the `page`. -If you are using `fetch`, requests can be [memoized](/docs/app/building-your-application/caching#request-memoization) by adding `cache: 'force-cache'`. This means you can safely call the same URL with the same options, and only one request will be made. +If you are using `fetch`, requests can be [memoized](/docs/app/deep-dive/caching#request-memoization) by adding `cache: 'force-cache'`. This means you can safely call the same URL with the same options, and only one request will be made. > **Good to know:** > @@ -411,7 +411,7 @@ When fetching data inside components, you need to be aware of two data fetching #### Sequential data fetching -If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are not [memoized](/docs/app/building-your-application/caching#request-memoization). +If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are not [memoized](/docs/app/deep-dive/caching#request-memoization). There may be cases where you want this pattern because one fetch depends on the result of the other. For example, the `Playlists` component will only start fetching data once the `Artist` component has finished fetching data because `Playlists` depends on the `artistID` prop: diff --git a/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx b/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx index 64d9967b4ddf7..c5ded24d30af2 100644 --- a/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx +++ b/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx @@ -120,7 +120,7 @@ Runtime type-checking will still ensure you don't accidentally pass a function t - In Client Components, forms invoking Server Actions will queue submissions if JavaScript isn't loaded yet, prioritizing client hydration. - After hydration, the browser does not refresh on form submission. - Server Actions are not limited to `<form>` and can be invoked from event handlers, `useEffect`, third-party libraries, and other form elements like `<button>`. -- Server Actions integrate with the Next.js [caching and revalidation](/docs/app/building-your-application/caching) architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip. +- Server Actions integrate with the Next.js [caching and revalidation](/docs/app/deep-dive/caching) architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip. - Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them. - The arguments and return value of Server Actions must be serializable by React. See the React docs for a list of [serializable arguments and values](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values). - Server Actions are functions. This means they can be reused anywhere in your application. @@ -723,7 +723,7 @@ When an error is thrown, it'll be caught by the nearest `error.js` or `<Suspense ### Revalidating data -You can revalidate the [Next.js Cache](/docs/app/building-your-application/caching) inside your Server Actions with the [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) API: +You can revalidate the [Next.js Cache](/docs/app/deep-dive/caching) inside your Server Actions with the [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) API: ```ts filename="app/actions.ts" switcher 'use server' diff --git a/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx b/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx index a71ed2f14a359..3c75d2aacb299 100644 --- a/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx +++ b/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx @@ -579,7 +579,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can - ISR is only supported when using the Node.js runtime (default). - ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports). -- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/building-your-application/caching#data-cache). +- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/deep-dive/caching#data-cache). - If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/building-your-application/rendering/server-components#dynamic-rendering). - Middleware won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Middleware will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. diff --git a/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx b/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx index 35b110a67cb01..59d9e36924e0b 100644 --- a/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx +++ b/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx @@ -4,7 +4,7 @@ description: Learn how you can use React Server Components to render parts of yo related: description: Learn how Next.js caches data and the result of static rendering. links: - - app/building-your-application/caching + - app/deep-dive/caching --- React Server Components allow you to write UI that can be rendered and optionally cached on the server. In Next.js, the rendering work is further split by route segments to enable streaming and partial rendering, and there are three different server rendering strategies: @@ -78,7 +78,7 @@ Dynamic rendering is useful when a route has data that is personalized to the us > > In Next.js, you can have dynamically rendered routes that have both cached and uncached data. This is because the RSC Payload and data are cached separately. This allows you to opt into dynamic rendering without worrying about the performance impact of fetching all the data at request time. > -> Learn more about the [full-route cache](/docs/app/building-your-application/caching#full-route-cache) and [Data Cache](/docs/app/building-your-application/caching#data-cache). +> Learn more about the [full-route cache](/docs/app/deep-dive/caching#full-route-cache) and [Data Cache](/docs/app/deep-dive/caching#data-cache). #### Switching to Dynamic Rendering diff --git a/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx b/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx index 8427cd894f672..8705b459e7d6a 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx @@ -107,7 +107,7 @@ For all the available params, see the [API Reference](/docs/app/api-reference/fu > **Good to know**: > > - Both static and dynamic metadata through `generateMetadata` are **only supported in Server Components**. -> - `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#react-cache-function) if `fetch` is unavailable. +> - `fetch` requests are automatically [memoized](/docs/app/deep-dive/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/deep-dive/caching#react-cache-function) if `fetch` is unavailable. > - Next.js will wait for data fetching inside `generateMetadata` to complete before streaming UI to the client. This guarantees the first part of a [streamed response](/docs/app/building-your-application/routing/loading-ui-and-streaming) includes `<head>` tags. ## File-based metadata diff --git a/docs/01-app/03-building-your-application/04-caching/index.mdx b/docs/01-app/04-deep-dive/caching.mdx similarity index 99% rename from docs/01-app/03-building-your-application/04-caching/index.mdx rename to docs/01-app/04-deep-dive/caching.mdx index 59eb06c077145..c2ec17ed58415 100644 --- a/docs/01-app/03-building-your-application/04-caching/index.mdx +++ b/docs/01-app/04-deep-dive/caching.mdx @@ -299,7 +299,7 @@ By default, the Full Route Cache is persistent. This means that the render outpu There are two ways you can invalidate the Full Route Cache: -- **[Revalidating Data](/docs/app/building-your-application/caching#revalidating)**: Revalidating the [Data Cache](#data-cache), will in turn invalidate the Router Cache by re-rendering components on the server and caching the new render output. +- **[Revalidating Data](/docs/app/deep-dive/caching#revalidating)**: Revalidating the [Data Cache](#data-cache), will in turn invalidate the Router Cache by re-rendering components on the server and caching the new render output. - **Redeploying**: Unlike the Data Cache, which persists across deployments, the Full Route Cache is cleared on new deployments. ### Opting out diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx index 41e4af2890d99..d1409a2e850fc 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx @@ -169,7 +169,7 @@ export default function Icon() { > - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-apis) or uncached data. > - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). > - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead. -> - App icons are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> - App icons are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ### Props diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx index 47185b21cda74..fcc45e1fcd927 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx @@ -21,7 +21,7 @@ Add or generate a `manifest.(json|webmanifest)` file that matches the [Web Manif Add a `manifest.js` or `manifest.ts` file that returns a [`Manifest` object](#manifest-object). -> Good to know: `manifest.js` is special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> Good to know: `manifest.js` is special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ```ts filename="app/manifest.ts" switcher import type { MetadataRoute } from 'next' diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx index 7a2f7fbd786fc..ae6a0e58ac62a 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx @@ -90,7 +90,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi > > - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-apis) or uncached data. > - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). -> - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/og`. diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx index a21f5426b653c..3eeea4ab2efce 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx @@ -19,7 +19,7 @@ Sitemap: https://acme.com/sitemap.xml Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object). -> **Good to know**: `robots.js` is a special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> **Good to know**: `robots.js` is a special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ```ts filename="app/robots.ts" switcher import type { MetadataRoute } from 'next' diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx index bfa2e51e553da..29b07bb539f1d 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx @@ -41,7 +41,7 @@ For smaller applications, you can create a `sitemap.xml` file and place it in th You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available. -> **Good to know**: `sitemap.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> **Good to know**: `sitemap.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ```ts filename="app/sitemap.ts" switcher import type { MetadataRoute } from 'next' diff --git a/docs/01-app/05-api-reference/04-functions/fetch.mdx b/docs/01-app/05-api-reference/04-functions/fetch.mdx index 11a95e99ddc3b..c9e677d228fdd 100644 --- a/docs/01-app/05-api-reference/04-functions/fetch.mdx +++ b/docs/01-app/05-api-reference/04-functions/fetch.mdx @@ -5,7 +5,7 @@ description: API reference for the extended fetch function. Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching and revalidation semantics. -In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent [Data Cache](/docs/app/building-your-application/caching#data-cache). +In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent [Data Cache](/docs/app/deep-dive/caching#data-cache). You can call `fetch` with `async` and `await` directly within Server Components. @@ -43,7 +43,7 @@ Since Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs ### `options.cache` -Configure how the request should interact with Next.js [Data Cache](/docs/app/building-your-application/caching#data-cache). +Configure how the request should interact with Next.js [Data Cache](/docs/app/deep-dive/caching#data-cache). ```ts fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) diff --git a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx index ab1d590cbbbf2..e77ca04b8d484 100644 --- a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx +++ b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx @@ -162,7 +162,7 @@ export default function Page({ params, searchParams }) {} > **Good to know**: > > - If metadata doesn't depend on runtime information, it should be defined using the static [`metadata` object](#the-metadata-object) rather than `generateMetadata`. -> - `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#react-cache-function) if `fetch` is unavailable. +> - `fetch` requests are automatically [memoized](/docs/app/deep-dive/caching#request-memoization) for the same data across `generateMetadata`, `generateStaticParams`, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/deep-dive/caching#react-cache-function) if `fetch` is unavailable. > - `searchParams` are only available in `page.js` segments. > - The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`. diff --git a/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx b/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx index 3a5c8562f35a0..7a75c29fee4d6 100644 --- a/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx +++ b/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx @@ -436,7 +436,7 @@ export default function Page({ params }) { } ``` -> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#react-cache-function) if `fetch` is unavailable. +> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/deep-dive/caching#request-memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/deep-dive/caching#react-cache-function) if `fetch` is unavailable. ## Version History diff --git a/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx b/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx index a751493a5d0f1..42f742fa70f37 100644 --- a/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx +++ b/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx @@ -3,13 +3,13 @@ title: revalidatePath description: API Reference for the revalidatePath function. --- -`revalidatePath` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific path. +`revalidatePath` allows you to purge [cached data](/docs/app/deep-dive/caching) on-demand for a specific path. > **Good to know**: > > - `revalidatePath` only invalidates the cache when the included path is next visited. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited. -> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) when used in a server action. This behavior is temporary and will be updated in the future to apply only to the specific path. -> - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache). +> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) when used in a server action. This behavior is temporary and will be updated in the future to apply only to the specific path. +> - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/deep-dive/caching#full-route-cache). ## Parameters diff --git a/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx b/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx index 04f8cf375020d..dd95f75a685e7 100644 --- a/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx +++ b/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx @@ -3,7 +3,7 @@ title: revalidateTag description: API Reference for the revalidateTag function. --- -`revalidateTag` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific cache tag. +`revalidateTag` allows you to purge [cached data](/docs/app/deep-dive/caching) on-demand for a specific cache tag. > **Good to know**: > diff --git a/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx b/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx index a910eff70b2d2..6f14215e9b08b 100644 --- a/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx +++ b/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx @@ -25,7 +25,7 @@ export default async function Component({ userID }) { > **Good to know**: > > - Accessing dynamic data sources such as `headers` or `cookies` inside a cache scope is not supported. If you need this data inside a cached function use `headers` outside of the cached function and pass the required dynamic data in as an argument. -> - This API uses Next.js' built-in [Data Cache](/docs/app/building-your-application/caching#data-cache) to persist the result across requests and deployments. +> - This API uses Next.js' built-in [Data Cache](/docs/app/deep-dive/caching#data-cache) to persist the result across requests and deployments. > **Warning**: This API is unstable and may change in the future. We will provide migration documentation and codemods, if needed, as this API stabilizes. diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx index 2bf588fd0d61c..7c93dc870ff7d 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx @@ -394,7 +394,7 @@ However, you can set `Cache-Control` headers for other responses or data. <AppOnly> -Learn more about [caching](/docs/app/building-your-application/caching) with the App Router. +Learn more about [caching](/docs/app/deep-dive/caching) with the App Router. </AppOnly> diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx index d00663781e2f8..2fca6a21267df 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx @@ -4,7 +4,7 @@ description: Learn how to override the invalidation time of the Client Router Ca version: experimental --- -`staleTimes` is an experimental feature that enables caching of page segments in the [client-side router cache](/docs/app/building-your-application/caching#client-side-router-cache). +`staleTimes` is an experimental feature that enables caching of page segments in the [client-side router cache](/docs/app/deep-dive/caching#client-side-router-cache). You can enable this experimental feature and provide custom revalidation times by setting the experimental `staleTimes` flag: @@ -26,16 +26,16 @@ The `static` and `dynamic` properties correspond with the time period (in second - The `dynamic` property is used when the page is neither statically generated nor fully prefetched (e.g. with `prefetch={true}`). - Default: 0 seconds (not cached) -- The `static` property is used for statically generated pages, or when the `prefetch` prop on `Link` is set to `true`, or when calling [`router.prefetch`](/docs/app/building-your-application/caching#routerprefetch). +- The `static` property is used for statically generated pages, or when the `prefetch` prop on `Link` is set to `true`, or when calling [`router.prefetch`](/docs/app/deep-dive/caching#routerprefetch). - Default: 5 minutes > **Good to know:** > > - [Loading boundaries](/docs/app/api-reference/file-conventions/loading) are considered reusable for the `static` period defined in this configuration. > - This doesn't affect [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), **meaning shared layouts won't automatically be refetched on every navigation, only the page segment that changes.** -> - This doesn't change [back/forward caching](/docs/app/building-your-application/caching#client-side-router-cache) behavior to prevent layout shift and to prevent losing the browser scroll position. +> - This doesn't change [back/forward caching](/docs/app/deep-dive/caching#client-side-router-cache) behavior to prevent layout shift and to prevent losing the browser scroll position. -You can learn more about the Client Router Cache [here](/docs/app/building-your-application/caching#client-side-router-cache). +You can learn more about the Client Router Cache [here](/docs/app/deep-dive/caching#client-side-router-cache). ### Version History
diff --git a/docs/01-app/02-guides/production-checklist.mdx b/docs/01-app/02-guides/production-checklist.mdx index 3a25354a9fcc2..0c330c6415fad 100644 --- a/docs/01-app/02-guides/production-checklist.mdx +++ b/docs/01-app/02-guides/production-checklist.mdx @@ -18,7 +18,7 @@ These Next.js optimizations are enabled by default and require no configuration: - **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. - **[Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Static Rendering](/docs/app/building-your-application/rendering/server-components#static-rendering-default):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} -- **[Caching](/docs/app/building-your-application/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. +- **[Caching](/docs/app/deep-dive/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. @@ -65,7 +65,7 @@ While building your application, we recommend using the following features to en - **[Route Handlers](/docs/app/building-your-application/routing/route-handlers):** Use Route Handlers to access your backend resources from Client Components. But do not call Route Handlers from Server Components to avoid an additional server request. - **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Parallel Data Fetching](/docs/app/building-your-application/data-fetching/fetching#parallel-and-sequential-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/building-your-application/data-fetching/fetching#preloading-data) where appropriate. -- **[Data Caching](/docs/app/building-your-application/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). +- **[Data Caching](/docs/app/deep-dive/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). - **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. diff --git a/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx b/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx index a8f999147870a..4eb221aa008bb 100644 --- a/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx +++ b/docs/01-app/03-building-your-application/01-routing/03-layouts-and-templates.mdx @@ -136,7 +136,7 @@ The two layouts would be nested as such: > - When a `layout.js` and `page.js` file are defined in the same folder, the layout will wrap the page. > - Layouts are [Server Components](/docs/app/building-your-application/rendering/server-components) by default but can be set to a [Client Component](/docs/app/building-your-application/rendering/client-components). > - Layouts can fetch data. View the [Data Fetching](/docs/app/building-your-application/data-fetching) section for more information. -> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/building-your-application/caching#request-memoization) without affecting performance. +> - Passing data between a parent layout and its children is not possible. However, you can fetch the same data in a route more than once, and React will [automatically dedupe the requests](/docs/app/deep-dive/caching#request-memoization) without affecting performance. > - Layouts do not have access to `pathname` ([learn more](/docs/app/api-reference/file-conventions/layout)). But imported Client Components can access the pathname using [`usePathname`](/docs/app/api-reference/functions/use-pathname) hook. > - Layouts do not have access to the route segments below itself. To access all route segments, you can use [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected-layout-segment) or [`useSelectedLayoutSegments`](/docs/app/api-reference/functions/use-selected-layout-segments) in a Client Component. > - You can use [Route Groups](/docs/app/building-your-application/routing/route-groups) to opt specific route segments in and out of shared layouts. diff --git a/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx b/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx index 092386dcf1bac..d769c5d9de776 100644 --- a/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx +++ b/docs/01-app/03-building-your-application/01-routing/04-linking-and-navigating.mdx @@ -3,7 +3,7 @@ title: Linking and Navigating description: Learn how navigation works in Next.js, and how to use the Link Component and `useRouter` hook. - app/api-reference/config/typescript @@ -283,11 +283,11 @@ See the [`<Link>` API reference](/docs/app/api-reference/components/link) for mo ### 3. Caching -Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. +Next.js has an **in-memory client-side cache** called the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). As users navigate around the app, the React Server Component Payload of [prefetched](#2-prefetching) route segments and visited routes are stored in the cache. This means on navigation, the cache is reused as much as possible, instead of making a new request to the server - improving performance by reducing the number of requests and data transferred. -Learn more about how the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) works and how to configure it. +Learn more about how the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) works and how to configure it. ### 4. Partial Rendering @@ -311,7 +311,7 @@ Browsers perform a "hard navigation" when navigating between pages. The Next.js ### 6. Back and Forward Navigation -By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). +By default, Next.js will maintain the scroll position for backwards and forwards navigation, and re-use route segments in the [Router Cache](/docs/app/deep-dive/caching#client-side-router-cache). ### 7. Routing between `pages/` and `app/` diff --git a/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx b/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx index 5bc44c9b3fb8f..bd188d9310f31 100644 --- a/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx +++ b/docs/01-app/03-building-your-application/01-routing/10-dynamic-routes.mdx @@ -77,7 +77,7 @@ export async function generateStaticParams() { -The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically memoized](/docs/app/building-your-application/caching#request-memoization). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times. Use the [migration guide](/docs/app/guides/migrating/app-router-migration#dynamic-paths-getstaticpaths) if you are migrating from the `pages` directory. diff --git a/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx b/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx index 7e57a020d6111..f8e17576132c8 100644 --- a/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx +++ b/docs/01-app/03-building-your-application/02-data-fetching/01-fetching.mdx @@ -265,7 +265,7 @@ This example caches the result of the database query for 1 hour (3600 seconds). Next.js uses APIs like `generateMetadata` and `generateStaticParams` where you will need to use the same data fetched in the `page`. -If you are using `fetch`, requests can be [memoized](/docs/app/building-your-application/caching#request-memoization) by adding `cache: 'force-cache'`. This means you can safely call the same URL with the same options, and only one request will be made. +If you are using `fetch`, requests can be [memoized](/docs/app/deep-dive/caching#request-memoization) by adding `cache: 'force-cache'`. This means you can safely call the same URL with the same options, and only one request will be made. @@ -411,7 +411,7 @@ When fetching data inside components, you need to be aware of two data fetching #### Sequential data fetching -If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are not [memoized](/docs/app/building-your-application/caching#request-memoization). +If you have nested components, and each component fetches its own data, then data fetching will happen sequentially if those data requests are not [memoized](/docs/app/deep-dive/caching#request-memoization). There may be cases where you want this pattern because one fetch depends on the result of the other. For example, the `Playlists` component will only start fetching data once the `Artist` component has finished fetching data because `Playlists` depends on the `artistID` prop: diff --git a/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx b/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx index 64d9967b4ddf7..c5ded24d30af2 100644 --- a/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx +++ b/docs/01-app/03-building-your-application/02-data-fetching/03-server-actions-and-mutations.mdx @@ -120,7 +120,7 @@ Runtime type-checking will still ensure you don't accidentally pass a function t - In Client Components, forms invoking Server Actions will queue submissions if JavaScript isn't loaded yet, prioritizing client hydration. - After hydration, the browser does not refresh on form submission. - Server Actions are not limited to `<form>` and can be invoked from event handlers, `useEffect`, third-party libraries, and other form elements like `<button>`. -- Server Actions integrate with the Next.js [caching and revalidation](/docs/app/building-your-application/caching) architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip. +- Server Actions integrate with the Next.js [caching and revalidation](/docs/app/deep-dive/caching) architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip. - Behind the scenes, actions use the `POST` method, and only this HTTP method can invoke them. - The arguments and return value of Server Actions must be serializable by React. See the React docs for a list of [serializable arguments and values](https://react.dev/reference/react/use-server#serializable-parameters-and-return-values). - Server Actions are functions. This means they can be reused anywhere in your application. @@ -723,7 +723,7 @@ When an error is thrown, it'll be caught by the nearest `error.js` or `<Suspense ### Revalidating data -You can revalidate the [Next.js Cache](/docs/app/building-your-application/caching) inside your Server Actions with the [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) API: +You can revalidate the [Next.js Cache](/docs/app/deep-dive/caching) inside your Server Actions with the [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) API: ```ts filename="app/actions.ts" switcher 'use server' diff --git a/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx b/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx index a71ed2f14a359..3c75d2aacb299 100644 --- a/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx +++ b/docs/01-app/03-building-your-application/02-data-fetching/04-incremental-static-regeneration.mdx @@ -579,7 +579,7 @@ This will make the Next.js server console log ISR cache hits and misses. You can - ISR is only supported when using the Node.js runtime (default). - ISR is not supported when creating a [Static Export](/docs/app/guides/static-exports). -- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/building-your-application/caching#data-cache). +- If you have multiple `fetch` requests in a statically rendered route, and each has a different `revalidate` frequency, the lowest time will be used for ISR. However, those revalidate frequencies will still be respected by the [Data Cache](/docs/app/deep-dive/caching#data-cache). - If any of the `fetch` requests used on a route have a `revalidate` time of `0`, or an explicit `no-store`, the route will be [dynamically rendered](/docs/app/building-your-application/rendering/server-components#dynamic-rendering). - Middleware won't be executed for on-demand ISR requests, meaning any path rewrites or logic in Middleware will not be applied. Ensure you are revalidating the exact path. For example, `/post/1` instead of a rewritten `/post-1`. diff --git a/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx b/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx index 35b110a67cb01..59d9e36924e0b 100644 --- a/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx +++ b/docs/01-app/03-building-your-application/03-rendering/01-server-components.mdx @@ -4,7 +4,7 @@ description: Learn how you can use React Server Components to render parts of yo description: Learn how Next.js caches data and the result of static rendering. React Server Components allow you to write UI that can be rendered and optionally cached on the server. In Next.js, the rendering work is further split by route segments to enable streaming and partial rendering, and there are three different server rendering strategies: @@ -78,7 +78,7 @@ Dynamic rendering is useful when a route has data that is personalized to the us > In Next.js, you can have dynamically rendered routes that have both cached and uncached data. This is because the RSC Payload and data are cached separately. This allows you to opt into dynamic rendering without worrying about the performance impact of fetching all the data at request time. -> Learn more about the [full-route cache](/docs/app/building-your-application/caching#full-route-cache) and [Data Cache](/docs/app/building-your-application/caching#data-cache). +> Learn more about the [full-route cache](/docs/app/deep-dive/caching#full-route-cache) and [Data Cache](/docs/app/deep-dive/caching#data-cache). #### Switching to Dynamic Rendering diff --git a/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx b/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx index 8427cd894f672..8705b459e7d6a 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/04-metadata.mdx @@ -107,7 +107,7 @@ For all the available params, see the [API Reference](/docs/app/api-reference/fu > - Both static and dynamic metadata through `generateMetadata` are **only supported in Server Components**. > - Next.js will wait for data fetching inside `generateMetadata` to complete before streaming UI to the client. This guarantees the first part of a [streamed response](/docs/app/building-your-application/routing/loading-ui-and-streaming) includes `<head>` tags. ## File-based metadata diff --git a/docs/01-app/03-building-your-application/04-caching/index.mdx b/docs/01-app/04-deep-dive/caching.mdx similarity index 99% rename from docs/01-app/03-building-your-application/04-caching/index.mdx rename to docs/01-app/04-deep-dive/caching.mdx index 59eb06c077145..c2ec17ed58415 100644 --- a/docs/01-app/03-building-your-application/04-caching/index.mdx +++ b/docs/01-app/04-deep-dive/caching.mdx @@ -299,7 +299,7 @@ By default, the Full Route Cache is persistent. This means that the render outpu There are two ways you can invalidate the Full Route Cache: -- **[Revalidating Data](/docs/app/building-your-application/caching#revalidating)**: Revalidating the [Data Cache](#data-cache), will in turn invalidate the Router Cache by re-rendering components on the server and caching the new render output. +- **[Revalidating Data](/docs/app/deep-dive/caching#revalidating)**: Revalidating the [Data Cache](#data-cache), will in turn invalidate the Router Cache by re-rendering components on the server and caching the new render output. - **Redeploying**: Unlike the Data Cache, which persists across deployments, the Full Route Cache is cleared on new deployments. ### Opting out diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx index 41e4af2890d99..d1409a2e850fc 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/app-icons.mdx @@ -169,7 +169,7 @@ export default function Icon() { > - By default, generated icons are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-apis) or uncached data. > - You can generate multiple icons in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). > - You cannot generate a `favicon` icon. Use [`icon`](#icon) or a [favicon.ico](#favicon) file instead. -> - App icons are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> - App icons are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ### Props diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx index 47185b21cda74..fcc45e1fcd927 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/manifest.mdx @@ -21,7 +21,7 @@ Add or generate a `manifest.(json|webmanifest)` file that matches the [Web Manif Add a `manifest.js` or `manifest.ts` file that returns a [`Manifest` object](#manifest-object). +> Good to know: `manifest.js` is special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ```ts filename="app/manifest.ts" switcher diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx index 7a2f7fbd786fc..ae6a0e58ac62a 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx @@ -90,7 +90,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi > - By default, generated images are [**statically optimized**](/docs/app/building-your-application/rendering/server-components#static-rendering-default) (generated at build time and cached) unless they use [Dynamic APIs](/docs/app/building-your-application/rendering/server-components#server-rendering-strategies#dynamic-apis) or uncached data. > - You can generate multiple Images in the same file using [`generateImageMetadata`](/docs/app/api-reference/functions/generate-image-metadata). -> - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> - `opengraph-image.js` and `twitter-image.js` are special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/og`. diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx index a21f5426b653c..3eeea4ab2efce 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/robots.mdx @@ -19,7 +19,7 @@ Sitemap: https://acme.com/sitemap.xml Add a `robots.js` or `robots.ts` file that returns a [`Robots` object](#robots-object). -> **Good to know**: `robots.js` is a special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> **Good to know**: `robots.js` is a special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ```ts filename="app/robots.ts" switcher diff --git a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx index bfa2e51e553da..29b07bb539f1d 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/01-metadata/sitemap.mdx @@ -41,7 +41,7 @@ For smaller applications, you can create a `sitemap.xml` file and place it in th You can use the `sitemap.(js|ts)` file convention to programmatically **generate** a sitemap by exporting a default function that returns an array of URLs. If using TypeScript, a [`Sitemap`](#returns) type is available. -> **Good to know**: `sitemap.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option. +> **Good to know**: `sitemap.js` is a special Route Handler that is cached by default unless it uses a [Dynamic API](/docs/app/deep-dive/caching#dynamic-apis) or [dynamic config](/docs/app/deep-dive/caching#segment-config-options) option. ```ts filename="app/sitemap.ts" switcher diff --git a/docs/01-app/05-api-reference/04-functions/fetch.mdx b/docs/01-app/05-api-reference/04-functions/fetch.mdx index 11a95e99ddc3b..c9e677d228fdd 100644 --- a/docs/01-app/05-api-reference/04-functions/fetch.mdx +++ b/docs/01-app/05-api-reference/04-functions/fetch.mdx @@ -5,7 +5,7 @@ description: API reference for the extended fetch function. Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs/Web/API/Fetch_API) to allow each request on the server to set its own persistent caching and revalidation semantics. +In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent [Data Cache](/docs/app/deep-dive/caching#data-cache). You can call `fetch` with `async` and `await` directly within Server Components. @@ -43,7 +43,7 @@ Since Next.js extends the [Web `fetch()` API](https://developer.mozilla.org/docs ### `options.cache` -Configure how the request should interact with Next.js [Data Cache](/docs/app/building-your-application/caching#data-cache). +Configure how the request should interact with Next.js [Data Cache](/docs/app/deep-dive/caching#data-cache). ```ts fetch(`https://...`, { cache: 'force-cache' | 'no-store' }) diff --git a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx index ab1d590cbbbf2..e77ca04b8d484 100644 --- a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx +++ b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx @@ -162,7 +162,7 @@ export default function Page({ params, searchParams }) {} > - If metadata doesn't depend on runtime information, it should be defined using the static [`metadata` object](#the-metadata-object) rather than `generateMetadata`. > - `searchParams` are only available in `page.js` segments. > - The [`redirect()`](/docs/app/api-reference/functions/redirect) and [`notFound()`](/docs/app/api-reference/functions/not-found) Next.js methods can also be used inside `generateMetadata`. diff --git a/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx b/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx index 3a5c8562f35a0..7a75c29fee4d6 100644 --- a/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx +++ b/docs/01-app/05-api-reference/04-functions/generate-static-params.mdx @@ -436,7 +436,7 @@ export default function Page({ params }) { -> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/building-your-application/caching#request-memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/building-your-application/caching#react-cache-function) if `fetch` is unavailable. ## Version History diff --git a/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx b/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx index a751493a5d0f1..42f742fa70f37 100644 --- a/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx +++ b/docs/01-app/05-api-reference/04-functions/revalidatePath.mdx @@ -3,13 +3,13 @@ title: revalidatePath description: API Reference for the revalidatePath function. -`revalidatePath` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific path. +`revalidatePath` allows you to purge [cached data](/docs/app/deep-dive/caching) on-demand for a specific path. > - `revalidatePath` only invalidates the cache when the included path is next visited. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited. -> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) when used in a server action. This behavior is temporary and will be updated in the future to apply only to the specific path. -> - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache). +> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/deep-dive/caching#client-side-router-cache) when used in a server action. This behavior is temporary and will be updated in the future to apply only to the specific path. +> - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/deep-dive/caching#full-route-cache). ## Parameters diff --git a/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx b/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx index 04f8cf375020d..dd95f75a685e7 100644 --- a/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx +++ b/docs/01-app/05-api-reference/04-functions/revalidateTag.mdx @@ -3,7 +3,7 @@ title: revalidateTag description: API Reference for the revalidateTag function. -`revalidateTag` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific cache tag. +`revalidateTag` allows you to purge [cached data](/docs/app/deep-dive/caching) on-demand for a specific cache tag. diff --git a/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx b/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx index a910eff70b2d2..6f14215e9b08b 100644 --- a/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx +++ b/docs/01-app/05-api-reference/04-functions/unstable_cache.mdx @@ -25,7 +25,7 @@ export default async function Component({ userID }) { > - Accessing dynamic data sources such as `headers` or `cookies` inside a cache scope is not supported. If you need this data inside a cached function use `headers` outside of the cached function and pass the required dynamic data in as an argument. -> - This API uses Next.js' built-in [Data Cache](/docs/app/building-your-application/caching#data-cache) to persist the result across requests and deployments. +> - This API uses Next.js' built-in [Data Cache](/docs/app/deep-dive/caching#data-cache) to persist the result across requests and deployments. > **Warning**: This API is unstable and may change in the future. We will provide migration documentation and codemods, if needed, as this API stabilizes. diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx index 2bf588fd0d61c..7c93dc870ff7d 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/headers.mdx @@ -394,7 +394,7 @@ However, you can set `Cache-Control` headers for other responses or data. <AppOnly> -Learn more about [caching](/docs/app/building-your-application/caching) with the App Router. +Learn more about [caching](/docs/app/deep-dive/caching) with the App Router. diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx index d00663781e2f8..2fca6a21267df 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/staleTimes.mdx @@ -4,7 +4,7 @@ description: Learn how to override the invalidation time of the Client Router Ca version: experimental -`staleTimes` is an experimental feature that enables caching of page segments in the [client-side router cache](/docs/app/building-your-application/caching#client-side-router-cache). +`staleTimes` is an experimental feature that enables caching of page segments in the [client-side router cache](/docs/app/deep-dive/caching#client-side-router-cache). You can enable this experimental feature and provide custom revalidation times by setting the experimental `staleTimes` flag: @@ -26,16 +26,16 @@ The `static` and `dynamic` properties correspond with the time period (in second - The `dynamic` property is used when the page is neither statically generated nor fully prefetched (e.g. with `prefetch={true}`). - Default: 0 seconds (not cached) -- The `static` property is used for statically generated pages, or when the `prefetch` prop on `Link` is set to `true`, or when calling [`router.prefetch`](/docs/app/building-your-application/caching#routerprefetch). +- The `static` property is used for statically generated pages, or when the `prefetch` prop on `Link` is set to `true`, or when calling [`router.prefetch`](/docs/app/deep-dive/caching#routerprefetch). - Default: 5 minutes > - [Loading boundaries](/docs/app/api-reference/file-conventions/loading) are considered reusable for the `static` period defined in this configuration. > - This doesn't affect [partial rendering](/docs/app/building-your-application/routing/linking-and-navigating#4-partial-rendering), **meaning shared layouts won't automatically be refetched on every navigation, only the page segment that changes.** -> - This doesn't change [back/forward caching](/docs/app/building-your-application/caching#client-side-router-cache) behavior to prevent layout shift and to prevent losing the browser scroll position. +> - This doesn't change [back/forward caching](/docs/app/deep-dive/caching#client-side-router-cache) behavior to prevent layout shift and to prevent losing the browser scroll position. -You can learn more about the Client Router Cache [here](/docs/app/building-your-application/caching#client-side-router-cache). +You can learn more about the Client Router Cache [here](/docs/app/deep-dive/caching#client-side-router-cache). ### Version History
[ "+The primary benefit of the `generateStaticParams` function is its smart retrieval of data. If content is fetched within the `generateStaticParams` function using a `fetch` request, the requests are [automatically memoized](/docs/app/deep-dive/caching#request-memoization). This means a `fetch` request with the same arguments across multiple `generateStaticParams`, Layouts, and Pages will only be made once, which decreases build times.", "-> Good to know: `manifest.js` is special Route Handlers that is cached by default unless it uses a [Dynamic API](/docs/app/building-your-application/caching#dynamic-apis) or [dynamic config](/docs/app/building-your-application/caching#segment-config-options) option.", "-In the browser, the `cache` option indicates how a fetch request will interact with the _browser's_ HTTP cache. With this extension, `cache` indicates how a _server-side_ fetch request will interact with the framework's persistent [Data Cache](/docs/app/building-your-application/caching#data-cache).", "+> **Good to know**: `fetch` requests are automatically [memoized](/docs/app/deep-dive/caching#request-memoization) for the same data across all `generate`-prefixed functions, Layouts, Pages, and Server Components. React [`cache` can be used](/docs/app/deep-dive/caching#react-cache-function) if `fetch` is unavailable." ]
[ 80, 213, 265, 301 ]
{ "additions": 36, "author": "delbaoliveira", "deletions": 36, "html_url": "https://github.com/vercel/next.js/pull/78537", "issue_id": 78537, "merged_at": "2025-04-25T15:51:30Z", "omission_probability": 0.1, "pr_number": 78537, "repo": "vercel/next.js", "title": "Docs IA 2.0: Move caching page to deep dive", "total_changes": 72 }
304
diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index 17f1cbc1524bd..cf19081447fd8 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -1440,7 +1440,11 @@ }, "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts": { "passed": [ - "back/forward cache Activity component is renderable when the routerBFCache flag is on" + "back/forward cache React state is preserved when navigating back to a page with different search params than before ", + "back/forward cache React state is preserved when navigating back/forward with links", + "back/forward cache React state is preserved when navigating with back/forward buttons", + "back/forward cache bfcache only preserves up to N entries", + "back/forward cache navigate back and forth repeatedly between the same pages without evicting" ], "failed": [], "pending": [], @@ -3544,6 +3548,16 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts": { + "passed": [ + "not-found-with-pages should prefer the app router 404 over the pages router 404 when both are present", + "not-found-with-pages should write all locales to the pages manifest" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/not-found/basic/index.test.ts": { "passed": [ "app dir - not-found - basic should include not found client reference manifest in the file trace", @@ -4230,6 +4244,15 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts": { + "passed": [ + "ppr-middleware-rewrite-force-dynamic-generate-static-params should have correct dynamic params" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/ppr-missing-root-params/ppr-missing-root-params.test.ts": { "passed": [ "ppr-missing-root-params (multiple) should result in a build error", @@ -4611,6 +4634,15 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts": { + "passed": [ + "react@experimental should opt into the react@experimental when enabling $flag" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/rsc-basic/rsc-basic.test.ts": { "passed": [ "app dir - rsc basics client references with TLA (edge) should support TLA in lazy client reference", @@ -4619,8 +4651,6 @@ "app dir - rsc basics client references with TLA (node) should support TLA in sync client reference imports", "app dir - rsc basics next internal shared context should not error if just load next/navigation module in pages/api", "app dir - rsc basics next internal shared context should not error if just load next/router module in app page", - "app dir - rsc basics react@experimental should opt into the react@experimental when enabling ppr", - "app dir - rsc basics react@experimental should opt into the react@experimental when enabling taint", "app dir - rsc basics should be able to call legacy react-dom/server APIs in client components", "app dir - rsc basics should be able to navigate between rsc routes", "app dir - rsc basics should correctly render component returning null", @@ -5784,6 +5814,7 @@ }, "test/e2e/app-dir/worker/worker.test.ts": { "passed": [ + "app dir - workers should not bundle web workers with string specifiers", "app dir - workers should support module web workers with dynamic imports", "app dir - workers should support web workers with dynamic imports" ], @@ -8017,6 +8048,13 @@ "flakey": [], "runtimeError": false }, + "test/e2e/swc-plugins/index.test.ts": { + "passed": ["swcPlugins supports swcPlugins basic case"], + "failed": [], + "pending": ["swcPlugins invalid plugin name shows a redbox in dev"], + "flakey": [], + "runtimeError": false + }, "test/e2e/swc-warnings/index.test.ts": { "passed": [], "failed": [], @@ -14662,9 +14700,10 @@ "flakey": [], "runtimeError": false }, - "test/integration/invalid-href/test/index.test.js": { + "test/integration/invalid-href/test/index.test.ts": { "passed": [ - "Invalid hrefs production mode does not show error in production when https://google.com is used as href on Link", + "Invalid hrefs production mode does not show error in production when exotic protocols are used in href in Link", + "Invalid hrefs production mode does not show error in production when https:// is used in href on Link", "Invalid hrefs production mode does not show error in production when mailto: is used as href on Link", "Invalid hrefs production mode does not show error when internal href is used with external as", "Invalid hrefs production mode doesn't fail on invalid url", @@ -14674,7 +14713,8 @@ ], "failed": [], "pending": [ - "Invalid hrefs development mode does not show error when https://google.com is used as href on Link", + "Invalid hrefs development mode does not show error when exotic protocols are used in href in Link", + "Invalid hrefs development mode does not show error when https:// is used as href in Link", "Invalid hrefs development mode does not show error when mailto: is used as href on Link", "Invalid hrefs development mode does not throw error when dynamic route mismatch is used on Link and params are manually provided", "Invalid hrefs development mode doesn't fail on invalid url",
diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index 17f1cbc1524bd..cf19081447fd8 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -1440,7 +1440,11 @@ "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts": { - "back/forward cache Activity component is renderable when the routerBFCache flag is on" + "back/forward cache React state is preserved when navigating back to a page with different search params than before ", + "back/forward cache React state is preserved when navigating back/forward with links", + "back/forward cache React state is preserved when navigating with back/forward buttons", + "back/forward cache bfcache only preserves up to N entries", + "back/forward cache navigate back and forth repeatedly between the same pages without evicting" "pending": [], @@ -3544,6 +3548,16 @@ + "test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts": { + "not-found-with-pages should prefer the app router 404 over the pages router 404 when both are present", + "not-found-with-pages should write all locales to the pages manifest" "test/e2e/app-dir/not-found/basic/index.test.ts": { "app dir - not-found - basic should include not found client reference manifest in the file trace", @@ -4230,6 +4244,15 @@ + "test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts": { + "ppr-middleware-rewrite-force-dynamic-generate-static-params should have correct dynamic params" "test/e2e/app-dir/ppr-missing-root-params/ppr-missing-root-params.test.ts": { "ppr-missing-root-params (multiple) should result in a build error", @@ -4611,6 +4634,15 @@ + "test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts": { + "react@experimental should opt into the react@experimental when enabling $flag" "test/e2e/app-dir/rsc-basic/rsc-basic.test.ts": { "app dir - rsc basics client references with TLA (edge) should support TLA in lazy client reference", @@ -4619,8 +4651,6 @@ "app dir - rsc basics client references with TLA (node) should support TLA in sync client reference imports", "app dir - rsc basics next internal shared context should not error if just load next/navigation module in pages/api", "app dir - rsc basics next internal shared context should not error if just load next/router module in app page", - "app dir - rsc basics react@experimental should opt into the react@experimental when enabling ppr", - "app dir - rsc basics react@experimental should opt into the react@experimental when enabling taint", "app dir - rsc basics should be able to call legacy react-dom/server APIs in client components", "app dir - rsc basics should be able to navigate between rsc routes", "app dir - rsc basics should correctly render component returning null", @@ -5784,6 +5814,7 @@ "test/e2e/app-dir/worker/worker.test.ts": { + "app dir - workers should not bundle web workers with string specifiers", "app dir - workers should support module web workers with dynamic imports", "app dir - workers should support web workers with dynamic imports" @@ -8017,6 +8048,13 @@ + "test/e2e/swc-plugins/index.test.ts": { + "passed": ["swcPlugins supports swcPlugins basic case"], + "pending": ["swcPlugins invalid plugin name shows a redbox in dev"], "test/e2e/swc-warnings/index.test.ts": { "passed": [], @@ -14662,9 +14700,10 @@ + "test/integration/invalid-href/test/index.test.ts": { - "Invalid hrefs production mode does not show error in production when https://google.com is used as href on Link", + "Invalid hrefs production mode does not show error in production when exotic protocols are used in href in Link", + "Invalid hrefs production mode does not show error in production when https:// is used in href on Link", "Invalid hrefs production mode does not show error in production when mailto: is used as href on Link", "Invalid hrefs production mode does not show error when internal href is used with external as", "Invalid hrefs production mode doesn't fail on invalid url", @@ -14674,7 +14713,8 @@ "pending": [ - "Invalid hrefs development mode does not show error when https://google.com is used as href on Link", + "Invalid hrefs development mode does not show error when exotic protocols are used in href in Link", + "Invalid hrefs development mode does not show error when https:// is used as href in Link", "Invalid hrefs development mode does not show error when mailto: is used as href on Link", "Invalid hrefs development mode does not throw error when dynamic route mismatch is used on Link and params are manually provided", "Invalid hrefs development mode doesn't fail on invalid url",
[ "- \"test/integration/invalid-href/test/index.test.js\": {" ]
[ 101 ]
{ "additions": 46, "author": "vercel-release-bot", "deletions": 6, "html_url": "https://github.com/vercel/next.js/pull/78053", "issue_id": 78053, "merged_at": "2025-04-11T07:44:04Z", "omission_probability": 0.1, "pr_number": 78053, "repo": "vercel/next.js", "title": "Update Turbopack production test manifest", "total_changes": 52 }
305
diff --git a/packages/next/src/server/typescript/utils.ts b/packages/next/src/server/typescript/utils.ts index 42bff2cf934a1..01ecf269112f8 100644 --- a/packages/next/src/server/typescript/utils.ts +++ b/packages/next/src/server/typescript/utils.ts @@ -35,11 +35,33 @@ export function getInfo() { } export function getTypeChecker() { - return info.languageService.getProgram()?.getTypeChecker() + const program = info.languageService.getProgram() + if (!program) { + log('Failed to get program while while running getTypeChecker.') + return + } + const typeChecker = program.getTypeChecker() + if (!typeChecker) { + log('Failed to get type checker while running getTypeChecker.') + return + } + return typeChecker } export function getSource(fileName: string) { - return info.languageService.getProgram()?.getSourceFile(fileName) + const program = info.languageService.getProgram() + if (!program) { + log('Failed to get program while running getSource for: ' + fileName) + return + } + + const sourceFile = program.getSourceFile(fileName) + if (!sourceFile) { + log('Failed to get source file while running getSource for: ' + fileName) + return + } + + return sourceFile } export function removeStringQuotes(str: string): string {
diff --git a/packages/next/src/server/typescript/utils.ts b/packages/next/src/server/typescript/utils.ts index 42bff2cf934a1..01ecf269112f8 100644 --- a/packages/next/src/server/typescript/utils.ts +++ b/packages/next/src/server/typescript/utils.ts @@ -35,11 +35,33 @@ export function getInfo() { export function getTypeChecker() { - return info.languageService.getProgram()?.getTypeChecker() + log('Failed to get program while while running getTypeChecker.') + const typeChecker = program.getTypeChecker() + if (!typeChecker) { + log('Failed to get type checker while running getTypeChecker.') + return typeChecker export function getSource(fileName: string) { - return info.languageService.getProgram()?.getSourceFile(fileName) + log('Failed to get program while running getSource for: ' + fileName) + const sourceFile = program.getSourceFile(fileName) + if (!sourceFile) { export function removeStringQuotes(str: string): string {
[ "+ log('Failed to get source file while running getSource for: ' + fileName)", "+ return sourceFile" ]
[ 32, 36 ]
{ "additions": 24, "author": "devjiwonchoi", "deletions": 2, "html_url": "https://github.com/vercel/next.js/pull/78538", "issue_id": 78538, "merged_at": "2025-04-25T10:06:53Z", "omission_probability": 0.1, "pr_number": 78538, "repo": "vercel/next.js", "title": "[ts-next-plugin] update log for utils", "total_changes": 26 }
306
diff --git a/test/turbopack-dev-tests-manifest.json b/test/turbopack-dev-tests-manifest.json index 32f51368c02b8..621c1e8d6969c 100644 --- a/test/turbopack-dev-tests-manifest.json +++ b/test/turbopack-dev-tests-manifest.json @@ -5023,6 +5023,18 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/css-modules-data-urls/css-modules-data-urls.test.ts": { + "passed": [ + "css-modules-data-urls should apply client class name from data url correctly", + "css-modules-data-urls should apply client styles from data url correctly", + "css-modules-data-urls should apply rsc class name from data url correctly", + "css-modules-data-urls should apply rsc styles from data url correctly" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/css-modules-pure-no-check/css-modules-pure-no-check.test.ts": { "passed": ["css-modules-pure-no-check should apply styles correctly"], "failed": [], @@ -5971,6 +5983,13 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts": { + "passed": ["instrumentation-order should work using cheerio"], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/interception-dynamic-segment-middleware/interception-dynamic-segment-middleware.test.ts": { "passed": [ "interception-dynamic-segment-middleware should work when interception route is paired with a dynamic segment & middleware" @@ -9323,6 +9342,17 @@ "flakey": [], "runtimeError": false }, + "test/e2e/config-turbopack/index.test.ts": { + "passed": [ + "config-turbopack when webpack is configured and config.experimental.turbo is set does not warn", + "config-turbopack when webpack is configured and config.turbopack is set does not warn", + "config-turbopack when webpack is configured but Turbopack is not warns" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/conflicting-app-page-error/index.test.ts": { "passed": [ "Conflict between app file and pages file should error again when there is new conflict", @@ -11550,6 +11580,13 @@ "flakey": [], "runtimeError": false }, + "test/e2e/worker-react-refresh/worker-react-refresh.test.tsx": { + "passed": ["worker-react-refresh does not cause any runtime errors"], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/yarn-pnp/test/mdx-pages.test.ts": { "passed": [], "failed": [],
diff --git a/test/turbopack-dev-tests-manifest.json b/test/turbopack-dev-tests-manifest.json index 32f51368c02b8..621c1e8d6969c 100644 --- a/test/turbopack-dev-tests-manifest.json +++ b/test/turbopack-dev-tests-manifest.json @@ -5023,6 +5023,18 @@ + "test/e2e/app-dir/css-modules-data-urls/css-modules-data-urls.test.ts": { + "css-modules-data-urls should apply client class name from data url correctly", + "css-modules-data-urls should apply client styles from data url correctly", + "css-modules-data-urls should apply rsc class name from data url correctly", + "css-modules-data-urls should apply rsc styles from data url correctly" "test/e2e/app-dir/css-modules-pure-no-check/css-modules-pure-no-check.test.ts": { "passed": ["css-modules-pure-no-check should apply styles correctly"], @@ -5971,6 +5983,13 @@ + "test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts": { + "passed": ["instrumentation-order should work using cheerio"], "test/e2e/app-dir/interception-dynamic-segment-middleware/interception-dynamic-segment-middleware.test.ts": { "interception-dynamic-segment-middleware should work when interception route is paired with a dynamic segment & middleware" @@ -9323,6 +9342,17 @@ + "test/e2e/config-turbopack/index.test.ts": { + "config-turbopack when webpack is configured and config.experimental.turbo is set does not warn", "test/e2e/conflicting-app-page-error/index.test.ts": { "Conflict between app file and pages file should error again when there is new conflict", @@ -11550,6 +11580,13 @@ + "test/e2e/worker-react-refresh/worker-react-refresh.test.tsx": { "test/e2e/yarn-pnp/test/mdx-pages.test.ts": { "passed": [],
[ "+ \"config-turbopack when webpack is configured and config.turbopack is set does not warn\",", "+ \"config-turbopack when webpack is configured but Turbopack is not warns\"", "+ \"passed\": [\"worker-react-refresh does not cause any runtime errors\"]," ]
[ 44, 45, 60 ]
{ "additions": 37, "author": "vercel-release-bot", "deletions": 0, "html_url": "https://github.com/vercel/next.js/pull/78535", "issue_id": 78535, "merged_at": "2025-04-25T09:42:36Z", "omission_probability": 0.1, "pr_number": 78535, "repo": "vercel/next.js", "title": "Update Turbopack development test manifest", "total_changes": 37 }
307
diff --git a/docs/01-app/01-getting-started/01-installation.mdx b/docs/01-app/01-getting-started/01-installation.mdx index 3654e5c296c0e..09c4ce68e7988 100644 --- a/docs/01-app/01-getting-started/01-installation.mdx +++ b/docs/01-app/01-getting-started/01-installation.mdx @@ -202,7 +202,7 @@ export default function Document() { ### Create the `public` folder (optional) -Create a [`public` folder](/docs/app/building-your-application/optimizing/static-assets) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`). +Create a [`public` folder](/docs/app/api-reference/file-conventions/public-folder) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`). You can then reference these assets using the root path (`/`). For example, `public/profile.png` can be referenced as `/profile.png`: diff --git a/docs/01-app/01-getting-started/02-project-structure.mdx b/docs/01-app/01-getting-started/02-project-structure.mdx index bf1931022b151..aeefcaedcf982 100644 --- a/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/docs/01-app/01-getting-started/02-project-structure.mdx @@ -20,12 +20,12 @@ Top-level folders are used to organize your application's code and static assets height="525" /> -| | | -| ------------------------------------------------------------------------ | ---------------------------------- | -| [`app`](/docs/app/building-your-application/routing) | App Router | -| [`pages`](/docs/pages/building-your-application/routing) | Pages Router | -| [`public`](/docs/app/building-your-application/optimizing/static-assets) | Static assets to be served | -| [`src`](/docs/app/api-reference/file-conventions/src-folder) | Optional application source folder | +| | | +| ------------------------------------------------------------------ | ---------------------------------- | +| [`app`](/docs/app/building-your-application/routing) | App Router | +| [`pages`](/docs/pages/building-your-application/routing) | Pages Router | +| [`public`](/docs/app/api-reference/file-conventions/public-folder) | Static assets to be served | +| [`src`](/docs/app/api-reference/file-conventions/src-folder) | Optional application source folder | ### Top-level files diff --git a/docs/01-app/02-guides/production-checklist.mdx b/docs/01-app/02-guides/production-checklist.mdx index e5db5d649143c..3a25354a9fcc2 100644 --- a/docs/01-app/02-guides/production-checklist.mdx +++ b/docs/01-app/02-guides/production-checklist.mdx @@ -66,7 +66,7 @@ While building your application, we recommend using the following features to en - **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Parallel Data Fetching](/docs/app/building-your-application/data-fetching/fetching#parallel-and-sequential-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/building-your-application/data-fetching/fetching#preloading-data) where appropriate. - **[Data Caching](/docs/app/building-your-application/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). -- **[Static Images](/docs/app/building-your-application/optimizing/static-assets):** Use the `public` directory to automatically cache your application's static assets, e.g. images. +- **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. </AppOnly> @@ -75,7 +75,7 @@ While building your application, we recommend using the following features to en - **[API Routes](/docs/pages/building-your-application/routing/api-routes):** Use Route Handlers to access your backend resources, and prevent sensitive secrets from being exposed to the client. - **[Data Caching](/docs/pages/building-your-application/data-fetching/get-static-props):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `getStaticProps` are cached where appropriate. - **[Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration):** Use Incremental Static Regeneration to update static pages after they've been built, without rebuilding your entire site. -- **[Static Images](/docs/pages/building-your-application/optimizing/static-assets):** Use the `public` directory to automatically cache your application's static assets, e.g. images. +- **[Static Images](/docs/pages/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. </PagesOnly> diff --git a/docs/01-app/03-building-your-application/06-optimizing/11-static-assets.mdx b/docs/01-app/05-api-reference/03-file-conventions/public-folder.mdx similarity index 97% rename from docs/01-app/03-building-your-application/06-optimizing/11-static-assets.mdx rename to docs/01-app/05-api-reference/03-file-conventions/public-folder.mdx index 4955ea32a37a3..e87c019c4fb0d 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/11-static-assets.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/public-folder.mdx @@ -1,6 +1,6 @@ --- -title: Static Assets in `public` -nav_title: Static Assets +title: public Folder +nav_title: public description: Next.js allows you to serve static files, like images, in the public directory. You can learn how it works here. --- diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx index e6409f920a587..7418ba7452a34 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx @@ -63,13 +63,13 @@ While `assetPrefix` covers requests to `_next/static`, it does not influence the <AppOnly> -- Files in the [public](/docs/app/building-your-application/optimizing/static-assets) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself +- Files in the [public](/docs/app/api-reference/file-conventions/public-folder) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself </AppOnly> <PagesOnly> -- Files in the [public](/docs/pages/building-your-application/optimizing/static-assets) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself +- Files in the [public](/docs/pages/api-reference/file-conventions/public-folder) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself - `/_next/data/` requests for `getServerSideProps` pages. These requests will always be made against the main domain since they're not static. - `/_next/data/` requests for `getStaticProps` pages. These requests will always be made against the main domain to support [Incremental Static Generation](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration), even if you're not using it (for consistency). diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx index 050908cfb3347..2a8d7c93185ce 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx @@ -91,7 +91,7 @@ The order Next.js routes are checked is: 1. [headers](/docs/app/api-reference/config/next-config-js/headers) are checked/applied 2. [redirects](/docs/app/api-reference/config/next-config-js/redirects) are checked/applied 3. `beforeFiles` rewrites are checked/applied -4. static files from the [public directory](/docs/app/building-your-application/optimizing/static-assets), `_next/static` files, and non-dynamic pages are checked/served +4. static files from the [public directory](/docs/app/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served 5. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match 6. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use [fallback: true/'blocking'](/docs/pages/api-reference/functions/get-static-paths#fallback-true) in `getStaticPaths`, the fallback `rewrites` defined in your `next.config.js` will _not_ be run. @@ -102,7 +102,7 @@ The order Next.js routes are checked is: 1. [headers](/docs/pages/api-reference/config/next-config-js/headers) are checked/applied 2. [redirects](/docs/pages/api-reference/config/next-config-js/redirects) are checked/applied 3. `beforeFiles` rewrites are checked/applied -4. static files from the [public directory](/docs/pages/building-your-application/optimizing/static-assets), `_next/static` files, and non-dynamic pages are checked/served +4. static files from the [public directory](/docs/pages/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served 5. `afterFiles` rewrites are checked/applied, if one of these rewrites is matched we check dynamic routes/static files after each match 6. `fallback` rewrites are checked/applied, these are applied before rendering the 404 page and after dynamic routes/all static assets have been checked. If you use [fallback: true/'blocking'](/docs/pages/api-reference/functions/get-static-paths#fallback-true) in `getStaticPaths`, the fallback `rewrites` defined in your `next.config.js` will _not_ be run. diff --git a/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx b/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx index 629edd0d2eb3e..bbdb5fe9c2068 100644 --- a/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx +++ b/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx @@ -185,7 +185,7 @@ export async function middleware(req: NextRequest) { } ``` -This [Middleware](/docs/pages/building-your-application/routing/middleware) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/building-your-application/optimizing/static-assets) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`. +This [Middleware](/docs/pages/building-your-application/routing/middleware) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/api-reference/file-conventions/public-folder) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`. ### Disabling Automatic Locale Detection diff --git a/docs/02-pages/03-building-your-application/05-optimizing/05-static-assets.mdx b/docs/02-pages/04-api-reference/02-file-conventions/public-folder.mdx similarity index 82% rename from docs/02-pages/03-building-your-application/05-optimizing/05-static-assets.mdx rename to docs/02-pages/04-api-reference/02-file-conventions/public-folder.mdx index 42da0d2ae7a07..436210bcf67ff 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/05-static-assets.mdx +++ b/docs/02-pages/04-api-reference/02-file-conventions/public-folder.mdx @@ -1,7 +1,8 @@ --- -title: Static Assets +title: public Folder +nav_title: public description: Next.js allows you to serve static files, like images, in the public directory. You can learn how it works here. -source: app/building-your-application/optimizing/static-assets +source: app/api-reference/file-conventions/public-folder --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/errors/can-not-output-to-public.mdx b/errors/can-not-output-to-public.mdx index c6e53b741749f..f9748ea7e2de2 100644 --- a/errors/can-not-output-to-public.mdx +++ b/errors/can-not-output-to-public.mdx @@ -14,4 +14,4 @@ Use a different `distDir` or export to a different folder. ## Useful Links -- [Static file serving docs](/docs/pages/building-your-application/optimizing/static-assets) +- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder) diff --git a/errors/can-not-output-to-static.mdx b/errors/can-not-output-to-static.mdx index e6ab400f479ab..c07c25f84a3e3 100644 --- a/errors/can-not-output-to-static.mdx +++ b/errors/can-not-output-to-static.mdx @@ -14,4 +14,4 @@ Use a different `distDir` or export to a different folder. ## Useful Links -- [Static file serving docs](/docs/pages/building-your-application/optimizing/static-assets) +- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder) diff --git a/errors/conflicting-public-file-page.mdx b/errors/conflicting-public-file-page.mdx index 301f663b0ae1b..5aaa33fe260ec 100644 --- a/errors/conflicting-public-file-page.mdx +++ b/errors/conflicting-public-file-page.mdx @@ -30,4 +30,4 @@ pages/ ## Useful Links -- [Static file serving docs](/docs/pages/building-your-application/optimizing/static-assets) +- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder) diff --git a/errors/custom-document-image-import.mdx b/errors/custom-document-image-import.mdx index f646c105fd72c..13fadc5932edd 100644 --- a/errors/custom-document-image-import.mdx +++ b/errors/custom-document-image-import.mdx @@ -44,5 +44,5 @@ module.exports = { - [Custom `Document`](/docs/pages/building-your-application/routing/custom-document) - [Custom `App`](/docs/pages/building-your-application/routing/custom-app) -- [Static File Serving](/docs/pages/building-your-application/optimizing/static-assets) +- [Static File Serving](/docs/pages/api-reference/file-conventions/public-folder) - [Disable Static Image Imports](/docs/pages/api-reference/components/image#disablestaticimages) diff --git a/errors/static-dir-deprecated.mdx b/errors/static-dir-deprecated.mdx index be9571d470574..de63480be4466 100644 --- a/errors/static-dir-deprecated.mdx +++ b/errors/static-dir-deprecated.mdx @@ -35,4 +35,4 @@ You can move your `static` directory inside of the `public` directory and all UR ## Useful Links -- [Static file serving docs](/docs/pages/building-your-application/optimizing/static-assets) +- [Static file serving docs](/docs/pages/api-reference/file-conventions/public-folder)
diff --git a/docs/01-app/01-getting-started/01-installation.mdx b/docs/01-app/01-getting-started/01-installation.mdx index 3654e5c296c0e..09c4ce68e7988 100644 --- a/docs/01-app/01-getting-started/01-installation.mdx +++ b/docs/01-app/01-getting-started/01-installation.mdx @@ -202,7 +202,7 @@ export default function Document() { ### Create the `public` folder (optional) +Create a [`public` folder](/docs/app/api-reference/file-conventions/public-folder) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`). You can then reference these assets using the root path (`/`). For example, `public/profile.png` can be referenced as `/profile.png`: diff --git a/docs/01-app/01-getting-started/02-project-structure.mdx b/docs/01-app/01-getting-started/02-project-structure.mdx index bf1931022b151..aeefcaedcf982 100644 --- a/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/docs/01-app/01-getting-started/02-project-structure.mdx @@ -20,12 +20,12 @@ Top-level folders are used to organize your application's code and static assets height="525" /> -| | | -| ------------------------------------------------------------------------ | ---------------------------------- | -| [`app`](/docs/app/building-your-application/routing) | App Router | -| [`public`](/docs/app/building-your-application/optimizing/static-assets) | Static assets to be served | -| [`src`](/docs/app/api-reference/file-conventions/src-folder) | Optional application source folder | +| | | +| ------------------------------------------------------------------ | ---------------------------------- | +| [`app`](/docs/app/building-your-application/routing) | App Router | +| [`public`](/docs/app/api-reference/file-conventions/public-folder) | Static assets to be served | +| [`src`](/docs/app/api-reference/file-conventions/src-folder) | Optional application source folder | ### Top-level files diff --git a/docs/01-app/02-guides/production-checklist.mdx b/docs/01-app/02-guides/production-checklist.mdx index e5db5d649143c..3a25354a9fcc2 100644 --- a/docs/01-app/02-guides/production-checklist.mdx +++ b/docs/01-app/02-guides/production-checklist.mdx @@ -66,7 +66,7 @@ While building your application, we recommend using the following features to en - **[Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming):** Use Loading UI and React Suspense to progressively send UI from the server to the client, and prevent the whole route from blocking while data is being fetched. - **[Parallel Data Fetching](/docs/app/building-your-application/data-fetching/fetching#parallel-and-sequential-data-fetching):** Reduce network waterfalls by fetching data in parallel, where appropriate. Also, consider [preloading data](/docs/app/building-your-application/data-fetching/fetching#preloading-data) where appropriate. - **[Data Caching](/docs/app/building-your-application/caching#data-cache):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `fetch` are [cached](/docs/app/api-reference/functions/unstable_cache). -- **[Static Images](/docs/app/building-your-application/optimizing/static-assets):** Use the `public` directory to automatically cache your application's static assets, e.g. images. +- **[Static Images](/docs/app/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. @@ -75,7 +75,7 @@ While building your application, we recommend using the following features to en - **[API Routes](/docs/pages/building-your-application/routing/api-routes):** Use Route Handlers to access your backend resources, and prevent sensitive secrets from being exposed to the client. - **[Data Caching](/docs/pages/building-your-application/data-fetching/get-static-props):** Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use `getStaticProps` are cached where appropriate. - **[Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration):** Use Incremental Static Regeneration to update static pages after they've been built, without rebuilding your entire site. -- **[Static Images](/docs/pages/building-your-application/optimizing/static-assets):** Use the `public` directory to automatically cache your application's static assets, e.g. images. +- **[Static Images](/docs/pages/api-reference/file-conventions/public-folder):** Use the `public` directory to automatically cache your application's static assets, e.g. images. </PagesOnly> diff --git a/docs/01-app/03-building-your-application/06-optimizing/11-static-assets.mdx b/docs/01-app/05-api-reference/03-file-conventions/public-folder.mdx similarity index 97% rename from docs/01-app/03-building-your-application/06-optimizing/11-static-assets.mdx rename to docs/01-app/05-api-reference/03-file-conventions/public-folder.mdx index 4955ea32a37a3..e87c019c4fb0d 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/11-static-assets.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/public-folder.mdx @@ -1,6 +1,6 @@ -title: Static Assets in `public` -nav_title: Static Assets diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx index e6409f920a587..7418ba7452a34 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/assetPrefix.mdx @@ -63,13 +63,13 @@ While `assetPrefix` covers requests to `_next/static`, it does not influence the <AppOnly> -- Files in the [public](/docs/app/building-your-application/optimizing/static-assets) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself +- Files in the [public](/docs/app/api-reference/file-conventions/public-folder) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself <PagesOnly> -- Files in the [public](/docs/pages/building-your-application/optimizing/static-assets) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself +- Files in the [public](/docs/pages/api-reference/file-conventions/public-folder) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself - `/_next/data/` requests for `getServerSideProps` pages. These requests will always be made against the main domain since they're not static. - `/_next/data/` requests for `getStaticProps` pages. These requests will always be made against the main domain to support [Incremental Static Generation](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration), even if you're not using it (for consistency). diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx index 050908cfb3347..2a8d7c93185ce 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/rewrites.mdx @@ -91,7 +91,7 @@ The order Next.js routes are checked is: 1. [headers](/docs/app/api-reference/config/next-config-js/headers) are checked/applied 2. [redirects](/docs/app/api-reference/config/next-config-js/redirects) are checked/applied -4. static files from the [public directory](/docs/app/building-your-application/optimizing/static-assets), `_next/static` files, and non-dynamic pages are checked/served +4. static files from the [public directory](/docs/app/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served @@ -102,7 +102,7 @@ The order Next.js routes are checked is: 1. [headers](/docs/pages/api-reference/config/next-config-js/headers) are checked/applied 2. [redirects](/docs/pages/api-reference/config/next-config-js/redirects) are checked/applied -4. static files from the [public directory](/docs/pages/building-your-application/optimizing/static-assets), `_next/static` files, and non-dynamic pages are checked/served +4. static files from the [public directory](/docs/pages/api-reference/file-conventions/public-folder), `_next/static` files, and non-dynamic pages are checked/served diff --git a/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx b/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx index 629edd0d2eb3e..bbdb5fe9c2068 100644 --- a/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx +++ b/docs/02-pages/03-building-your-application/01-routing/10-internationalization.mdx @@ -185,7 +185,7 @@ export async function middleware(req: NextRequest) { } ``` +This [Middleware](/docs/pages/building-your-application/routing/middleware) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/api-reference/file-conventions/public-folder) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`. ### Disabling Automatic Locale Detection diff --git a/docs/02-pages/03-building-your-application/05-optimizing/05-static-assets.mdx b/docs/02-pages/04-api-reference/02-file-conventions/public-folder.mdx similarity index 82% rename from docs/02-pages/03-building-your-application/05-optimizing/05-static-assets.mdx rename to docs/02-pages/04-api-reference/02-file-conventions/public-folder.mdx index 42da0d2ae7a07..436210bcf67ff 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/05-static-assets.mdx +++ b/docs/02-pages/04-api-reference/02-file-conventions/public-folder.mdx @@ -1,7 +1,8 @@ -title: Static Assets -source: app/building-your-application/optimizing/static-assets +source: app/api-reference/file-conventions/public-folder {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/errors/can-not-output-to-public.mdx b/errors/can-not-output-to-public.mdx index c6e53b741749f..f9748ea7e2de2 100644 --- a/errors/can-not-output-to-public.mdx +++ b/errors/can-not-output-to-public.mdx diff --git a/errors/can-not-output-to-static.mdx b/errors/can-not-output-to-static.mdx index e6ab400f479ab..c07c25f84a3e3 100644 --- a/errors/can-not-output-to-static.mdx +++ b/errors/can-not-output-to-static.mdx diff --git a/errors/conflicting-public-file-page.mdx b/errors/conflicting-public-file-page.mdx index 301f663b0ae1b..5aaa33fe260ec 100644 --- a/errors/conflicting-public-file-page.mdx +++ b/errors/conflicting-public-file-page.mdx @@ -30,4 +30,4 @@ pages/ diff --git a/errors/custom-document-image-import.mdx b/errors/custom-document-image-import.mdx index f646c105fd72c..13fadc5932edd 100644 --- a/errors/custom-document-image-import.mdx +++ b/errors/custom-document-image-import.mdx @@ -44,5 +44,5 @@ module.exports = { - [Custom `Document`](/docs/pages/building-your-application/routing/custom-document) - [Custom `App`](/docs/pages/building-your-application/routing/custom-app) -- [Static File Serving](/docs/pages/building-your-application/optimizing/static-assets) +- [Static File Serving](/docs/pages/api-reference/file-conventions/public-folder) - [Disable Static Image Imports](/docs/pages/api-reference/components/image#disablestaticimages) diff --git a/errors/static-dir-deprecated.mdx b/errors/static-dir-deprecated.mdx index be9571d470574..de63480be4466 100644 --- a/errors/static-dir-deprecated.mdx +++ b/errors/static-dir-deprecated.mdx @@ -35,4 +35,4 @@ You can move your `static` directory inside of the `public` directory and all UR
[ "-Create a [`public` folder](/docs/app/building-your-application/optimizing/static-assets) at the root of your project to store static assets such as images, fonts, etc. Files inside `public` can then be referenced by your code starting from the base URL (`/`).", "-| [`pages`](/docs/pages/building-your-application/routing) | Pages Router |", "+| [`pages`](/docs/pages/building-your-application/routing) | Pages Router |", "-This [Middleware](/docs/pages/building-your-application/routing/middleware) skips adding the default prefix to [API Routes](/docs/pages/building-your-application/routing/api-routes) and [public](/docs/pages/building-your-application/optimizing/static-assets) files like fonts or images. If a request is made to the default locale, we redirect to our prefix `/en`." ]
[ 8, 24, 30, 124 ]
{ "additions": 24, "author": "delbaoliveira", "deletions": 23, "html_url": "https://github.com/vercel/next.js/pull/78531", "issue_id": 78531, "merged_at": "2025-04-25T07:08:57Z", "omission_probability": 0.1, "pr_number": 78531, "repo": "vercel/next.js", "title": "Docs IA 2.0: Create `public` folder API reference", "total_changes": 47 }
308
diff --git a/examples/reproduction-template/package.json b/examples/reproduction-template/package.json index d37e611be27ce..04673970a995c 100644 --- a/examples/reproduction-template/package.json +++ b/examples/reproduction-template/package.json @@ -7,8 +7,8 @@ }, "dependencies": { "next": "canary", - "react": "^19.0.0", - "react-dom": "^19.0.0" + "react": "19.1.0", + "react-dom": "19.1.0" }, "devDependencies": { "@types/node": "^22", diff --git a/packages/create-next-app/templates/index.ts b/packages/create-next-app/templates/index.ts index 707cb5d55f091..ceedc7e2cdbd4 100644 --- a/packages/create-next-app/templates/index.ts +++ b/packages/create-next-app/templates/index.ts @@ -13,7 +13,7 @@ import { GetTemplateFileArgs, InstallTemplateArgs } from "./types"; // Do not rename or format. sync-react script relies on this line. // prettier-ignore -const nextjsReactPeerVersion = "^19.0.0"; +const nextjsReactPeerVersion = "19.1.0"; /** * Get the file path for a given file in a template, e.g. "next.config.js". diff --git a/run-tests.js b/run-tests.js index c4cd08b2516c7..bb71421b18fc9 100644 --- a/run-tests.js +++ b/run-tests.js @@ -19,7 +19,7 @@ const { getTestFilter } = require('./test/get-test-filter') // Do not rename or format. sync-react script relies on this line. // prettier-ignore -const nextjsReactPeerVersion = "^19.0.0"; +const nextjsReactPeerVersion = "19.1.0"; let argv = require('yargs/yargs')(process.argv.slice(2)) .string('type') diff --git a/scripts/sync-react.js b/scripts/sync-react.js index 7c35e81bb057f..cf27f3da668ee 100644 --- a/scripts/sync-react.js +++ b/scripts/sync-react.js @@ -5,6 +5,7 @@ const fsp = require('fs/promises') const process = require('process') const execa = require('execa') const { Octokit } = require('octokit') +const SemVer = require('semver') const yargs = require('yargs') /** @type {any} */ @@ -17,9 +18,13 @@ const pullRequestReviewers = ['eps1lon'] /** * Set to `null` to automatically sync the React version of Pages Router with App Router React version. * Set to a specific version to override the Pages Router React version e.g. `^19.0.0`. + * + * "Active" just refers to our current development practice. While we do support + * React 18 in pages router, we don't focus our development process on it considering + * it does not receive new features. * @type {string | null} */ -const pagesRouterReact = '^19.0.0' +const activePagesRouterReact = '^19.0.0' const defaultLatestChannel = 'canary' const filesReferencingReactPeerDependencyVersion = [ @@ -176,6 +181,31 @@ async function getChangelogFromGitHub(baseSha, newSha) { return changelog.length > 0 ? changelog.join('\n') : null } +async function findHighestNPMReactVersion(versionLike) { + const { stdout, stderr } = await execa( + 'npm', + ['--silent', 'view', '--json', `react@${versionLike}`, 'version'], + { + // Avoid "Usage Error: This project is configured to use pnpm". + cwd: '/tmp', + } + ) + if (stderr) { + console.error(stderr) + throw new Error( + `Failed to read highest react@${versionLike} version from npm.` + ) + } + + const result = JSON.parse(stdout) + + return typeof result === 'string' + ? result + : result.sort((a, b) => { + return SemVer.compare(b, a) + })[0] +} + async function main() { const cwd = process.cwd() const errors = [] @@ -232,19 +262,7 @@ async function main() { // TODO: Fork arguments in GitHub workflow to ensure `--version ""` is considered a mistake newVersionStr === '' ) { - const { stdout, stderr } = await execa( - 'npm', - ['--silent', 'view', `react@${defaultLatestChannel}`, 'version'], - { - // Avoid "Usage Error: This project is configured to use pnpm". - cwd: '/tmp', - } - ) - if (stderr) { - console.error(stderr) - throw new Error('Failed to read latest React canary version from npm.') - } - newVersionStr = stdout.trim() + newVersionStr = await findHighestNPMReactVersion(defaultLatestChannel) console.log( `--version was not provided. Using react@${defaultLatestChannel}: ${newVersionStr}` ) @@ -325,10 +343,14 @@ Or, run this command with no arguments to use the most recently published versio ) } - const syncPagesRouterReact = pagesRouterReact === null - const pagesRouterReactVersion = syncPagesRouterReact + const syncPagesRouterReact = activePagesRouterReact === null + const newActivePagesRouterReactVersion = syncPagesRouterReact ? newVersionStr - : pagesRouterReact + : activePagesRouterReact + const pagesRouterReactVersion = `^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ${newActivePagesRouterReactVersion}` + const highestPagesRouterReactVersion = await findHighestNPMReactVersion( + pagesRouterReactVersion + ) const { sha: baseSha, dateString: baseDateString } = baseVersionInfo if (syncPagesRouterReact) { @@ -336,13 +358,13 @@ Or, run this command with no arguments to use the most recently published versio const filePath = path.join(cwd, fileName) const previousSource = await fsp.readFile(filePath, 'utf-8') const updatedSource = previousSource.replace( - `const nextjsReactPeerVersion = "${baseVersionStr}";`, - `const nextjsReactPeerVersion = "${pagesRouterReactVersion}";` + /const nextjsReactPeerVersion = "[^"]+";/, + `const nextjsReactPeerVersion = "${highestPagesRouterReactVersion}";` ) - if (pagesRouterReact === null && updatedSource === previousSource) { + if (activePagesRouterReact === null && updatedSource === previousSource) { errors.push( new Error( - `${fileName}: Failed to update ${baseVersionStr} to ${pagesRouterReactVersion}. Is this file still referencing the React peer dependency version?` + `${fileName}: Failed to update ${baseVersionStr} to ${highestPagesRouterReactVersion}. Is this file still referencing the React peer dependency version?` ) ) } else { @@ -356,10 +378,10 @@ Or, run this command with no arguments to use the most recently published versio const packageJson = await fsp.readFile(packageJsonPath, 'utf-8') const manifest = JSON.parse(packageJson) if (manifest.dependencies['react']) { - manifest.dependencies['react'] = pagesRouterReactVersion + manifest.dependencies['react'] = highestPagesRouterReactVersion } if (manifest.dependencies['react-dom']) { - manifest.dependencies['react-dom'] = pagesRouterReactVersion + manifest.dependencies['react-dom'] = highestPagesRouterReactVersion } await fsp.writeFile( packageJsonPath, @@ -379,12 +401,10 @@ Or, run this command with no arguments to use the most recently published versio const manifest = JSON.parse(packageJson) // Need to specify last supported RC version to avoid breaking changes. if (manifest.peerDependencies['react']) { - manifest.peerDependencies['react'] = - `^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ${pagesRouterReactVersion}` + manifest.peerDependencies['react'] = pagesRouterReactVersion } if (manifest.peerDependencies['react-dom']) { - manifest.peerDependencies['react-dom'] = - `^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ${pagesRouterReactVersion}` + manifest.peerDependencies['react-dom'] = pagesRouterReactVersion } await fsp.writeFile( packageJsonPath, diff --git a/test/.stats-app/package.json b/test/.stats-app/package.json index 685785b202747..b60e79da78957 100644 --- a/test/.stats-app/package.json +++ b/test/.stats-app/package.json @@ -4,8 +4,8 @@ "license": "MIT", "dependencies": { "next": "latest", - "react": "^19.0.0", - "react-dom": "^19.0.0" + "react": "19.1.0", + "react-dom": "19.1.0" }, "engines": { "node": ">=18.18.0" diff --git a/test/development/acceptance/hydration-error.test.ts b/test/development/acceptance/hydration-error.test.ts index 6390ccf734a9a..99bbbc6c3c2fc 100644 --- a/test/development/acceptance/hydration-error.test.ts +++ b/test/development/acceptance/hydration-error.test.ts @@ -11,11 +11,6 @@ describe('Error overlay for hydration errors in Pages router', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), skipStart: true, - // TODO: once Next.js minimal React version is 19.1, remove this override. - dependencies: { - react: isReact18 ? '^18.3.1' : '^19.1.0', - 'react-dom': isReact18 ? '^18.3.1' : '^19.1.0', - }, }) it('includes a React docs link when hydration error does occur', async () => { diff --git a/test/e2e/next-test/first-time-setup-js/package.json b/test/e2e/next-test/first-time-setup-js/package.json index 42cae18466013..ffdd279ec5ebe 100644 --- a/test/e2e/next-test/first-time-setup-js/package.json +++ b/test/e2e/next-test/first-time-setup-js/package.json @@ -8,7 +8,7 @@ }, "dependencies": { "next": "canary", - "react": "^19.0.0", - "react-dom": "^19.0.0" + "react": "19.1.0", + "react-dom": "19.1.0" } } diff --git a/test/e2e/next-test/first-time-setup-ts/package.json b/test/e2e/next-test/first-time-setup-ts/package.json index 13e6a69061a04..2779abb8cbdea 100644 --- a/test/e2e/next-test/first-time-setup-ts/package.json +++ b/test/e2e/next-test/first-time-setup-ts/package.json @@ -8,8 +8,8 @@ }, "dependencies": { "next": "canary", - "react": "^19.0.0", - "react-dom": "^19.0.0" + "react": "19.1.0", + "react-dom": "19.1.0" }, "devDependencies": { "@types/react": "^18", diff --git a/test/lib/next-modes/base.ts b/test/lib/next-modes/base.ts index 44fc2e004b094..8ff628d0eade5 100644 --- a/test/lib/next-modes/base.ts +++ b/test/lib/next-modes/base.ts @@ -58,7 +58,7 @@ type OmitFirstArgument<F> = F extends ( // Do not rename or format. sync-react script relies on this line. // prettier-ignore -const nextjsReactPeerVersion = "^19.0.0"; +const nextjsReactPeerVersion = "19.1.0"; export class NextInstance { protected files: ResolvedFileConfig
diff --git a/examples/reproduction-template/package.json b/examples/reproduction-template/package.json index d37e611be27ce..04673970a995c 100644 --- a/examples/reproduction-template/package.json +++ b/examples/reproduction-template/package.json @@ -7,8 +7,8 @@ "@types/node": "^22", diff --git a/packages/create-next-app/templates/index.ts b/packages/create-next-app/templates/index.ts index 707cb5d55f091..ceedc7e2cdbd4 100644 --- a/packages/create-next-app/templates/index.ts +++ b/packages/create-next-app/templates/index.ts @@ -13,7 +13,7 @@ import { GetTemplateFileArgs, InstallTemplateArgs } from "./types"; * Get the file path for a given file in a template, e.g. "next.config.js". diff --git a/run-tests.js b/run-tests.js index c4cd08b2516c7..bb71421b18fc9 100644 --- a/run-tests.js +++ b/run-tests.js @@ -19,7 +19,7 @@ const { getTestFilter } = require('./test/get-test-filter') let argv = require('yargs/yargs')(process.argv.slice(2)) .string('type') diff --git a/scripts/sync-react.js b/scripts/sync-react.js index 7c35e81bb057f..cf27f3da668ee 100644 --- a/scripts/sync-react.js +++ b/scripts/sync-react.js @@ -5,6 +5,7 @@ const fsp = require('fs/promises') const process = require('process') const execa = require('execa') const { Octokit } = require('octokit') +const SemVer = require('semver') const yargs = require('yargs') /** @type {any} */ @@ -17,9 +18,13 @@ const pullRequestReviewers = ['eps1lon'] * Set to `null` to automatically sync the React version of Pages Router with App Router React version. * Set to a specific version to override the Pages Router React version e.g. `^19.0.0`. + * "Active" just refers to our current development practice. While we do support + * React 18 in pages router, we don't focus our development process on it considering + * it does not receive new features. * @type {string | null} */ -const pagesRouterReact = '^19.0.0' +const activePagesRouterReact = '^19.0.0' const defaultLatestChannel = 'canary' const filesReferencingReactPeerDependencyVersion = [ @@ -176,6 +181,31 @@ async function getChangelogFromGitHub(baseSha, newSha) { return changelog.length > 0 ? changelog.join('\n') : null +async function findHighestNPMReactVersion(versionLike) { + const { stdout, stderr } = await execa( + 'npm', + ['--silent', 'view', '--json', `react@${versionLike}`, 'version'], + // Avoid "Usage Error: This project is configured to use pnpm". + cwd: '/tmp', + } + if (stderr) { + console.error(stderr) + throw new Error( + `Failed to read highest react@${versionLike} version from npm.` + ) + } + const result = JSON.parse(stdout) + return typeof result === 'string' + ? result + : result.sort((a, b) => { + return SemVer.compare(b, a) + })[0] +} async function main() { const cwd = process.cwd() const errors = [] @@ -232,19 +262,7 @@ async function main() { // TODO: Fork arguments in GitHub workflow to ensure `--version ""` is considered a mistake newVersionStr === '' ) { - const { stdout, stderr } = await execa( - 'npm', - ['--silent', 'view', `react@${defaultLatestChannel}`, 'version'], - // Avoid "Usage Error: This project is configured to use pnpm". - cwd: '/tmp', - } - ) - if (stderr) { - console.error(stderr) - throw new Error('Failed to read latest React canary version from npm.') + newVersionStr = await findHighestNPMReactVersion(defaultLatestChannel) console.log( `--version was not provided. Using react@${defaultLatestChannel}: ${newVersionStr}` @@ -325,10 +343,14 @@ Or, run this command with no arguments to use the most recently published versio - const syncPagesRouterReact = pagesRouterReact === null - const pagesRouterReactVersion = syncPagesRouterReact + const syncPagesRouterReact = activePagesRouterReact === null + const newActivePagesRouterReactVersion = syncPagesRouterReact ? newVersionStr - : pagesRouterReact + : activePagesRouterReact + const pagesRouterReactVersion = `^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ${newActivePagesRouterReactVersion}` + const highestPagesRouterReactVersion = await findHighestNPMReactVersion( + pagesRouterReactVersion const { sha: baseSha, dateString: baseDateString } = baseVersionInfo if (syncPagesRouterReact) { @@ -336,13 +358,13 @@ Or, run this command with no arguments to use the most recently published versio const filePath = path.join(cwd, fileName) const previousSource = await fsp.readFile(filePath, 'utf-8') const updatedSource = previousSource.replace( - `const nextjsReactPeerVersion = "${baseVersionStr}";`, - `const nextjsReactPeerVersion = "${pagesRouterReactVersion}";` + /const nextjsReactPeerVersion = "[^"]+";/, + `const nextjsReactPeerVersion = "${highestPagesRouterReactVersion}";` ) - if (pagesRouterReact === null && updatedSource === previousSource) { + if (activePagesRouterReact === null && updatedSource === previousSource) { errors.push( new Error( - `${fileName}: Failed to update ${baseVersionStr} to ${pagesRouterReactVersion}. Is this file still referencing the React peer dependency version?` + `${fileName}: Failed to update ${baseVersionStr} to ${highestPagesRouterReactVersion}. Is this file still referencing the React peer dependency version?` ) ) } else { @@ -356,10 +378,10 @@ Or, run this command with no arguments to use the most recently published versio const packageJson = await fsp.readFile(packageJsonPath, 'utf-8') if (manifest.dependencies['react']) { - manifest.dependencies['react'] = pagesRouterReactVersion if (manifest.dependencies['react-dom']) { - manifest.dependencies['react-dom'] = pagesRouterReactVersion + manifest.dependencies['react-dom'] = highestPagesRouterReactVersion @@ -379,12 +401,10 @@ Or, run this command with no arguments to use the most recently published versio // Need to specify last supported RC version to avoid breaking changes. if (manifest.peerDependencies['react']) { - manifest.peerDependencies['react'] = if (manifest.peerDependencies['react-dom']) { - manifest.peerDependencies['react-dom'] = + manifest.peerDependencies['react-dom'] = pagesRouterReactVersion diff --git a/test/.stats-app/package.json b/test/.stats-app/package.json index 685785b202747..b60e79da78957 100644 --- a/test/.stats-app/package.json +++ b/test/.stats-app/package.json @@ -4,8 +4,8 @@ "license": "MIT", "next": "latest", "engines": { "node": ">=18.18.0" diff --git a/test/development/acceptance/hydration-error.test.ts b/test/development/acceptance/hydration-error.test.ts index 6390ccf734a9a..99bbbc6c3c2fc 100644 --- a/test/development/acceptance/hydration-error.test.ts +++ b/test/development/acceptance/hydration-error.test.ts @@ -11,11 +11,6 @@ describe('Error overlay for hydration errors in Pages router', () => { const { next } = nextTestSetup({ files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), skipStart: true, - // TODO: once Next.js minimal React version is 19.1, remove this override. - dependencies: { - react: isReact18 ? '^18.3.1' : '^19.1.0', - }, }) it('includes a React docs link when hydration error does occur', async () => { diff --git a/test/e2e/next-test/first-time-setup-js/package.json b/test/e2e/next-test/first-time-setup-js/package.json index 42cae18466013..ffdd279ec5ebe 100644 --- a/test/e2e/next-test/first-time-setup-js/package.json +++ b/test/e2e/next-test/first-time-setup-js/package.json @@ -8,7 +8,7 @@ diff --git a/test/e2e/next-test/first-time-setup-ts/package.json b/test/e2e/next-test/first-time-setup-ts/package.json index 13e6a69061a04..2779abb8cbdea 100644 --- a/test/e2e/next-test/first-time-setup-ts/package.json +++ b/test/e2e/next-test/first-time-setup-ts/package.json @@ -8,8 +8,8 @@ "@types/react": "^18", diff --git a/test/lib/next-modes/base.ts b/test/lib/next-modes/base.ts index 44fc2e004b094..8ff628d0eade5 100644 --- a/test/lib/next-modes/base.ts +++ b/test/lib/next-modes/base.ts @@ -58,7 +58,7 @@ type OmitFirstArgument<F> = F extends ( export class NextInstance { protected files: ResolvedFileConfig
[ "+ *", "+ {", "- {", "- }", "- newVersionStr = stdout.trim()", "+ manifest.dependencies['react'] = highestPagesRouterReactVersion", "+ manifest.peerDependencies['react'] = pagesRouterReactVersion", "- 'react-dom': isReact18 ? '^18.3.1' : '^19.1.0'," ]
[ 57, 76, 107, 115, 116, 162, 176, 211 ]
{ "additions": 58, "author": "eps1lon", "deletions": 43, "html_url": "https://github.com/vercel/next.js/pull/77895", "issue_id": 77895, "merged_at": "2025-04-10T12:39:55Z", "omission_probability": 0.1, "pr_number": 77895, "repo": "vercel/next.js", "title": "[test] Use React 19.1 everywhere", "total_changes": 101 }
309
diff --git a/package.json b/package.json index 2c939d1d0832b..0fc8077498e2c 100644 --- a/package.json +++ b/package.json @@ -253,7 +253,6 @@ "semver": "7.3.7", "shell-quote": "1.7.3", "strip-ansi": "6.0.0", - "styled-components": "6.0.0-rc.3", "styled-jsx": "5.1.6", "styled-jsx-plugin-postcss": "3.0.2", "swr": "^2.2.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a017bf6fd7c5..4cda2620327a6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -549,9 +549,6 @@ importers: strip-ansi: specifier: 6.0.0 version: 6.0.0 - styled-components: - specifier: 6.0.0-rc.3 - version: 6.0.0-rc.3([email protected]([email protected]))([email protected]) styled-jsx: specifier: 5.1.6 version: 5.1.6(@babel/[email protected])([email protected])([email protected]) @@ -1937,13 +1934,6 @@ packages: engines: {node: '>= 12.0.0'} hasBin: true - '@babel/[email protected]': - resolution: {integrity: sha512-TOKytQ9uQW9c4np8F+P7ZfPINy5Kv+pizDIUwSVH8X5zHgYHV4AA8HE5LA450xXeu4jEfmUckTYvv1I4S26M/g==} - engines: {node: '>=6.9.0'} - hasBin: true - peerDependencies: - '@babel/core': 7.22.5 - '@babel/[email protected]': resolution: {integrity: sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==} @@ -2136,10 +2126,6 @@ packages: resolution: {integrity: sha512-wbfdZ9w5vk0C0oyHqAJbc62+vet5prjj01jjJ8sKn3j9h3MQQlflEdXYvuqRWjHnM12coDEqiC1IRCi0U/EKwQ==} engines: {node: '>=6.9.0'} - '@babel/[email protected]': - resolution: {integrity: sha512-orajc5T2PsRYUN3ZryCEFeMDYwyw09c/pZeaQEZPH0MpKzSvn3e0uXsDBu3k03VI+9DBiRo+l22BfKTpKwa/Wg==} - engines: {node: '>=6.9.0'} - '@babel/[email protected]': resolution: {integrity: sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==} engines: {node: '>=6.9.0'} @@ -2387,12 +2373,6 @@ packages: peerDependencies: '@babel/core': 7.22.5 - '@babel/[email protected]': - resolution: {integrity: sha512-wNqc87qjLvsD1PIMQBzLn1bMuTlGzqLzM/1VGQ22Wm51cbCWS9k71ydp5iZS4hjwQNuTWSn/xbZkkusNENwtZg==} - engines: {node: '>=6.9.0'} - peerDependencies: - '@babel/core': 7.22.5 - '@babel/[email protected]': resolution: {integrity: sha512-cKp3dlQsFsEs5CWKnN7BnSHOd0EOW8EKpEjkoz1pO2E5KzIDNV9Ros1b0CnmbVgAGXJubOYVBOGCT1OmJwOI7w==} deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead. @@ -4967,9 +4947,6 @@ packages: '@napi-rs/[email protected]': resolution: {integrity: sha512-HAPjR3bnCsdXBsATpDIP5WCrw0JcACwhhrwIAQhiR46n+jm+a2F8kBsfseAuWtSyQ+H3Yebt2k43B5dy+04yMA==} - '@nicolo-ribaudo/[email protected]': - resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==} - '@nicolo-ribaudo/[email protected]': resolution: {integrity: sha512-54/JRvkLIzzDWshCWfuhadfrfZVPiElY8Fcgmg1HroEly/EDSszzhBAsarCux+D/kOslTRquNzuyGSmUSTTHGg==} @@ -7948,10 +7925,6 @@ packages: [email protected]: resolution: {integrity: sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow==} - [email protected]: - resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} - engines: {node: '>= 6'} - [email protected]: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} @@ -9999,9 +9972,6 @@ packages: [email protected]: resolution: {integrity: sha512-b1FMfwetIKymC0eioW7mTywihSQE4oLzQn1dB6rZB5fx/3NpNEdAWeCSMB+60/AeT0TCXsxzAlcYVEFCTAksWg==} - [email protected]: - resolution: {integrity: sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==} - [email protected]: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} @@ -10200,10 +10170,6 @@ packages: resolution: {integrity: sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==} deprecated: Glob versions prior to v9 are no longer supported - [email protected]: - resolution: {integrity: sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==} - deprecated: Glob versions prior to v9 are no longer supported - [email protected]: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} deprecated: Glob versions prior to v9 are no longer supported @@ -15399,9 +15365,6 @@ packages: resolution: {integrity: sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==} engines: {node: '>=8'} - [email protected]: - resolution: {integrity: sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==} - [email protected]: resolution: {integrity: sha512-1j0w61+eVxu7DawFJtnfYcvSv6qPFvfTaqzTQ2BLknVhHTwGS8sc63ZBF4rzkWMBVKybo4S5OBtDdZahh2A1xg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} @@ -15473,10 +15436,6 @@ packages: resolution: {integrity: sha512-3TYDR7xWt4dIqV2JauJr+EJeW356RXijHeUlO+8djJ+uBXPn8/2dpzBc8yQhh583sVvc9CvFAeQVgijsH+PNNg==} engines: {node: '>=0.10.0'} - [email protected]: - resolution: {integrity: sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==} - engines: {node: '>=6'} - [email protected]: resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} engines: {node: '>=8'} @@ -15906,17 +15865,6 @@ packages: [email protected]: resolution: {integrity: sha512-HFpbb5gr2ypci7Qw+IOhnP2zOU7e77b+rzM+wTzXzfi1PrtBCX0E7Pk4wL4iTLnhzZ+JgEGAhX81ebTg/aYjQw==} - [email protected]: - resolution: {integrity: sha512-5FbCTxynopck99GRwM5Ey0+VRp8pkQq69TwGOJJeYtR7gPvwGjNx8yBPLN7/dfxwwvn9ymOZYB19eQkv2k70wQ==} - engines: {node: '>= 16'} - peerDependencies: - babel-plugin-styled-components: '>= 2' - react: 19.2.0-canary-3fbfb9ba-20250409 - react-dom: 19.2.0-canary-3fbfb9ba-20250409 - peerDependenciesMeta: - babel-plugin-styled-components: - optional: true - [email protected]: resolution: {integrity: sha512-6xuteERUhLSLbztb2l2zhrxJpcW3eb7ooSMc3j5D51jiao6HZNaJoimmSnpUMji1qWxbAZD0Lee0ftB4atxoRA==} @@ -16369,9 +16317,6 @@ packages: [email protected]: resolution: {integrity: sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==} - [email protected]: - resolution: {integrity: sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==} - [email protected]: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} @@ -17585,20 +17530,6 @@ snapshots: '@ast-grep/cli-win32-ia32-msvc': 0.31.0 '@ast-grep/cli-win32-x64-msvc': 0.31.0 - '@babel/[email protected](@babel/[email protected])': - dependencies: - '@babel/core': 7.22.5 - '@jridgewell/trace-mapping': 0.3.22 - commander: 4.1.1 - convert-source-map: 1.9.0 - fs-readdir-recursive: 1.1.0 - glob: 7.2.0 - make-dir: 2.1.0 - slash: 2.0.0 - optionalDependencies: - '@nicolo-ribaudo/chokidar-2': 2.1.8-no-fsevents.3 - chokidar: 3.6.0 - '@babel/[email protected]': dependencies: '@babel/highlight': 7.22.20 @@ -17894,10 +17825,6 @@ snapshots: - supports-color optional: true - '@babel/[email protected]': - dependencies: - '@babel/types': 7.22.5 - '@babel/[email protected]': dependencies: '@babel/types': 7.22.5 @@ -18203,11 +18130,6 @@ snapshots: - supports-color optional: true - '@babel/[email protected](@babel/[email protected])': - dependencies: - '@babel/core': 7.22.5 - '@babel/helper-plugin-utils': 7.25.7 - '@babel/[email protected](@babel/[email protected])': dependencies: '@babel/core': 7.22.5 @@ -21391,9 +21313,6 @@ snapshots: '@napi-rs/[email protected]': {} - '@nicolo-ribaudo/[email protected]': - optional: true - '@nicolo-ribaudo/[email protected]': dependencies: eslint-scope: 5.1.1 @@ -24932,8 +24851,6 @@ snapshots: [email protected]: {} - [email protected]: {} - [email protected]: {} [email protected]: {} @@ -27788,8 +27705,6 @@ snapshots: [email protected]: {} - [email protected]: {} - [email protected]: {} [email protected]: @@ -28028,15 +27943,6 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 - [email protected]: - dependencies: - fs.realpath: 1.0.0 - inflight: 1.0.6 - inherits: 2.0.4 - minimatch: 3.0.4 - once: 1.4.0 - path-is-absolute: 1.0.1 - [email protected]: dependencies: fs.realpath: 1.0.0 @@ -34630,8 +34536,6 @@ snapshots: dependencies: kind-of: 6.0.3 - [email protected]: {} - [email protected]: dependencies: color: 4.2.3 @@ -34720,8 +34624,6 @@ snapshots: [email protected]: {} - [email protected]: {} - [email protected]: {} [email protected]: {} @@ -35211,29 +35113,6 @@ snapshots: dependencies: inline-style-parser: 0.1.1 - [email protected]([email protected]([email protected]))([email protected]): - dependencies: - '@babel/cli': 7.21.5(@babel/[email protected]) - '@babel/core': 7.22.5 - '@babel/helper-module-imports': 7.21.4 - '@babel/plugin-external-helpers': 7.18.6(@babel/[email protected]) - '@babel/plugin-proposal-class-properties': 7.18.6(@babel/[email protected]) - '@babel/plugin-proposal-object-rest-spread': 7.20.7(@babel/[email protected]) - '@babel/preset-env': 7.22.5(@babel/[email protected]) - '@babel/preset-react': 7.22.5(@babel/[email protected]) - '@babel/preset-typescript': 7.22.5(@babel/[email protected]) - '@babel/traverse': 7.22.5 - '@emotion/unitless': 0.8.1 - css-to-react-native: 3.2.0 - postcss: 8.4.31 - react: 19.2.0-canary-3fbfb9ba-20250409 - react-dom: 19.2.0-canary-3fbfb9ba-20250409([email protected]) - shallowequal: 1.1.0 - stylis: 4.2.0 - tslib: 2.5.3 - transitivePeerDependencies: - - supports-color - [email protected]: dependencies: postcss: 7.0.32 @@ -35744,8 +35623,6 @@ snapshots: [email protected]: {} - [email protected]: {} - [email protected]: {} [email protected]([email protected]): diff --git a/test/development/basic/styled-components-disabled.test.ts b/test/development/basic/styled-components-disabled.test.ts index 48fb6d5b6beb5..5ca0e31b0fde5 100644 --- a/test/development/basic/styled-components-disabled.test.ts +++ b/test/development/basic/styled-components-disabled.test.ts @@ -5,7 +5,7 @@ import { NextInstance } from 'e2e-utils' import { retry } from 'next-test-utils' // TODO: Somehow the warning doesn't show up with Turbopack, even though the transform is not enabled. -// TODO: It no longer shows up with Webpack either in tests. Manual repro does work though. +// TODO: It no longer shows up with Webpack either in tests. ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe.skip)( 'styled-components SWC transform', () => { diff --git a/test/development/basic/styled-components-disabled/.gitignore b/test/development/basic/styled-components-disabled/.gitignore new file mode 100644 index 0000000000000..c2658d7d1b318 --- /dev/null +++ b/test/development/basic/styled-components-disabled/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/test/development/basic/styled-components-disabled/package.json b/test/development/basic/styled-components-disabled/package.json new file mode 100644 index 0000000000000..52282b15f003f --- /dev/null +++ b/test/development/basic/styled-components-disabled/package.json @@ -0,0 +1,7 @@ +{ + "name": "styled-components-disabled", + "private": true, + "dependencies": { + "styled-components": "6.1.16" + } +} diff --git a/test/development/basic/styled-components-disabled/pages/index.js b/test/development/basic/styled-components-disabled/pages/index.js index 31bd1226e7689..55f57ff35a699 100644 --- a/test/development/basic/styled-components-disabled/pages/index.js +++ b/test/development/basic/styled-components-disabled/pages/index.js @@ -13,7 +13,7 @@ const Button = styled.a` /* The GitHub button is a primary button * edit this to target it specifically! */ ${(props) => - props.primary && + props.$primary && css` background: white; color: black; @@ -27,7 +27,7 @@ export default function Home() { href="https://github.com/styled-components/styled-components" target="_blank" rel="noopener" - primary + $primary > GitHub </Button> diff --git a/test/development/basic/styled-components/.gitignore b/test/development/basic/styled-components/.gitignore new file mode 100644 index 0000000000000..c2658d7d1b318 --- /dev/null +++ b/test/development/basic/styled-components/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/test/development/basic/styled-components/package.json b/test/development/basic/styled-components/package.json new file mode 100644 index 0000000000000..262a402dfe0ec --- /dev/null +++ b/test/development/basic/styled-components/package.json @@ -0,0 +1,7 @@ +{ + "name": "styled-components", + "private": true, + "dependencies": { + "styled-components": "6.1.16" + } +} diff --git a/test/development/basic/styled-components/pages/index.js b/test/development/basic/styled-components/pages/index.js index a40708a545465..6fbdc8380e8e2 100644 --- a/test/development/basic/styled-components/pages/index.js +++ b/test/development/basic/styled-components/pages/index.js @@ -13,7 +13,7 @@ const Button = styled.a` /* The GitHub button is a primary button * edit this to target it specifically! */ ${(props) => - props.primary && + props.$primary && css` background: white; color: black; @@ -33,7 +33,7 @@ export default function Home() { href="https://github.com/styled-components/styled-components" target="_blank" rel="noopener" - primary + $primary > GitHub </Button>
diff --git a/package.json b/package.json index 2c939d1d0832b..0fc8077498e2c 100644 --- a/package.json +++ b/package.json @@ -253,7 +253,6 @@ "semver": "7.3.7", "shell-quote": "1.7.3", "strip-ansi": "6.0.0", - "styled-components": "6.0.0-rc.3", "styled-jsx": "5.1.6", "styled-jsx-plugin-postcss": "3.0.2", "swr": "^2.2.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a017bf6fd7c5..4cda2620327a6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -549,9 +549,6 @@ importers: strip-ansi: specifier: 6.0.0 version: 6.0.0 - styled-components: - specifier: 6.0.0-rc.3 - version: 6.0.0-rc.3([email protected]([email protected]))([email protected]) styled-jsx: specifier: 5.1.6 version: 5.1.6(@babel/[email protected])([email protected])([email protected]) @@ -1937,13 +1934,6 @@ packages: engines: {node: '>= 12.0.0'} hasBin: true - '@babel/[email protected]': - hasBin: true resolution: {integrity: sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==} @@ -2136,10 +2126,6 @@ packages: resolution: {integrity: sha512-wbfdZ9w5vk0C0oyHqAJbc62+vet5prjj01jjJ8sKn3j9h3MQQlflEdXYvuqRWjHnM12coDEqiC1IRCi0U/EKwQ==} - resolution: {integrity: sha512-orajc5T2PsRYUN3ZryCEFeMDYwyw09c/pZeaQEZPH0MpKzSvn3e0uXsDBu3k03VI+9DBiRo+l22BfKTpKwa/Wg==} resolution: {integrity: sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==} @@ -2387,12 +2373,6 @@ packages: peerDependencies: - '@babel/[email protected]': - resolution: {integrity: sha512-wNqc87qjLvsD1PIMQBzLn1bMuTlGzqLzM/1VGQ22Wm51cbCWS9k71ydp5iZS4hjwQNuTWSn/xbZkkusNENwtZg==} '@babel/[email protected]': resolution: {integrity: sha512-cKp3dlQsFsEs5CWKnN7BnSHOd0EOW8EKpEjkoz1pO2E5KzIDNV9Ros1b0CnmbVgAGXJubOYVBOGCT1OmJwOI7w==} deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead. @@ -4967,9 +4947,6 @@ packages: '@napi-rs/[email protected]': resolution: {integrity: sha512-HAPjR3bnCsdXBsATpDIP5WCrw0JcACwhhrwIAQhiR46n+jm+a2F8kBsfseAuWtSyQ+H3Yebt2k43B5dy+04yMA==} - resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==} resolution: {integrity: sha512-54/JRvkLIzzDWshCWfuhadfrfZVPiElY8Fcgmg1HroEly/EDSszzhBAsarCux+D/kOslTRquNzuyGSmUSTTHGg==} @@ -7948,10 +7925,6 @@ packages: [email protected]: resolution: {integrity: sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow==} - [email protected]: - resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} - engines: {node: '>= 6'} [email protected]: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} @@ -9999,9 +9972,6 @@ packages: [email protected]: resolution: {integrity: sha512-b1FMfwetIKymC0eioW7mTywihSQE4oLzQn1dB6rZB5fx/3NpNEdAWeCSMB+60/AeT0TCXsxzAlcYVEFCTAksWg==} - [email protected]: - resolution: {integrity: sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==} [email protected]: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} @@ -10200,10 +10170,6 @@ packages: resolution: {integrity: sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==} - resolution: {integrity: sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==} - deprecated: Glob versions prior to v9 are no longer supported resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} @@ -15399,9 +15365,6 @@ packages: resolution: {integrity: sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==} - [email protected]: - resolution: {integrity: sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==} resolution: {integrity: sha512-1j0w61+eVxu7DawFJtnfYcvSv6qPFvfTaqzTQ2BLknVhHTwGS8sc63ZBF4rzkWMBVKybo4S5OBtDdZahh2A1xg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} @@ -15473,10 +15436,6 @@ packages: resolution: {integrity: sha512-3TYDR7xWt4dIqV2JauJr+EJeW356RXijHeUlO+8djJ+uBXPn8/2dpzBc8yQhh583sVvc9CvFAeQVgijsH+PNNg==} engines: {node: '>=0.10.0'} - [email protected]: - resolution: {integrity: sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==} - engines: {node: '>=6'} [email protected]: resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} @@ -15906,17 +15865,6 @@ packages: [email protected]: resolution: {integrity: sha512-HFpbb5gr2ypci7Qw+IOhnP2zOU7e77b+rzM+wTzXzfi1PrtBCX0E7Pk4wL4iTLnhzZ+JgEGAhX81ebTg/aYjQw==} - resolution: {integrity: sha512-5FbCTxynopck99GRwM5Ey0+VRp8pkQq69TwGOJJeYtR7gPvwGjNx8yBPLN7/dfxwwvn9ymOZYB19eQkv2k70wQ==} - engines: {node: '>= 16'} - babel-plugin-styled-components: '>= 2' - react-dom: 19.2.0-canary-3fbfb9ba-20250409 - peerDependenciesMeta: - babel-plugin-styled-components: - optional: true resolution: {integrity: sha512-6xuteERUhLSLbztb2l2zhrxJpcW3eb7ooSMc3j5D51jiao6HZNaJoimmSnpUMji1qWxbAZD0Lee0ftB4atxoRA==} @@ -16369,9 +16317,6 @@ packages: [email protected]: resolution: {integrity: sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==} - [email protected]: - resolution: {integrity: sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==} [email protected]: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} @@ -17585,20 +17530,6 @@ snapshots: '@ast-grep/cli-win32-ia32-msvc': 0.31.0 '@ast-grep/cli-win32-x64-msvc': 0.31.0 - '@babel/[email protected](@babel/[email protected])': - '@jridgewell/trace-mapping': 0.3.22 - commander: 4.1.1 - convert-source-map: 1.9.0 - fs-readdir-recursive: 1.1.0 - glob: 7.2.0 - make-dir: 2.1.0 - slash: 2.0.0 - optionalDependencies: - '@nicolo-ribaudo/chokidar-2': 2.1.8-no-fsevents.3 - chokidar: 3.6.0 '@babel/highlight': 7.22.20 @@ -17894,10 +17825,6 @@ snapshots: - '@babel/types': 7.22.5 '@babel/types': 7.22.5 @@ -18203,11 +18130,6 @@ snapshots: - '@babel/helper-plugin-utils': 7.25.7 '@babel/[email protected](@babel/[email protected])': @@ -21391,9 +21313,6 @@ snapshots: '@napi-rs/[email protected]': {} - optional: true eslint-scope: 5.1.1 @@ -24932,8 +24851,6 @@ snapshots: [email protected]: {} - [email protected]: {} [email protected]: {} [email protected]: {} @@ -27788,8 +27705,6 @@ snapshots: [email protected]: {} - [email protected]: {} [email protected]: {} [email protected]: @@ -28028,15 +27943,6 @@ snapshots: once: 1.4.0 path-is-absolute: 1.0.1 - inherits: 2.0.4 - minimatch: 3.0.4 - once: 1.4.0 - path-is-absolute: 1.0.1 fs.realpath: 1.0.0 @@ -34630,8 +34536,6 @@ snapshots: kind-of: 6.0.3 - [email protected]: {} color: 4.2.3 @@ -34720,8 +34624,6 @@ snapshots: [email protected]: {} - [email protected]: {} [email protected]: {} [email protected]: {} @@ -35211,29 +35113,6 @@ snapshots: inline-style-parser: 0.1.1 - [email protected]([email protected]([email protected]))([email protected]): - '@babel/cli': 7.21.5(@babel/[email protected]) - '@babel/helper-module-imports': 7.21.4 - '@babel/plugin-external-helpers': 7.18.6(@babel/[email protected]) - '@babel/plugin-proposal-class-properties': 7.18.6(@babel/[email protected]) - '@babel/plugin-proposal-object-rest-spread': 7.20.7(@babel/[email protected]) - '@babel/preset-react': 7.22.5(@babel/[email protected]) - '@babel/preset-typescript': 7.22.5(@babel/[email protected]) - '@babel/traverse': 7.22.5 - '@emotion/unitless': 0.8.1 - css-to-react-native: 3.2.0 - postcss: 8.4.31 - react-dom: 19.2.0-canary-3fbfb9ba-20250409([email protected]) - shallowequal: 1.1.0 - stylis: 4.2.0 - tslib: 2.5.3 - transitivePeerDependencies: - - supports-color postcss: 7.0.32 @@ -35744,8 +35623,6 @@ snapshots: [email protected]: {} [email protected]: {} [email protected]([email protected]): diff --git a/test/development/basic/styled-components-disabled.test.ts b/test/development/basic/styled-components-disabled.test.ts index 48fb6d5b6beb5..5ca0e31b0fde5 100644 --- a/test/development/basic/styled-components-disabled.test.ts +++ b/test/development/basic/styled-components-disabled.test.ts @@ -5,7 +5,7 @@ import { NextInstance } from 'e2e-utils' import { retry } from 'next-test-utils' // TODO: Somehow the warning doesn't show up with Turbopack, even though the transform is not enabled. +// TODO: It no longer shows up with Webpack either in tests. ;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe.skip)( 'styled-components SWC transform', () => { diff --git a/test/development/basic/styled-components-disabled/.gitignore b/test/development/basic/styled-components-disabled/.gitignore +++ b/test/development/basic/styled-components-disabled/.gitignore diff --git a/test/development/basic/styled-components-disabled/package.json b/test/development/basic/styled-components-disabled/package.json index 0000000000000..52282b15f003f +++ b/test/development/basic/styled-components-disabled/package.json + "name": "styled-components-disabled", diff --git a/test/development/basic/styled-components-disabled/pages/index.js b/test/development/basic/styled-components-disabled/pages/index.js index 31bd1226e7689..55f57ff35a699 100644 --- a/test/development/basic/styled-components-disabled/pages/index.js +++ b/test/development/basic/styled-components-disabled/pages/index.js @@ -27,7 +27,7 @@ export default function Home() { diff --git a/test/development/basic/styled-components/.gitignore b/test/development/basic/styled-components/.gitignore +++ b/test/development/basic/styled-components/.gitignore diff --git a/test/development/basic/styled-components/package.json b/test/development/basic/styled-components/package.json index 0000000000000..262a402dfe0ec +++ b/test/development/basic/styled-components/package.json + "name": "styled-components", diff --git a/test/development/basic/styled-components/pages/index.js b/test/development/basic/styled-components/pages/index.js index a40708a545465..6fbdc8380e8e2 100644 --- a/test/development/basic/styled-components/pages/index.js +++ b/test/development/basic/styled-components/pages/index.js @@ -33,7 +33,7 @@ export default function Home() {
[ "- resolution: {integrity: sha512-TOKytQ9uQW9c4np8F+P7ZfPINy5Kv+pizDIUwSVH8X5zHgYHV4AA8HE5LA450xXeu4jEfmUckTYvv1I4S26M/g==}", "- [email protected]:", "- '@babel/[email protected](@babel/[email protected])':", "- fs.realpath: 1.0.0", "- inflight: 1.0.6", "- '@babel/preset-env': 7.22.5(@babel/[email protected])", "- [email protected]: {}", "-// TODO: It no longer shows up with Webpack either in tests. Manual repro does work though." ]
[ 31, 131, 191, 233, 234, 273, 295, 308 ]
{ "additions": 21, "author": "eps1lon", "deletions": 129, "html_url": "https://github.com/vercel/next.js/pull/77782", "issue_id": 77782, "merged_at": "2025-04-10T12:52:48Z", "omission_probability": 0.1, "pr_number": 77782, "repo": "vercel/next.js", "title": "[test] Remove global styled-components install ", "total_changes": 150 }
310
diff --git a/crates/next-core/src/next_config.rs b/crates/next-core/src/next_config.rs index 3d5665d6943cc..1ceb4e98498e9 100644 --- a/crates/next-core/src/next_config.rs +++ b/crates/next-core/src/next_config.rs @@ -725,7 +725,6 @@ pub struct ExperimentalConfig { /// directory. ppr: Option<ExperimentalPartialPrerendering>, taint: Option<bool>, - react_owner_stack: Option<bool>, #[serde(rename = "routerBFCache")] router_bfcache: Option<bool>, proxy_timeout: Option<f64>, @@ -1417,11 +1416,6 @@ impl NextConfig { Vc::cell(self.experimental.taint.unwrap_or(false)) } - #[turbo_tasks::function] - pub fn enable_react_owner_stack(&self) -> Vc<bool> { - Vc::cell(self.experimental.react_owner_stack.unwrap_or(false)) - } - #[turbo_tasks::function] pub fn enable_router_bfcache(&self) -> Vc<bool> { Vc::cell(self.experimental.router_bfcache.unwrap_or(false)) diff --git a/crates/next-core/src/next_import_map.rs b/crates/next-core/src/next_import_map.rs index 235e03b2ac7a9..b1dd5fef5211d 100644 --- a/crates/next-core/src/next_import_map.rs +++ b/crates/next-core/src/next_import_map.rs @@ -120,7 +120,6 @@ pub async fn get_next_client_import_map( ClientContextType::App { app_dir } => { let react_flavor = if *next_config.enable_ppr().await? || *next_config.enable_taint().await? - || *next_config.enable_react_owner_stack().await? || *next_config.enable_view_transition().await? || *next_config.enable_router_bfcache().await? { @@ -700,10 +699,9 @@ async fn rsc_aliases( ) -> Result<()> { let ppr = *next_config.enable_ppr().await?; let taint = *next_config.enable_taint().await?; - let react_owner_stack = *next_config.enable_react_owner_stack().await?; let router_bfcache = *next_config.enable_router_bfcache().await?; let view_transition = *next_config.enable_view_transition().await?; - let react_channel = if ppr || taint || react_owner_stack || view_transition || router_bfcache { + let react_channel = if ppr || taint || view_transition || router_bfcache { "-experimental" } else { ""
diff --git a/crates/next-core/src/next_config.rs b/crates/next-core/src/next_config.rs index 3d5665d6943cc..1ceb4e98498e9 100644 --- a/crates/next-core/src/next_config.rs +++ b/crates/next-core/src/next_config.rs @@ -725,7 +725,6 @@ pub struct ExperimentalConfig { /// directory. ppr: Option<ExperimentalPartialPrerendering>, taint: Option<bool>, - react_owner_stack: Option<bool>, #[serde(rename = "routerBFCache")] router_bfcache: Option<bool>, proxy_timeout: Option<f64>, @@ -1417,11 +1416,6 @@ impl NextConfig { Vc::cell(self.experimental.taint.unwrap_or(false)) } - #[turbo_tasks::function] - pub fn enable_react_owner_stack(&self) -> Vc<bool> { - Vc::cell(self.experimental.react_owner_stack.unwrap_or(false)) - } - #[turbo_tasks::function] pub fn enable_router_bfcache(&self) -> Vc<bool> { Vc::cell(self.experimental.router_bfcache.unwrap_or(false)) diff --git a/crates/next-core/src/next_import_map.rs b/crates/next-core/src/next_import_map.rs index 235e03b2ac7a9..b1dd5fef5211d 100644 --- a/crates/next-core/src/next_import_map.rs +++ b/crates/next-core/src/next_import_map.rs @@ -120,7 +120,6 @@ pub async fn get_next_client_import_map( ClientContextType::App { app_dir } => { let react_flavor = if *next_config.enable_ppr().await? || *next_config.enable_taint().await? - || *next_config.enable_react_owner_stack().await? || *next_config.enable_view_transition().await? || *next_config.enable_router_bfcache().await? { @@ -700,10 +699,9 @@ async fn rsc_aliases( ) -> Result<()> { let ppr = *next_config.enable_ppr().await?; let taint = *next_config.enable_taint().await?; - let react_owner_stack = *next_config.enable_react_owner_stack().await?; let router_bfcache = *next_config.enable_router_bfcache().await?; let view_transition = *next_config.enable_view_transition().await?; + let react_channel = if ppr || taint || view_transition || router_bfcache { "-experimental" } else { ""
[ "- let react_channel = if ppr || taint || react_owner_stack || view_transition || router_bfcache {" ]
[ 43 ]
{ "additions": 1, "author": "eps1lon", "deletions": 9, "html_url": "https://github.com/vercel/next.js/pull/78021", "issue_id": 78021, "merged_at": "2025-04-10T12:56:16Z", "omission_probability": 0.1, "pr_number": 78021, "repo": "vercel/next.js", "title": "Cleanup `config.experimental.reactOwnerstack`", "total_changes": 10 }
311
diff --git a/docs/01-app/05-api-reference/01-directives/use-cache.mdx b/docs/01-app/05-api-reference/01-directives/use-cache.mdx index 49dd39c9675aa..25cf971562f78 100644 --- a/docs/01-app/05-api-reference/01-directives/use-cache.mdx +++ b/docs/01-app/05-api-reference/01-directives/use-cache.mdx @@ -14,11 +14,11 @@ related: - app/api-reference/functions/revalidateTag --- -The `use cache` directive designates a component and/or a function to be cached. It can be used at the top of a file to indicate that all exports in the file are cacheable, or inline at the top of a function or component to inform Next.js the return value should be cached and reused for subsequent requests. This is an experimental Next.js feature, and not a native React feature like [`use client`](/docs/app/api-reference/directives/use-client) or [`use server`](/docs/app/api-reference/directives/use-server). +The `use cache` directive allows you to mark a route, React component, or a function as cacheable. It can be used at the top of a file to indicate that all exports in the file should be cached, or inline at the top of function or component to cache the return value. ## Usage -Enable support for the `use cache` directive with the [`useCache`](/docs/app/api-reference/config/next-config-js/useCache) flag in your `next.config.ts` file: +`use cache` is currently an experimental feature. To enable it, add the [`useCache`](/docs/app/api-reference/config/next-config-js/useCache) option to your `next.config.ts` file: ```ts filename="next.config.ts" switcher import type { NextConfig } from 'next' @@ -43,9 +43,9 @@ const nextConfig = { module.exports = nextConfig ``` -Additionally, `use cache` directives are also enabled when the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) flag is set. +> **Good to know:** `use cache` can also be enabled with the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) option. -Then, you can use the `use cache` directive at the file, component, or function level: +Then, add `use cache` at the file, component, or function level: ```tsx // File level @@ -69,20 +69,68 @@ export async function getData() { } ``` -## Good to know +## How `use cache` works -- `use cache` is an experimental Next.js feature, and not a native React feature like [`use client`](/docs/app/api-reference/directives/use-client) or [`use server`](/docs/app/api-reference/directives/use-server). -- Any [serializable](https://react.dev/reference/rsc/use-server#serializable-parameters-and-return-values) arguments (or props) passed to the cached function, as well as any serializable values it reads from the parent scope, will be converted to a format like JSON and automatically become a part of the cache key. -- Any non-serializable arguments, props, or closed-over values will turn into opaque references inside the cached function, and can be only passed through and not inspected nor modified. These non-serializable values will be filled in at the request time and won't become a part of the cache key. - - For example, a cached function can take in JSX as a `children` prop and return `<div>{children}</div>`, but it won't be able to introspect the actual `children` object. -- The return value of the cacheable function must also be serializable. This ensures that the cached data can be stored and retrieved correctly. -- Functions that use the `use cache` directive must not have any side-effects, such as modifying state, directly manipulating the DOM, or setting timers to execute code at intervals. -- If used alongside [Partial Prerendering](/docs/app/building-your-application/rendering/partial-prerendering), segments that have `use cache` will be prerendered as part of the static HTML shell. -- Unlike [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) which only supports JSON data, `use cache` can cache any serializable data React can render, including the render output of components. +### Cache keys + +A cache entry's key is generated using a serialized version of its inputs, which includes: + +- Build ID (generated for each build) +- Function ID (a secure identifier unique to the function) +- The [serializable](https://react.dev/reference/rsc/use-server#serializable-parameters-and-return-values) function arguments (or props). + +The arguments passed to the cached function, as well as any values it reads from the parent scope automatically become a part of the key. This means, the same cache entry will be reused as long as its inputs are the same. + +## Non-serializable arguments + +Any non-serializable arguments, props, or closed-over values will turn into references inside the cached function, and can be only passed through and not inspected nor modified. These non-serializable values will be filled in at the request time and won't become a part of the cache key. + +For example, a cached function can take in JSX as a `children` prop and return `<div>{children}</div>`, but it won't be able to introspect the actual `children` object. This allows you to nest uncached content inside a cached component. + +```tsx filename="app/ui/cached-component.tsx" switcher +function CachedComponent({ children }: { children: ReactNode }) { + 'use cache' + return <div>{children}</div> +} +``` + +```jsx filename="app/ui/cached-component.js" switcher +function CachedComponent({ children }) { + 'use cache' + return <div>{children}</div> +} +``` + +## Return values + +The return value of the cacheable function must be serializable. This ensures that the cached data can be stored and retrieved correctly. + +## `use cache` at build time + +When used at the top of a [layout](/docs/app/api-reference/file-conventions/layout) or [page](/docs/app/api-reference/file-conventions/page), the route segment will be prerendered, allowing it to later be [revalidated](#during-revalidation). + +This means `use cache` cannot be used with [request-time APIs](/docs/app/building-your-application/rendering/server-components#dynamic-apis) like `cookies` or `headers`. + +## `use cache` at runtime + +On the **server**, the cache entries of individual components or functions will be cached in-memory. + +Then, on the **client**, any content returned from the server cache will be stored in the browser's memory for the duration of the session or until [revalidated](#during-revalidation). + +## During revalidation + +By default, `use cache` has server-side revalidation period of **15 minutes**. While this period may be useful for content that doesn't require frequent updates, you can use the `cacheLife` and `cacheTag` APIs to configure when the individual cache entries should be revalidated. + +- [`cacheLife`](/docs/app/api-reference/functions/cacheLife): Configure the cache entry lifetime. +- [`cacheTag`](/docs/app/api-reference/functions/cacheTag): Create tags for on-demand revalidation. + +Both of these APIs integrate across the client and server caching layers, meaning you can configure your caching semantics in one place and have them apply everywhere. + +See the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) and [`cacheTag`](/docs/app/api-reference/functions/cacheTag) API docs for more information. ## Examples -### Caching entire routes with `use cache` +### Caching an entire route with `use cache` To prerender an entire route, add `use cache` to the top of **both** the `layout` and `page` files. Each of these segments are treated as separate entry points in your application, and will be cached independently. @@ -138,13 +186,14 @@ export default function Page() { } ``` -> This is recommended for applications that previously used the [`export const dynamic = "force-static"`](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) option, and will ensure the entire route is prerendered. - -### Caching component output with `use cache` +> **Good to know**: +> +> - If `use cache` is added only to the `layout` or the `page`, only that route segment and any components imported into it will be cached. +> - If any of the nested children in the route use [Dynamic APIs](/docs/app/building-your-application/rendering/server-components#dynamic-apis), then the route will opt out of prerendering. -You can use `use cache` at the component level to cache any fetches or computations performed within that component. When you reuse the component throughout your application it can share the same cache entry as long as the props maintain the same structure. +### Caching a component's output with `use cache` -The props are serialized and form part of the cache key, and the cache entry will be reused as long as the serialized props produce the same value in each instance. +You can use `use cache` at the component level to cache any fetches or computations performed within that component. The cache entry will be reused as long as the serialized props produce the same value in each instance. ```tsx filename="app/components/bookings.tsx" highlight={2} switcher export async function Bookings({ type = 'haircut' }: BookingsProps) { @@ -174,7 +223,7 @@ export async function Bookings({ type = 'haircut' }) { ### Caching function output with `use cache` -Since you can add `use cache` to any asynchronous function, you aren't limited to caching components or routes only. You might want to cache a network request or database query or compute something that is very slow. By adding `use cache` to a function containing this type of work it becomes cacheable, and when reused, will share the same cache entry. +Since you can add `use cache` to any asynchronous function, you aren't limited to caching components or routes only. You might want to cache a network request, a database query, or a slow computation. ```tsx filename="app/actions.ts" highlight={2} switcher export async function getData() { @@ -194,25 +243,6 @@ export async function getData() { } ``` -### Revalidating - -By default, Next.js sets a **[revalidation period](/docs/app/building-your-application/data-fetching/fetching#revalidating-cached-data) of 15 minutes** when you use the `use cache` directive. Next.js sets a near-infinite expiration duration, meaning it's suitable for content that doesn't need frequent updates. - -While this revalidation period may be useful for content you don't expect to change often, you can use the `cacheLife` and `cacheTag` APIs to configure the cache behavior: - -- [`cacheLife`](/docs/app/api-reference/functions/cacheLife): For time-based revalidation periods. -- [`cacheTag`](/docs/app/api-reference/functions/cacheTag): For tagging cached data. - -Both of these APIs integrate across the client and server caching layers, meaning you can configure your caching semantics in one place and have them apply everywhere. - -See the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) and [`cacheTag`](/docs/app/api-reference/functions/cacheTag) docs for more information. - -### Invalidating - -To invalidate the cached data, you can use the [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) function. - -See the [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) docs for more information. - ### Interleaving If you need to pass non-serializable arguments to a cacheable function, you can pass them as `children`. This means the `children` reference can change without affecting the cache entry. diff --git a/docs/01-app/05-api-reference/04-functions/cacheLife.mdx b/docs/01-app/05-api-reference/04-functions/cacheLife.mdx index 5e3cb133ffe0b..ea54643015766 100644 --- a/docs/01-app/05-api-reference/04-functions/cacheLife.mdx +++ b/docs/01-app/05-api-reference/04-functions/cacheLife.mdx @@ -66,22 +66,24 @@ export default async function Page() { ### Default cache profiles -Next.js provides a set of named cache profiles modeled on various timescales. If you don't specify a cache profile in the `cacheLife` function alongside the `use cache` directive, Next.js will automatically apply the “default” cache profile. +Next.js provides a set of named cache profiles modeled on various timescales. If you don't specify a cache profile in the `cacheLife` function alongside the `use cache` directive, Next.js will automatically apply the `default` cache profile. However, we recommend always adding a cache profile when using the `use cache` directive to explicitly define caching behavior. -| **Profile** | **Stale** | **Revalidate** | **Expire** | **Description** | -| ----------- | --------- | -------------- | -------------- | ------------------------------------------------------------------------ | -| `default` | undefined | 15 minutes | INFINITE_CACHE | Default profile, suitable for content that doesn't need frequent updates | -| `seconds` | undefined | 1 second | 1 minute | For rapidly changing content requiring near real-time updates | -| `minutes` | 5 minutes | 1 minute | 1 hour | For content that updates frequently within an hour | -| `hours` | 5 minutes | 1 hour | 1 day | For content that updates daily but can be slightly stale | -| `days` | 5 minutes | 1 day | 1 week | For content that updates weekly but can be a day old | -| `weeks` | 5 minutes | 1 week | 1 month | For content that updates monthly but can be a week old | -| `max` | 5 minutes | 1 month | INFINITE_CACHE | For very stable content that rarely needs updating | +| **Profile** | `stale` | `revalidate` | `expire` | **Description** | +| ----------- | --------- | ------------ | -------- | ------------------------------------------------------------------------ | +| `default` | 5 minutes | 15 minutes | 1 year | Default profile, suitable for content that doesn't need frequent updates | +| `seconds` | 0 | 1 second | 1 second | For rapidly changing content requiring near real-time updates | +| `minutes` | 5 minutes | 1 minute | 1 hour | For content that updates frequently within an hour | +| `hours` | 5 minutes | 1 hour | 1 day | For content that updates daily but can be slightly stale | +| `days` | 5 minutes | 1 day | 1 week | For content that updates weekly but can be a day old | +| `weeks` | 5 minutes | 1 week | 30 days | For content that updates monthly but can be a week old | +| `max` | 5 minutes | 30 days | 1 year | For very stable content that rarely needs updating | The string values used to reference cache profiles don't carry inherent meaning; instead they serve as semantic labels. This allows you to better understand and manage your cached content within your codebase. +> **Good to know:** Updating the [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes) and [`expireTime`](/docs/app/api-reference/config/next-config-js/expireTime) config options also updates the `stale` and `expire` properties of the `default` cache profile. + ### Custom cache profiles You can configure custom cache profiles by adding them to the [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife) option in your `next.config.ts` file.
diff --git a/docs/01-app/05-api-reference/01-directives/use-cache.mdx b/docs/01-app/05-api-reference/01-directives/use-cache.mdx index 49dd39c9675aa..25cf971562f78 100644 --- a/docs/01-app/05-api-reference/01-directives/use-cache.mdx +++ b/docs/01-app/05-api-reference/01-directives/use-cache.mdx @@ -14,11 +14,11 @@ related: - app/api-reference/functions/revalidateTag --- -The `use cache` directive designates a component and/or a function to be cached. It can be used at the top of a file to indicate that all exports in the file are cacheable, or inline at the top of a function or component to inform Next.js the return value should be cached and reused for subsequent requests. This is an experimental Next.js feature, and not a native React feature like [`use client`](/docs/app/api-reference/directives/use-client) or [`use server`](/docs/app/api-reference/directives/use-server). +The `use cache` directive allows you to mark a route, React component, or a function as cacheable. It can be used at the top of a file to indicate that all exports in the file should be cached, or inline at the top of function or component to cache the return value. ## Usage -Enable support for the `use cache` directive with the [`useCache`](/docs/app/api-reference/config/next-config-js/useCache) flag in your `next.config.ts` file: +`use cache` is currently an experimental feature. To enable it, add the [`useCache`](/docs/app/api-reference/config/next-config-js/useCache) option to your `next.config.ts` file: ```ts filename="next.config.ts" switcher import type { NextConfig } from 'next' @@ -43,9 +43,9 @@ const nextConfig = { module.exports = nextConfig -Additionally, `use cache` directives are also enabled when the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) flag is set. +> **Good to know:** `use cache` can also be enabled with the [`dynamicIO`](/docs/app/api-reference/config/next-config-js/dynamicIO) option. -Then, you can use the `use cache` directive at the file, component, or function level: +Then, add `use cache` at the file, component, or function level: ```tsx // File level @@ -69,20 +69,68 @@ export async function getData() { -## Good to know +## How `use cache` works -- `use cache` is an experimental Next.js feature, and not a native React feature like [`use client`](/docs/app/api-reference/directives/use-client) or [`use server`](/docs/app/api-reference/directives/use-server). -- Any [serializable](https://react.dev/reference/rsc/use-server#serializable-parameters-and-return-values) arguments (or props) passed to the cached function, as well as any serializable values it reads from the parent scope, will be converted to a format like JSON and automatically become a part of the cache key. - - For example, a cached function can take in JSX as a `children` prop and return `<div>{children}</div>`, but it won't be able to introspect the actual `children` object. -- The return value of the cacheable function must also be serializable. This ensures that the cached data can be stored and retrieved correctly. -- Functions that use the `use cache` directive must not have any side-effects, such as modifying state, directly manipulating the DOM, or setting timers to execute code at intervals. -- If used alongside [Partial Prerendering](/docs/app/building-your-application/rendering/partial-prerendering), segments that have `use cache` will be prerendered as part of the static HTML shell. -- Unlike [`unstable_cache`](/docs/app/api-reference/functions/unstable_cache) which only supports JSON data, `use cache` can cache any serializable data React can render, including the render output of components. +### Cache keys +A cache entry's key is generated using a serialized version of its inputs, which includes: +- Build ID (generated for each build) +- Function ID (a secure identifier unique to the function) +- The [serializable](https://react.dev/reference/rsc/use-server#serializable-parameters-and-return-values) function arguments (or props). +The arguments passed to the cached function, as well as any values it reads from the parent scope automatically become a part of the key. This means, the same cache entry will be reused as long as its inputs are the same. +## Non-serializable arguments +Any non-serializable arguments, props, or closed-over values will turn into references inside the cached function, and can be only passed through and not inspected nor modified. These non-serializable values will be filled in at the request time and won't become a part of the cache key. +For example, a cached function can take in JSX as a `children` prop and return `<div>{children}</div>`, but it won't be able to introspect the actual `children` object. This allows you to nest uncached content inside a cached component. +```tsx filename="app/ui/cached-component.tsx" switcher +function CachedComponent({ children }: { children: ReactNode }) { +```jsx filename="app/ui/cached-component.js" switcher +function CachedComponent({ children }) { +## Return values +The return value of the cacheable function must be serializable. This ensures that the cached data can be stored and retrieved correctly. +## `use cache` at build time +When used at the top of a [layout](/docs/app/api-reference/file-conventions/layout) or [page](/docs/app/api-reference/file-conventions/page), the route segment will be prerendered, allowing it to later be [revalidated](#during-revalidation). +This means `use cache` cannot be used with [request-time APIs](/docs/app/building-your-application/rendering/server-components#dynamic-apis) like `cookies` or `headers`. +## `use cache` at runtime +On the **server**, the cache entries of individual components or functions will be cached in-memory. +## During revalidation +By default, `use cache` has server-side revalidation period of **15 minutes**. While this period may be useful for content that doesn't require frequent updates, you can use the `cacheLife` and `cacheTag` APIs to configure when the individual cache entries should be revalidated. +- [`cacheTag`](/docs/app/api-reference/functions/cacheTag): Create tags for on-demand revalidation. +Both of these APIs integrate across the client and server caching layers, meaning you can configure your caching semantics in one place and have them apply everywhere. ## Examples -### Caching entire routes with `use cache` +### Caching an entire route with `use cache` To prerender an entire route, add `use cache` to the top of **both** the `layout` and `page` files. Each of these segments are treated as separate entry points in your application, and will be cached independently. @@ -138,13 +186,14 @@ export default function Page() { +> **Good to know**: +> +> - If `use cache` is added only to the `layout` or the `page`, only that route segment and any components imported into it will be cached. +> - If any of the nested children in the route use [Dynamic APIs](/docs/app/building-your-application/rendering/server-components#dynamic-apis), then the route will opt out of prerendering. +### Caching a component's output with `use cache` ```tsx filename="app/components/bookings.tsx" highlight={2} switcher export async function Bookings({ type = 'haircut' }: BookingsProps) { @@ -174,7 +223,7 @@ export async function Bookings({ type = 'haircut' }) { ### Caching function output with `use cache` +Since you can add `use cache` to any asynchronous function, you aren't limited to caching components or routes only. You might want to cache a network request, a database query, or a slow computation. ```tsx filename="app/actions.ts" highlight={2} switcher export async function getData() { @@ -194,25 +243,6 @@ export async function getData() { -### Revalidating -By default, Next.js sets a **[revalidation period](/docs/app/building-your-application/data-fetching/fetching#revalidating-cached-data) of 15 minutes** when you use the `use cache` directive. Next.js sets a near-infinite expiration duration, meaning it's suitable for content that doesn't need frequent updates. -While this revalidation period may be useful for content you don't expect to change often, you can use the `cacheLife` and `cacheTag` APIs to configure the cache behavior: -- [`cacheTag`](/docs/app/api-reference/functions/cacheTag): For tagging cached data. -See the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) and [`cacheTag`](/docs/app/api-reference/functions/cacheTag) docs for more information. -### Invalidating -To invalidate the cached data, you can use the [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) function. -See the [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) docs for more information. ### Interleaving If you need to pass non-serializable arguments to a cacheable function, you can pass them as `children`. This means the `children` reference can change without affecting the cache entry. diff --git a/docs/01-app/05-api-reference/04-functions/cacheLife.mdx b/docs/01-app/05-api-reference/04-functions/cacheLife.mdx index 5e3cb133ffe0b..ea54643015766 100644 --- a/docs/01-app/05-api-reference/04-functions/cacheLife.mdx +++ b/docs/01-app/05-api-reference/04-functions/cacheLife.mdx @@ -66,22 +66,24 @@ export default async function Page() { ### Default cache profiles -Next.js provides a set of named cache profiles modeled on various timescales. If you don't specify a cache profile in the `cacheLife` function alongside the `use cache` directive, Next.js will automatically apply the “default” cache profile. +Next.js provides a set of named cache profiles modeled on various timescales. If you don't specify a cache profile in the `cacheLife` function alongside the `use cache` directive, Next.js will automatically apply the `default` cache profile. However, we recommend always adding a cache profile when using the `use cache` directive to explicitly define caching behavior. -| **Profile** | **Stale** | **Revalidate** | **Expire** | **Description** | -| ----------- | --------- | -------------- | -------------- | ------------------------------------------------------------------------ | -| `default` | undefined | 15 minutes | INFINITE_CACHE | Default profile, suitable for content that doesn't need frequent updates | -| `seconds` | undefined | 1 second | 1 minute | For rapidly changing content requiring near real-time updates | -| `minutes` | 5 minutes | 1 minute | 1 hour | For content that updates frequently within an hour | -| `hours` | 5 minutes | 1 hour | 1 day | For content that updates daily but can be slightly stale | -| `weeks` | 5 minutes | 1 week | 1 month | For content that updates monthly but can be a week old | -| `max` | 5 minutes | 1 month | INFINITE_CACHE | For very stable content that rarely needs updating | +| **Profile** | `stale` | `revalidate` | `expire` | **Description** | +| ----------- | --------- | ------------ | -------- | ------------------------------------------------------------------------ | +| `default` | 5 minutes | 15 minutes | 1 year | Default profile, suitable for content that doesn't need frequent updates | +| `seconds` | 0 | 1 second | 1 second | For rapidly changing content requiring near real-time updates | +| `minutes` | 5 minutes | 1 minute | 1 hour | For content that updates frequently within an hour | +| `hours` | 5 minutes | 1 hour | 1 day | For content that updates daily but can be slightly stale | +| `days` | 5 minutes | 1 day | 1 week | For content that updates weekly but can be a day old | +| `weeks` | 5 minutes | 1 week | 30 days | For content that updates monthly but can be a week old | +| `max` | 5 minutes | 30 days | 1 year | For very stable content that rarely needs updating | The string values used to reference cache profiles don't carry inherent meaning; instead they serve as semantic labels. This allows you to better understand and manage your cached content within your codebase. +> **Good to know:** Updating the [`staleTimes`](/docs/app/api-reference/config/next-config-js/staleTimes) and [`expireTime`](/docs/app/api-reference/config/next-config-js/expireTime) config options also updates the `stale` and `expire` properties of the `default` cache profile. ### Custom cache profiles You can configure custom cache profiles by adding them to the [`cacheLife`](/docs/app/api-reference/config/next-config-js/cacheLife) option in your `next.config.ts` file.
[ "-- Any non-serializable arguments, props, or closed-over values will turn into opaque references inside the cached function, and can be only passed through and not inspected nor modified. These non-serializable values will be filled in at the request time and won't become a part of the cache key.", "+Then, on the **client**, any content returned from the server cache will be stored in the browser's memory for the duration of the session or until [revalidated](#during-revalidation).", "+- [`cacheLife`](/docs/app/api-reference/functions/cacheLife): Configure the cache entry lifetime.", "+See the [`cacheLife`](/docs/app/api-reference/functions/cacheLife) and [`cacheTag`](/docs/app/api-reference/functions/cacheTag) API docs for more information.", "-> This is recommended for applications that previously used the [`export const dynamic = \"force-static\"`](/docs/app/api-reference/file-conventions/route-segment-config#dynamic) option, and will ensure the entire route is prerendered.", "-### Caching component output with `use cache`", "-You can use `use cache` at the component level to cache any fetches or computations performed within that component. When you reuse the component throughout your application it can share the same cache entry as long as the props maintain the same structure.", "-The props are serialized and form part of the cache key, and the cache entry will be reused as long as the serialized props produce the same value in each instance.", "+You can use `use cache` at the component level to cache any fetches or computations performed within that component. The cache entry will be reused as long as the serialized props produce the same value in each instance.", "-Since you can add `use cache` to any asynchronous function, you aren't limited to caching components or routes only. You might want to cache a network request or database query or compute something that is very slow. By adding `use cache` to a function containing this type of work it becomes cacheable, and when reused, will share the same cache entry.", "-- [`cacheLife`](/docs/app/api-reference/functions/cacheLife): For time-based revalidation periods.", "-Both of these APIs integrate across the client and server caching layers, meaning you can configure your caching semantics in one place and have them apply everywhere.", "-| `days` | 5 minutes | 1 day | 1 week | For content that updates weekly but can be a day old |" ]
[ 39, 89, 95, 100, 113, 115, 121, 124, 125, 133, 148, 151, 183 ]
{ "additions": 81, "author": "delbaoliveira", "deletions": 49, "html_url": "https://github.com/vercel/next.js/pull/78024", "issue_id": 78024, "merged_at": "2025-04-10T13:26:26Z", "omission_probability": 0.1, "pr_number": 78024, "repo": "vercel/next.js", "title": "Docs: Improve `\"use cache\"` and `cacheLife` API references", "total_changes": 130 }
312
diff --git a/docs/01-app/05-api-reference/04-functions/use-link-status.mdx b/docs/01-app/05-api-reference/04-functions/use-link-status.mdx index ee064dd02cfc3..11bbf42ba2c19 100644 --- a/docs/01-app/05-api-reference/04-functions/use-link-status.mdx +++ b/docs/01-app/05-api-reference/04-functions/use-link-status.mdx @@ -1,9 +1,20 @@ --- title: useLinkStatus description: API Reference for the useLinkStatus hook. +related: + title: Next Steps + description: Learn more about the features mentioned in this page by reading the API Reference. + links: + - app/api-reference/components/link + - app/api-reference/file-conventions/loading --- -`useLinkStatus` is a **Client Component** hook that lets you track the loading state of a `Link` component during navigation. It can be used to show loading indicators during page transitions, especially when [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled, or the linked route does not have any loading states. +The `useLinkStatus` hook lets you tracks the **pending** state of a `<Link>`. You can use it to show inline visual feedback to the user (like spinners or text glimmers) while a navigation to a new route completes. + +`useLinkStatus` is useful when: + +- [Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled or in progress meaning navigation is blocked. +- The destination route is dynamic **and** doesn't include a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file that would allow an instant navigation. ```tsx filename="app/loading-indicator.tsx" switcher 'use client' @@ -12,7 +23,9 @@ import { useLinkStatus } from 'next/link' export default function LoadingIndicator() { const { pending } = useLinkStatus() - return pending ? <span>⌛</span> : null + return pending ? ( + <div role="status" aria-label="Loading" className="spinner" /> + ) : null } ``` @@ -23,7 +36,9 @@ import { useLinkStatus } from 'next/link' export default function LoadingIndicator() { const { pending } = useLinkStatus() - return pending ? <span>⌛</span> : null + return pending ? ( + <div role="status" aria-label="Loading" className="spinner" /> + ) : null } ``` @@ -81,13 +96,11 @@ const { pending } = useLinkStatus() | -------- | ------- | -------------------------------------------- | | pending | boolean | `true` before history updates, `false` after | -## Examples - -### Improving the user experience when navigating with new query parameters +## Example -In this example, navigating between categories updates the query string (e.g. ?category=books). However, the page may appear unresponsive because the `<PageSkeleton />` fallback won't replace the existing content (see [preventing unwanted loading indicators](https://react.dev/reference/react/useTransition#preventing-unwanted-loading-indicators)). +### Inline loading indicator -You can use the `useLinkStatus` hook to render a lightweight loading indicator next to the active link and provide immediate feedback to the user while the data is being fetched. +It's helpful to add visual feedback that navigation is happening in case the user clicks a link before prefetching is complete. ```tsx filename="app/components/loading-indicator.tsx" switcher 'use client' @@ -96,7 +109,9 @@ import { useLinkStatus } from 'next/link' export default function LoadingIndicator() { const { pending } = useLinkStatus() - return pending ? <span>⌛</span> : null + return pending ? ( + <div role="status" aria-label="Loading" className="spinner" /> + ) : null } ``` @@ -107,105 +122,102 @@ import { useLinkStatus } from 'next/link' export default function LoadingIndicator() { const { pending } = useLinkStatus() - return pending ? <span>⌛</span> : null + return pending ? ( + <div role="status" aria-label="Loading" className="spinner" /> + ) : null } ``` -```tsx filename="app/page.tsx" switcher -import { useSearchParams } from 'next/navigation' +```tsx filename="app/shop/layout.tsx" switcher import Link from 'next/link' -import { Suspense } from 'react' -import LoadingIndicator from './loading-indicator' +import LoadingIndicator from './components/loading-indicator' + +const links = [ + { href: '/shop/electronics', label: 'Electronics' }, + { href: '/shop/clothing', label: 'Clothing' }, + { href: '/shop/books', label: 'Books' }, +] -function MenuBar() { +function Menubar() { return ( <div> - <Link href="?category=electronics"> - Electronics <LoadingIndicator /> - </Link> - <Link href="?category=clothing"> - Clothing <LoadingIndicator /> - </Link> - <Link href="?category=books"> - Books <LoadingIndicator /> - </Link> + {links.map((link) => ( + <Link key={link.label} href={link.href}> + {link.label} <LoadingIndicator /> + </Link> + ))} </div> ) } -async function ProductList({ category }: { category: string }) { - const products = await fetchProducts(category) - +export default function Layout({ children }: { children: React.ReactNode }) { return ( - <ul> - {products.map((product) => ( - <li key={product}>{product}</li> - ))} - </ul> + <div> + <Menubar /> + {children} + </div> ) } +``` + +```jsx filename="app/shop/layout.js" switcher +import Link from 'next/link' +import LoadingIndicator from './components/loading-indicator' -export default async function ProductCategories({ - searchParams, -}: { - searchParams: Promise<{ - category: string - }> -}) { - const { category } = await searchParams +const links = [ + { href: '/shop/electronics', label: 'Electronics' }, + { href: '/shop/clothing', label: 'Clothing' }, + { href: '/shop/books', label: 'Books' }, +] +function Menubar() { return ( - <Suspense fallback={<PageSkeleton />}> - <MenuBar /> - <ProductList category={category} /> - </Suspense> + <div> + {links.map((link) => ( + <Link key={link.label} href={link.href}> + {link.label} <LoadingIndicator /> + </Link> + ))} + </div> ) } -``` -```jsx filename="app/page.js" switcher -import { useSearchParams } from 'next/navigation' -import Link from 'next/link' -import { Suspense } from 'react' -import LoadingIndicator from './loading-indicator' - -function MenuBar() { +export default function Layout({ children }) { return ( <div> - <Link href="?category=electronics"> - Electronics <LoadingIndicator /> - </Link> - <Link href="?category=clothing"> - Clothing <LoadingIndicator /> - </Link> - <Link href="?category=books"> - Books <LoadingIndicator /> - </Link> + <Menubar /> + {children} </div> ) } +``` -async function ProductList({ category }) { - const products = await fetchProducts(category) +## Gracefully handling fast navigation - return ( - <ul> - {products.map((product) => ( - <li key={product}>{product}</li> - ))} - </ul> - ) +If the navigation to a new route is fast, users may see an unecessary flash of the loading indicator. One way to improve the user experience and only show the loading indicator when the navigation takes time to complete is to add an initial animation delay (e.g. 100ms) and start the animation as invisible (e.g. `opacity: 0`). + +```css filename="app/styles/global.css" +.spinner { + /* ... */ + opacity: 0; + animation: + fadeIn 500ms 100ms forwards, + rotate 1s linear infinite; } -export default async function ProductCategories({ searchParams }) { - const { category } = await searchParams +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} - return ( - <Suspense fallback={<PageSkeleton />}> - <MenuBar /> - <ProductList category={category} /> - </Suspense> - ) +@keyframes rotate { + to { + transform: rotate(360deg); + } } ```
diff --git a/docs/01-app/05-api-reference/04-functions/use-link-status.mdx b/docs/01-app/05-api-reference/04-functions/use-link-status.mdx index ee064dd02cfc3..11bbf42ba2c19 100644 --- a/docs/01-app/05-api-reference/04-functions/use-link-status.mdx +++ b/docs/01-app/05-api-reference/04-functions/use-link-status.mdx @@ -1,9 +1,20 @@ title: useLinkStatus description: API Reference for the useLinkStatus hook. +related: + title: Next Steps + description: Learn more about the features mentioned in this page by reading the API Reference. + links: + - app/api-reference/components/link + - app/api-reference/file-conventions/loading -`useLinkStatus` is a **Client Component** hook that lets you track the loading state of a `Link` component during navigation. It can be used to show loading indicators during page transitions, especially when [prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled, or the linked route does not have any loading states. +The `useLinkStatus` hook lets you tracks the **pending** state of a `<Link>`. You can use it to show inline visual feedback to the user (like spinners or text glimmers) while a navigation to a new route completes. +`useLinkStatus` is useful when: +- [Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching) is disabled or in progress meaning navigation is blocked. +- The destination route is dynamic **and** doesn't include a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file that would allow an instant navigation. ```tsx filename="app/loading-indicator.tsx" switcher @@ -12,7 +23,9 @@ import { useLinkStatus } from 'next/link' @@ -23,7 +36,9 @@ import { useLinkStatus } from 'next/link' @@ -81,13 +96,11 @@ const { pending } = useLinkStatus() | -------- | ------- | -------------------------------------------- | | pending | boolean | `true` before history updates, `false` after | -## Examples +## Example +### Inline loading indicator -You can use the `useLinkStatus` hook to render a lightweight loading indicator next to the active link and provide immediate feedback to the user while the data is being fetched. +It's helpful to add visual feedback that navigation is happening in case the user clicks a link before prefetching is complete. ```tsx filename="app/components/loading-indicator.tsx" switcher @@ -96,7 +109,9 @@ import { useLinkStatus } from 'next/link' @@ -107,105 +122,102 @@ import { useLinkStatus } from 'next/link' -```tsx filename="app/page.tsx" switcher +```tsx filename="app/shop/layout.tsx" switcher import Link from 'next/link' -async function ProductList({ category }: { category: string }) { +export default function Layout({ children }: { children: React.ReactNode }) { +```jsx filename="app/shop/layout.js" switcher +import Link from 'next/link' -export default async function ProductCategories({ - searchParams, -}: { - searchParams: Promise<{ - category: string - }> -}) { -``` -```jsx filename="app/page.js" switcher -import Link from 'next/link' +export default function Layout({ children }) { -async function ProductList({ category }) { +## Gracefully handling fast navigation +If the navigation to a new route is fast, users may see an unecessary flash of the loading indicator. One way to improve the user experience and only show the loading indicator when the navigation takes time to complete is to add an initial animation delay (e.g. 100ms) and start the animation as invisible (e.g. `opacity: 0`). +```css filename="app/styles/global.css" +.spinner { + /* ... */ + opacity: 0; + animation: + fadeIn 500ms 100ms forwards, + rotate 1s linear infinite; -export default async function ProductCategories({ searchParams }) { + from { + opacity: 0; + opacity: 1; +} + transform: rotate(360deg);
[ "-### Improving the user experience when navigating with new query parameters", "-In this example, navigating between categories updates the query string (e.g. ?category=books). However, the page may appear unresponsive because the `<PageSkeleton />` fallback won't replace the existing content (see [preventing unwanted loading indicators](https://react.dev/reference/react/useTransition#preventing-unwanted-loading-indicators)).", "+@keyframes fadeIn {", "+@keyframes rotate {" ]
[ 54, 57, 226, 241 ]
{ "additions": 90, "author": "delbaoliveira", "deletions": 78, "html_url": "https://github.com/vercel/next.js/pull/78022", "issue_id": 78022, "merged_at": "2025-04-10T13:30:20Z", "omission_probability": 0.1, "pr_number": 78022, "repo": "vercel/next.js", "title": "Docs: Update `useLinkStatus` API reference", "total_changes": 168 }
313
diff --git a/crates/next-api/src/versioned_content_map.rs b/crates/next-api/src/versioned_content_map.rs index 88ecf4752b939..ba58fbbaafb88 100644 --- a/crates/next-api/src/versioned_content_map.rs +++ b/crates/next-api/src/versioned_content_map.rs @@ -120,22 +120,11 @@ impl VersionedContentMap { client_relative_path: Vc<FileSystemPath>, client_output_path: Vc<FileSystemPath>, ) -> Result<Vc<OptionMapEntry>> { - let assets = assets_operation.connect(); - async fn get_entries( - assets: Vc<OutputAssets>, - ) -> Result<Vec<(ResolvedVc<FileSystemPath>, ResolvedVc<Box<dyn OutputAsset>>)>> { - let assets_ref = assets.await?; - let entries = assets_ref - .iter() - .map(|&asset| async move { - let path = asset.path().to_resolved().await?; - Ok((path, asset)) - }) - .try_join() - .await?; - Ok(entries) - } - let entries = get_entries(assets).await.unwrap_or_default(); + let entries = get_entries(assets_operation) + .read_strongly_consistent() + .await + // Any error should result in an empty list, which removes all assets from the map + .ok(); self.map_path_to_op.update_conditionally(|map| { let mut changed = false; @@ -143,7 +132,7 @@ impl VersionedContentMap { // get current map's keys, subtract keys that don't exist in operation let mut stale_assets = map.0.keys().copied().collect::<FxHashSet<_>>(); - for (k, _) in entries.iter() { + for (k, _) in entries.iter().flatten() { let res = map.0.entry(*k).or_default().insert(assets_operation); stale_assets.remove(k); changed = changed || res; @@ -163,12 +152,17 @@ impl VersionedContentMap { }); // Make sure all written client assets are up-to-date - let _ = emit_assets(assets, node_root, client_relative_path, client_output_path) - .resolve() - .await?; + let _ = emit_assets( + assets_operation.connect(), + node_root, + client_relative_path, + client_output_path, + ) + .resolve() + .await?; let map_entry = Vc::cell(Some(MapEntry { assets_operation, - path_to_asset: entries.into_iter().collect(), + path_to_asset: entries.iter().flatten().copied().collect(), })); Ok(map_entry) } @@ -265,6 +259,25 @@ impl VersionedContentMap { } } +type GetEntriesResultT = Vec<(ResolvedVc<FileSystemPath>, ResolvedVc<Box<dyn OutputAsset>>)>; + +#[turbo_tasks::value(transparent)] +struct GetEntriesResult(GetEntriesResultT); + +#[turbo_tasks::function(operation)] +async fn get_entries(assets: OperationVc<OutputAssets>) -> Result<Vc<GetEntriesResult>> { + let assets_ref = assets.connect().await?; + let entries = assets_ref + .iter() + .map(|&asset| async move { + let path = asset.path().to_resolved().await?; + Ok((path, asset)) + }) + .try_join() + .await?; + Ok(Vc::cell(entries)) +} + #[turbo_tasks::function(operation)] fn compute_entry_operation( map: ResolvedVc<VersionedContentMap>, diff --git a/test/development/app-dir/missing-required-html-tags/index.test.ts b/test/development/app-dir/missing-required-html-tags/index.test.ts index 0ad44ac2cc790..067e6d81a1533 100644 --- a/test/development/app-dir/missing-required-html-tags/index.test.ts +++ b/test/development/app-dir/missing-required-html-tags/index.test.ts @@ -8,7 +8,7 @@ import { } from 'next-test-utils' describe('app-dir - missing required html tags', () => { - const { next, isTurbopack } = nextTestSetup({ files: __dirname }) + const { next } = nextTestSetup({ files: __dirname }) it('should display correct error count in dev indicator', async () => { const browser = await next.browser('/') @@ -75,22 +75,7 @@ describe('app-dir - missing required html tags', () => { ) ) - if (isTurbopack) { - await assertHasRedbox(browser) - await expect(browser).toDisplayRedbox(` - { - "count": 1, - "description": "Error: Missing <html> and <body> tags in the root layout. - Read more at https://nextjs.org/docs/messages/missing-root-layout-tags", - "environmentLabel": null, - "label": "Runtime Error", - "source": null, - "stack": [], - } - `) - } else { - // TODO(NDX-768): Should show "missing tags" error - await assertNoRedbox(browser) - } + // TODO(NDX-768): Should show "missing tags" error + await assertNoRedbox(browser) }) })
diff --git a/crates/next-api/src/versioned_content_map.rs b/crates/next-api/src/versioned_content_map.rs index 88ecf4752b939..ba58fbbaafb88 100644 --- a/crates/next-api/src/versioned_content_map.rs +++ b/crates/next-api/src/versioned_content_map.rs @@ -120,22 +120,11 @@ impl VersionedContentMap { client_relative_path: Vc<FileSystemPath>, client_output_path: Vc<FileSystemPath>, ) -> Result<Vc<OptionMapEntry>> { - let assets = assets_operation.connect(); - async fn get_entries( - assets: Vc<OutputAssets>, - ) -> Result<Vec<(ResolvedVc<FileSystemPath>, ResolvedVc<Box<dyn OutputAsset>>)>> { - let assets_ref = assets.await?; - let entries = assets_ref - .iter() - .map(|&asset| async move { - let path = asset.path().to_resolved().await?; - Ok((path, asset)) - }) - .try_join() - .await?; - Ok(entries) - } - let entries = get_entries(assets).await.unwrap_or_default(); + let entries = get_entries(assets_operation) + .read_strongly_consistent() + .await + // Any error should result in an empty list, which removes all assets from the map + .ok(); self.map_path_to_op.update_conditionally(|map| { let mut changed = false; @@ -143,7 +132,7 @@ impl VersionedContentMap { // get current map's keys, subtract keys that don't exist in operation let mut stale_assets = map.0.keys().copied().collect::<FxHashSet<_>>(); - for (k, _) in entries.iter() { + for (k, _) in entries.iter().flatten() { let res = map.0.entry(*k).or_default().insert(assets_operation); stale_assets.remove(k); changed = changed || res; @@ -163,12 +152,17 @@ impl VersionedContentMap { }); // Make sure all written client assets are up-to-date - let _ = emit_assets(assets, node_root, client_relative_path, client_output_path) - .resolve() - .await?; + let _ = emit_assets( + assets_operation.connect(), + node_root, + client_relative_path, + client_output_path, + ) + .resolve() let map_entry = Vc::cell(Some(MapEntry { assets_operation, - path_to_asset: entries.into_iter().collect(), + path_to_asset: entries.iter().flatten().copied().collect(), })); Ok(map_entry) @@ -265,6 +259,25 @@ impl VersionedContentMap { } +type GetEntriesResultT = Vec<(ResolvedVc<FileSystemPath>, ResolvedVc<Box<dyn OutputAsset>>)>; +#[turbo_tasks::value(transparent)] +struct GetEntriesResult(GetEntriesResultT); +async fn get_entries(assets: OperationVc<OutputAssets>) -> Result<Vc<GetEntriesResult>> { + let assets_ref = assets.connect().await?; + let entries = assets_ref + .iter() + .map(|&asset| async move { + let path = asset.path().to_resolved().await?; + Ok((path, asset)) + }) + .try_join() + Ok(Vc::cell(entries)) +} #[turbo_tasks::function(operation)] fn compute_entry_operation( map: ResolvedVc<VersionedContentMap>, diff --git a/test/development/app-dir/missing-required-html-tags/index.test.ts b/test/development/app-dir/missing-required-html-tags/index.test.ts index 0ad44ac2cc790..067e6d81a1533 100644 --- a/test/development/app-dir/missing-required-html-tags/index.test.ts +++ b/test/development/app-dir/missing-required-html-tags/index.test.ts @@ -8,7 +8,7 @@ import { } from 'next-test-utils' describe('app-dir - missing required html tags', () => { - const { next, isTurbopack } = nextTestSetup({ files: __dirname }) it('should display correct error count in dev indicator', async () => { const browser = await next.browser('/') @@ -75,22 +75,7 @@ describe('app-dir - missing required html tags', () => { ) ) - if (isTurbopack) { - await assertHasRedbox(browser) - await expect(browser).toDisplayRedbox(` - { - "count": 1, - "description": "Error: Missing <html> and <body> tags in the root layout. - Read more at https://nextjs.org/docs/messages/missing-root-layout-tags", - "environmentLabel": null, - "label": "Runtime Error", - "source": null, - "stack": [], - } - `) - // TODO(NDX-768): Should show "missing tags" error - await assertNoRedbox(browser) - } + await assertNoRedbox(browser) }) })
[ "+#[turbo_tasks::function(operation)]", "+ const { next } = nextTestSetup({ files: __dirname })", "- } else {", "+ // TODO(NDX-768): Should show \"missing tags\" error" ]
[ 72, 98, 119, 123 ]
{ "additions": 37, "author": "sokra", "deletions": 39, "html_url": "https://github.com/vercel/next.js/pull/77974", "issue_id": 77974, "merged_at": "2025-04-09T16:38:57Z", "omission_probability": 0.1, "pr_number": 77974, "repo": "vercel/next.js", "title": "Turbopack: read asset entries strongly consistent", "total_changes": 76 }
314
diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts index 598b6ce2bf122..2940d4e30feb0 100644 --- a/packages/next/src/server/base-server.ts +++ b/packages/next/src/server/base-server.ts @@ -1131,6 +1131,8 @@ export default abstract class Server< matchedPath = this.normalize(matchedPath) const normalizedUrlPath = this.stripNextDataPath(urlPathname) + matchedPath = denormalizePagePath(matchedPath) + // Perform locale detection and normalization. const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, { defaultLocale, @@ -1151,11 +1153,15 @@ export default abstract class Server< } } - // TODO: check if this is needed any more? - matchedPath = denormalizePagePath(matchedPath) - let srcPathname = matchedPath let pageIsDynamic = isDynamicRoute(srcPathname) + let paramsResult: { + params: ParsedUrlQuery | false + hasValidParams: boolean + } = { + params: false, + hasValidParams: false, + } if (!pageIsDynamic) { const match = await this.matchers.match(srcPathname, { @@ -1165,8 +1171,15 @@ export default abstract class Server< // Update the source pathname to the matched page's pathname. if (match) { srcPathname = match.definition.pathname - // The page is dynamic if the params are defined. - pageIsDynamic = typeof match.params !== 'undefined' + + // The page is dynamic if the params are defined. We know at this + // stage that the matched path is not a static page if the params + // were parsed from the matched path header. + if (typeof match.params !== 'undefined') { + pageIsDynamic = true + paramsResult.params = match.params + paramsResult.hasValidParams = true + } } } @@ -1236,10 +1249,14 @@ export default abstract class Server< if (pageIsDynamic) { let params: ParsedUrlQuery | false = {} - let paramsResult = utils.normalizeDynamicRouteParams( - queryParams, - false - ) + // If we don't already have valid params, try to parse them from + // the query params. + if (!paramsResult.hasValidParams) { + paramsResult = utils.normalizeDynamicRouteParams( + queryParams, + false + ) + } // for prerendered ISR paths we attempt parsing the route // params from the URL directly as route-matches may not diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx new file mode 100644 index 0000000000000..8ed2439d837c4 --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx @@ -0,0 +1,17 @@ +import { type Params, expectedParams } from '../../../expected' + +export default async function CatchAll({ + params, +}: { + params: Promise<Params> +}) { + const received = await params + + return <p>{JSON.stringify(received)}</p> +} + +export async function generateStaticParams(): Promise<Params[]> { + return [expectedParams] +} + +export const dynamic = 'force-dynamic' diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx new file mode 100644 index 0000000000000..33d03756335ee --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx @@ -0,0 +1,5 @@ +import Link from 'next/link' + +export default function Home() { + return <Link href="/1/2">Go to /1/2</Link> +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx new file mode 100644 index 0000000000000..888614deda3ba --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx @@ -0,0 +1,8 @@ +import { ReactNode } from 'react' +export default function Root({ children }: { children: ReactNode }) { + return ( + <html> + <body>{children}</body> + </html> + ) +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts new file mode 100644 index 0000000000000..37ae1d80cd3d1 --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts @@ -0,0 +1,9 @@ +export type Params = { + locale: string + rest: string[] +} + +export const expectedParams: Params = { + locale: 'en', + rest: ['1', '2'], +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts new file mode 100644 index 0000000000000..d6cac831af0fb --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts @@ -0,0 +1,21 @@ +import type { NextRequest } from 'next/server' +import { NextResponse } from 'next/server' + +export function middleware(request: NextRequest) { + return NextResponse.rewrite( + new URL('/en' + request.nextUrl.pathname, request.url) + ) +} + +export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - api (API routes) + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)', + ], +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js new file mode 100644 index 0000000000000..016ac8833b57f --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + experimental: { + ppr: true, + }, +} + +module.exports = nextConfig diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts new file mode 100644 index 0000000000000..4c583bbdf32c6 --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts @@ -0,0 +1,26 @@ +import { nextTestSetup } from 'e2e-utils' +import { expectedParams as expected } from './expected' + +describe('ppr-middleware-rewrite-force-dynamic-generate-static-params', () => { + const { next } = nextTestSetup({ + files: __dirname, + }) + + const expectedParams = JSON.stringify(expected) + + it('should have correct dynamic params', async () => { + // should be rewritten with /en + const browser = await next.browser('/') + expect(await browser.elementByCss('a').text()).toBe('Go to /1/2') + + // navigate to /1/2 + await browser.elementByCss('a').click() + + // should be rewritten with /en/1/2 with correct params + expect(await browser.elementByCss('p').text()).toBe(expectedParams) + + // reloading the page should have the same params + await browser.refresh() + expect(await browser.elementByCss('p').text()).toBe(expectedParams) + }) +})
diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts index 598b6ce2bf122..2940d4e30feb0 100644 --- a/packages/next/src/server/base-server.ts +++ b/packages/next/src/server/base-server.ts @@ -1131,6 +1131,8 @@ export default abstract class Server< matchedPath = this.normalize(matchedPath) const normalizedUrlPath = this.stripNextDataPath(urlPathname) + matchedPath = denormalizePagePath(matchedPath) // Perform locale detection and normalization. const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, { defaultLocale, @@ -1151,11 +1153,15 @@ export default abstract class Server< - // TODO: check if this is needed any more? - matchedPath = denormalizePagePath(matchedPath) - let srcPathname = matchedPath let pageIsDynamic = isDynamicRoute(srcPathname) + let paramsResult: { + params: ParsedUrlQuery | false + hasValidParams: boolean + } = { + params: false, + hasValidParams: false, + } if (!pageIsDynamic) { const match = await this.matchers.match(srcPathname, { @@ -1165,8 +1171,15 @@ export default abstract class Server< // Update the source pathname to the matched page's pathname. if (match) { srcPathname = match.definition.pathname - pageIsDynamic = typeof match.params !== 'undefined' + // The page is dynamic if the params are defined. We know at this + // stage that the matched path is not a static page if the params + // were parsed from the matched path header. + if (typeof match.params !== 'undefined') { + pageIsDynamic = true + paramsResult.hasValidParams = true @@ -1236,10 +1249,14 @@ export default abstract class Server< if (pageIsDynamic) { let params: ParsedUrlQuery | false = {} - let paramsResult = utils.normalizeDynamicRouteParams( - queryParams, - false - ) + // If we don't already have valid params, try to parse them from + // the query params. + if (!paramsResult.hasValidParams) { + paramsResult = utils.normalizeDynamicRouteParams( + queryParams, + ) + } // for prerendered ISR paths we attempt parsing the route // params from the URL directly as route-matches may not diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx index 0000000000000..8ed2439d837c4 +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx @@ -0,0 +1,17 @@ +import { type Params, expectedParams } from '../../../expected' +export default async function CatchAll({ + params, +}: { + params: Promise<Params> +}) { + const received = await params +export async function generateStaticParams(): Promise<Params[]> { + return [expectedParams] +export const dynamic = 'force-dynamic' diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx index 0000000000000..33d03756335ee +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx @@ -0,0 +1,5 @@ +import Link from 'next/link' +export default function Home() { diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx index 0000000000000..888614deda3ba +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx @@ -0,0 +1,8 @@ +export default function Root({ children }: { children: ReactNode }) { + return ( + <html> + <body>{children}</body> + </html> diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts index 0000000000000..37ae1d80cd3d1 +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts @@ -0,0 +1,9 @@ +export type Params = { + rest: string[] +export const expectedParams: Params = { + locale: 'en', + rest: ['1', '2'], diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts index 0000000000000..d6cac831af0fb +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts @@ -0,0 +1,21 @@ +import type { NextRequest } from 'next/server' +export function middleware(request: NextRequest) { + return NextResponse.rewrite( + new URL('/en' + request.nextUrl.pathname, request.url) +export const config = { + matcher: [ + /* + * - api (API routes) + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + ], diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js index 0000000000000..016ac8833b57f +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + experimental: { + ppr: true, + }, +module.exports = nextConfig diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts index 0000000000000..4c583bbdf32c6 +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts @@ -0,0 +1,26 @@ +import { nextTestSetup } from 'e2e-utils' +import { expectedParams as expected } from './expected' +describe('ppr-middleware-rewrite-force-dynamic-generate-static-params', () => { + const { next } = nextTestSetup({ + files: __dirname, + const expectedParams = JSON.stringify(expected) + // should be rewritten with /en + const browser = await next.browser('/') + expect(await browser.elementByCss('a').text()).toBe('Go to /1/2') + // navigate to /1/2 + await browser.elementByCss('a').click() + // should be rewritten with /en/1/2 with correct params + // reloading the page should have the same params + await browser.refresh()
[ "- // The page is dynamic if the params are defined.", "+ paramsResult.params = match.params", "+ }", "+ false", "+ return <p>{JSON.stringify(received)}</p>", "+ return <Link href=\"/1/2\">Go to /1/2</Link>", "+import { ReactNode } from 'react'", "+ locale: string", "+import { NextResponse } from 'next/server'", "+ * Match all request paths except for the ones starting with:", "+ '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',", "+ it('should have correct dynamic params', async () => {", "+})" ]
[ 36, 44, 46, 63, 84, 101, 109, 124, 139, 150, 156, 191, 206 ]
{ "additions": 122, "author": "wyattjoh", "deletions": 9, "html_url": "https://github.com/vercel/next.js/pull/77994", "issue_id": 77994, "merged_at": "2025-04-10T14:47:41Z", "omission_probability": 0.1, "pr_number": 77994, "repo": "vercel/next.js", "title": "fix: use the match result after matching using the matched path header", "total_changes": 131 }
315
diff --git a/turbopack/crates/turbopack-core/src/module_graph/mod.rs b/turbopack/crates/turbopack-core/src/module_graph/mod.rs index 5bf545577c9c7..4a89cc48d1f5b 100644 --- a/turbopack/crates/turbopack-core/src/module_graph/mod.rs +++ b/turbopack/crates/turbopack-core/src/module_graph/mod.rs @@ -325,6 +325,21 @@ impl SingleModuleGraph { graph.shrink_to_fit(); + #[cfg(debug_assertions)] + { + let mut duplicates = Vec::new(); + let mut set = FxHashSet::default(); + for &module in modules.keys() { + let ident = module.ident().to_string().await?; + if !set.insert(ident.clone()) { + duplicates.push(ident); + } + } + if !duplicates.is_empty() { + panic!("Duplicate module idents in graph: {:#?}", duplicates); + } + } + Ok(SingleModuleGraph { graph: TracedDiGraph::new(graph), number_of_modules,
diff --git a/turbopack/crates/turbopack-core/src/module_graph/mod.rs b/turbopack/crates/turbopack-core/src/module_graph/mod.rs index 5bf545577c9c7..4a89cc48d1f5b 100644 --- a/turbopack/crates/turbopack-core/src/module_graph/mod.rs +++ b/turbopack/crates/turbopack-core/src/module_graph/mod.rs @@ -325,6 +325,21 @@ impl SingleModuleGraph { graph.shrink_to_fit(); + #[cfg(debug_assertions)] + { + let mut duplicates = Vec::new(); + let mut set = FxHashSet::default(); + for &module in modules.keys() { + let ident = module.ident().to_string().await?; + if !set.insert(ident.clone()) { + duplicates.push(ident); + } + if !duplicates.is_empty() { + } + Ok(SingleModuleGraph { graph: TracedDiGraph::new(graph), number_of_modules,
[ "+ panic!(\"Duplicate module idents in graph: {:#?}\", duplicates);" ]
[ 19 ]
{ "additions": 15, "author": "sokra", "deletions": 0, "html_url": "https://github.com/vercel/next.js/pull/78025", "issue_id": 78025, "merged_at": "2025-04-10T15:23:25Z", "omission_probability": 0.1, "pr_number": 78025, "repo": "vercel/next.js", "title": "Turbopack: add debug assertion to check for duplicate modules", "total_changes": 15 }
316
diff --git a/test/e2e/app-dir/worker/app/string/page.js b/test/e2e/app-dir/worker/app/string/page.js new file mode 100644 index 0000000000000..ba9f0a9795f38 --- /dev/null +++ b/test/e2e/app-dir/worker/app/string/page.js @@ -0,0 +1,22 @@ +'use client' +import { useState } from 'react' + +export default function Home() { + const [state, setState] = useState('default') + return ( + <div> + <button + onClick={() => { + const worker = new Worker('/unbundled-worker.js') + worker.addEventListener('message', (event) => { + setState(event.data) + }) + }} + > + Get web worker data + </button> + <p>Worker state: </p> + <p id="worker-state">{state}</p> + </div> + ) +} diff --git a/test/e2e/app-dir/worker/public/unbundled-worker.js b/test/e2e/app-dir/worker/public/unbundled-worker.js new file mode 100644 index 0000000000000..50de186169b44 --- /dev/null +++ b/test/e2e/app-dir/worker/public/unbundled-worker.js @@ -0,0 +1 @@ +self.postMessage('unbundled-worker') diff --git a/test/e2e/app-dir/worker/worker.test.ts b/test/e2e/app-dir/worker/worker.test.ts index d6674b372acd2..aa4bd25edf7d1 100644 --- a/test/e2e/app-dir/worker/worker.test.ts +++ b/test/e2e/app-dir/worker/worker.test.ts @@ -1,5 +1,5 @@ import { nextTestSetup } from 'e2e-utils' -import { check } from 'next-test-utils' +import { retry } from 'next-test-utils' describe('app dir - workers', () => { const { next, skipped } = nextTestSetup({ @@ -17,9 +17,10 @@ describe('app dir - workers', () => { await browser.elementByCss('button').click() - await check( - async () => browser.elementByCss('#worker-state').text(), - 'worker.ts:worker-dep' + await retry(async () => + expect(await browser.elementByCss('#worker-state').text()).toBe( + 'worker.ts:worker-dep' + ) ) }) @@ -29,9 +30,23 @@ describe('app dir - workers', () => { await browser.elementByCss('button').click() - await check( - async () => browser.elementByCss('#worker-state').text(), - 'worker.ts:worker-dep' + await retry(async () => + expect(await browser.elementByCss('#worker-state').text()).toBe( + 'worker.ts:worker-dep' + ) + ) + }) + + it('should not bundle web workers with string specifiers', async () => { + const browser = await next.browser('/string') + expect(await browser.elementByCss('#worker-state').text()).toBe('default') + + await browser.elementByCss('button').click() + + await retry(async () => + expect(await browser.elementByCss('#worker-state').text()).toBe( + 'unbundled-worker' + ) ) }) }) diff --git a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs index 59a50d22ac969..99575c4c7b2db 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs @@ -1641,14 +1641,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( return Ok(()); } - let (args, hints) = explain_args(&args); - handler.span_warn_with_code( - span, - &format!("new Worker({args}) is not statically analyse-able{hints}",), - DiagnosticId::Error( - errors::failed_to_analyse::ecmascript::DYNAMIC_IMPORT.to_string(), - ), - ); + // Ignore (e.g. dynamic parameter or string literal), just as Webpack does return Ok(()); } _ => {} diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs new file mode 100644 index 0000000000000..2dfd34db8c102 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs @@ -0,0 +1,2 @@ +// Shouldn't cause a worker to be created, but will still be pulled in by `new URL()` +module.exports = 123 diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js index be07538408e45..f92a4088c8a18 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js @@ -11,9 +11,8 @@ import(/* turbopackIgnore: true */ "./ignore.mjs"); require(/* webpackIgnore: true */ "./ignore.cjs"); require(/* turbopackIgnore: true */ "./ignore.cjs"); -// and for workers -new Worker(/* webpackIgnore: true */ "./ignore.mjs"); -new Worker(/* turbopackIgnore: true */ "./ignore.cjs"); +new Worker(/* turbopackIgnore: true */ new URL("./ignore-worker.cjs", import.meta.url)) +new Worker(/* webpackIgnore: true */ new URL("./ignore-worker.cjs", import.meta.url)) export function foo(plugin) { return require(/* turbopackIgnore: true */ plugin) diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js similarity index 97% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js index 0e788ecb48d5f..e6b674c0d17b7 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js @@ -1,4 +1,4 @@ -(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js", { +(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js", { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)": ((__turbopack_context__) => { diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js.map similarity index 100% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js.map diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js similarity index 78% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js index 84eebf6c3bab8..7c4ff91fee634 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js @@ -1,4 +1,4 @@ -(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js", { +(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js", { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)": (function(__turbopack_context__) { @@ -20,6 +20,11 @@ __turbopack_context__.v(__turbopack_context__.b([ "output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_cjs_3041f295._.js" ])); }}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)": ((__turbopack_context__) => { + +var { g: global, __dirname } = __turbopack_context__; +{ +__turbopack_context__.v("/static/ignore-worker.c7cb9893.cjs");}}), "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)": ((__turbopack_context__) => { "use strict"; @@ -43,13 +48,12 @@ import(/* turbopackIgnore: true */ "./ignore.mjs"); // this should work for cjs requires too require(/* webpackIgnore: true */ "./ignore.cjs"); require(/* turbopackIgnore: true */ "./ignore.cjs"); -// and for workers -new Worker(/* webpackIgnore: true */ "./ignore.mjs"); -new Worker(/* turbopackIgnore: true */ "./ignore.cjs"); +new Worker(new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)"))); +new Worker(new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)"))); function foo(plugin) { return require(/* turbopackIgnore: true */ plugin); } }}), }]); -//# sourceMappingURL=4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map \ No newline at end of file +//# sourceMappingURL=4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map similarity index 59% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map index e4b4b27f5d280..0bb350528d36d 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map @@ -3,5 +3,5 @@ "sources": [], "sections": [ {"offset": {"line": 6, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs"],"sourcesContent":["module.exports = \"turbopack\";\n"],"names":[],"mappings":"AAAA,OAAO,OAAO,GAAG"}}, - {"offset": {"line": 27, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import(\"./vercel.mjs\").then(console.log);\nimport(/* webpackIgnore: false */ \"./vercel.mjs\").then(console.log);\nconsole.log(require(\"./vercel.cjs\"));\nnew Worker(/* turbopackIgnore: false */ new URL(\"./vercel.cjs\", import.meta.url));\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ \"./ignore.mjs\");\nimport(/* turbopackIgnore: true */ \"./ignore.mjs\");\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ \"./ignore.cjs\");\nrequire(/* turbopackIgnore: true */ \"./ignore.cjs\");\n\n// and for workers\nnew Worker(/* webpackIgnore: true */ \"./ignore.mjs\");\nnew Worker(/* turbopackIgnore: true */ \"./ignore.cjs\");\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":[],"mappings":";;;;;;;;AAAA,yLAAuB,IAAI,CAAC,QAAQ,GAAG;AACvC,yLAAkD,IAAI,CAAC,QAAQ,GAAG;AAClE,QAAQ,GAAG;AACX,IAAI;AAEJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxC,QAAQ,uBAAuB,GAAG;AAClC,QAAQ,yBAAyB,GAAG;AAEpC,kBAAkB;AAClB,IAAI,OAAO,uBAAuB,GAAG;AACrC,IAAI,OAAO,yBAAyB,GAAG;AAEhC,SAAS,IAAI,MAAM;IACxB,OAAO,QAAQ,yBAAyB,GAAG;AAC7C"}}] + {"offset": {"line": 32, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import(\"./vercel.mjs\").then(console.log);\nimport(/* webpackIgnore: false */ \"./vercel.mjs\").then(console.log);\nconsole.log(require(\"./vercel.cjs\"));\nnew Worker(/* turbopackIgnore: false */ new URL(\"./vercel.cjs\", import.meta.url));\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ \"./ignore.mjs\");\nimport(/* turbopackIgnore: true */ \"./ignore.mjs\");\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ \"./ignore.cjs\");\nrequire(/* turbopackIgnore: true */ \"./ignore.cjs\");\n\nnew Worker(/* turbopackIgnore: true */ new URL(\"./ignore-worker.cjs\", import.meta.url))\nnew Worker(/* webpackIgnore: true */ new URL(\"./ignore-worker.cjs\", import.meta.url))\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":[],"mappings":";;;;;;;;AAAA,yLAAuB,IAAI,CAAC,QAAQ,GAAG;AACvC,yLAAkD,IAAI,CAAC,QAAQ,GAAG;AAClE,QAAQ,GAAG;AACX,IAAI;AAEJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxC,QAAQ,uBAAuB,GAAG;AAClC,QAAQ,yBAAyB,GAAG;AAEpC,IAAI;AACJ,IAAI;AAEG,SAAS,IAAI,MAAM;IACxB,OAAO,QAAQ,yBAAyB,GAAG;AAC7C"}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js similarity index 57% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js index c7b89bd2ebbe7..2249b5ad7ff06 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js @@ -1,6 +1,6 @@ (globalThis.TURBOPACK = globalThis.TURBOPACK || []).push([ - "output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js", + "output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js", {}, - {"otherChunks":["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js","output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]} + {"otherChunks":["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js","output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]} ]); // Dummy runtime \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js.map similarity index 100% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js.map diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/static/ignore-worker.c7cb9893.cjs b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/static/ignore-worker.c7cb9893.cjs new file mode 100644 index 0000000000000..de83f1419f091 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/static/ignore-worker.c7cb9893.cjs @@ -0,0 +1,2 @@ +// Shouldn't cause a worker to be created, but will still be pulled in by `new URL()` +module.exports = 123 \ No newline at end of file
diff --git a/test/e2e/app-dir/worker/app/string/page.js b/test/e2e/app-dir/worker/app/string/page.js index 0000000000000..ba9f0a9795f38 +++ b/test/e2e/app-dir/worker/app/string/page.js @@ -0,0 +1,22 @@ +'use client' +import { useState } from 'react' +export default function Home() { + const [state, setState] = useState('default') + return ( + <div> + <button + onClick={() => { + const worker = new Worker('/unbundled-worker.js') + worker.addEventListener('message', (event) => { + setState(event.data) + }) + }} + > + Get web worker data + </button> + <p>Worker state: </p> + </div> + ) +} diff --git a/test/e2e/app-dir/worker/public/unbundled-worker.js b/test/e2e/app-dir/worker/public/unbundled-worker.js index 0000000000000..50de186169b44 +++ b/test/e2e/app-dir/worker/public/unbundled-worker.js @@ -0,0 +1 @@ +self.postMessage('unbundled-worker') diff --git a/test/e2e/app-dir/worker/worker.test.ts b/test/e2e/app-dir/worker/worker.test.ts index d6674b372acd2..aa4bd25edf7d1 100644 --- a/test/e2e/app-dir/worker/worker.test.ts +++ b/test/e2e/app-dir/worker/worker.test.ts @@ -1,5 +1,5 @@ import { nextTestSetup } from 'e2e-utils' -import { check } from 'next-test-utils' +import { retry } from 'next-test-utils' describe('app dir - workers', () => { const { next, skipped } = nextTestSetup({ @@ -17,9 +17,10 @@ describe('app dir - workers', () => { @@ -29,9 +30,23 @@ describe('app dir - workers', () => { + ) + }) + it('should not bundle web workers with string specifiers', async () => { + const browser = await next.browser('/string') + expect(await browser.elementByCss('#worker-state').text()).toBe('default') + await browser.elementByCss('button').click() }) diff --git a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs index 59a50d22ac969..99575c4c7b2db 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/mod.rs @@ -1641,14 +1641,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>( return Ok(()); } - let (args, hints) = explain_args(&args); - handler.span_warn_with_code( - span, - &format!("new Worker({args}) is not statically analyse-able{hints}",), - errors::failed_to_analyse::ecmascript::DYNAMIC_IMPORT.to_string(), - ), - ); + // Ignore (e.g. dynamic parameter or string literal), just as Webpack does return Ok(()); } _ => {} diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs index 0000000000000..2dfd34db8c102 +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js index be07538408e45..f92a4088c8a18 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js @@ -11,9 +11,8 @@ import(/* turbopackIgnore: true */ "./ignore.mjs"); +new Worker(/* turbopackIgnore: true */ new URL("./ignore-worker.cjs", import.meta.url)) +new Worker(/* webpackIgnore: true */ new URL("./ignore-worker.cjs", import.meta.url)) export function foo(plugin) { return require(/* turbopackIgnore: true */ plugin) diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js similarity index 97% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js index 0e788ecb48d5f..e6b674c0d17b7 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js -(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js", { +(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js", { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)": ((__turbopack_context__) => { diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js.map rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js.map diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js similarity index 78% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js index 84eebf6c3bab8..7c4ff91fee634 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js -(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js", { +(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push(["output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js", { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)": (function(__turbopack_context__) { @@ -20,6 +20,11 @@ __turbopack_context__.v(__turbopack_context__.b([ "output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_cjs_3041f295._.js" ])); +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)": ((__turbopack_context__) => { +var { g: global, __dirname } = __turbopack_context__; +{ +__turbopack_context__.v("/static/ignore-worker.c7cb9893.cjs");}}), "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)": ((__turbopack_context__) => { "use strict"; @@ -43,13 +48,12 @@ import(/* turbopackIgnore: true */ "./ignore.mjs"); // this should work for cjs requires too function foo(plugin) { return require(/* turbopackIgnore: true */ plugin); }]); -//# sourceMappingURL=4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map +//# sourceMappingURL=4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map similarity index 59% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map index e4b4b27f5d280..0bb350528d36d 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js.map @@ -3,5 +3,5 @@ "sources": [], "sections": [ {"offset": {"line": 6, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs"],"sourcesContent":["module.exports = \"turbopack\";\n"],"names":[],"mappings":"AAAA,OAAO,OAAO,GAAG"}}, - {"offset": {"line": 27, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import(\"./vercel.mjs\").then(console.log);\nimport(/* webpackIgnore: false */ \"./vercel.mjs\").then(console.log);\nconsole.log(require(\"./vercel.cjs\"));\nnew Worker(/* turbopackIgnore: false */ new URL(\"./vercel.cjs\", import.meta.url));\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ \"./ignore.mjs\");\nimport(/* turbopackIgnore: true */ \"./ignore.mjs\");\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ \"./ignore.cjs\");\nrequire(/* turbopackIgnore: true */ \"./ignore.cjs\");\n\n// and for workers\nnew Worker(/* webpackIgnore: true */ \"./ignore.mjs\");\nnew Worker(/* turbopackIgnore: true */ \"./ignore.cjs\");\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":[],"mappings":";;;;;;;;AAAA,yLAAuB,IAAI,CAAC,QAAQ,GAAG;AACvC,yLAAkD,IAAI,CAAC,QAAQ,GAAG;AAClE,QAAQ,GAAG;AACX,IAAI;AAEJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxC,QAAQ,uBAAuB,GAAG;AAClC,QAAQ,yBAAyB,GAAG;AAEpC,kBAAkB;AAClB,IAAI,OAAO,uBAAuB,GAAG;AACrC,IAAI,OAAO,yBAAyB,GAAG;AAEhC,SAAS,IAAI,MAAM;IACxB,OAAO,QAAQ,yBAAyB,GAAG;AAC7C"}}] + {"offset": {"line": 32, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import(\"./vercel.mjs\").then(console.log);\nimport(/* webpackIgnore: false */ \"./vercel.mjs\").then(console.log);\nconsole.log(require(\"./vercel.cjs\"));\nnew Worker(/* turbopackIgnore: false */ new URL(\"./vercel.cjs\", import.meta.url));\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ \"./ignore.mjs\");\nimport(/* turbopackIgnore: true */ \"./ignore.mjs\");\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ \"./ignore.cjs\");\nrequire(/* turbopackIgnore: true */ \"./ignore.cjs\");\n\nnew Worker(/* turbopackIgnore: true */ new URL(\"./ignore-worker.cjs\", import.meta.url))\nnew Worker(/* webpackIgnore: true */ new URL(\"./ignore-worker.cjs\", import.meta.url))\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":[],"mappings":";;;;;;;;AAAA,yLAAuB,IAAI,CAAC,QAAQ,GAAG;AACvC,yLAAkD,IAAI,CAAC,QAAQ,GAAG;AAClE,QAAQ,GAAG;AACX,IAAI;AAEJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxC,QAAQ,uBAAuB,GAAG;AAClC,QAAQ,yBAAyB,GAAG;AAEpC,IAAI;AACJ,IAAI;AAEG,SAAS,IAAI,MAAM;IACxB,OAAO,QAAQ,yBAAyB,GAAG;AAC7C"}}] diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js similarity index 57% rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js index c7b89bd2ebbe7..2249b5ad7ff06 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js @@ -1,6 +1,6 @@ (globalThis.TURBOPACK = globalThis.TURBOPACK || []).push([ - "output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js", + "output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js", {}, - {"otherChunks":["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_f0a767e9._.js","output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_e1849155._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]} + {"otherChunks":["output/4c35f_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0dd84fce._.js","output/4e721_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_7f940ff3._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]} ]); // Dummy runtime diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js.map rename from turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_03bfbde6.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/output/b1abf_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_a67357ee.js.map diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/static/ignore-worker.c7cb9893.cjs b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/static/ignore-worker.c7cb9893.cjs index 0000000000000..de83f1419f091 +++ b/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/static/ignore-worker.c7cb9893.cjs
[ "+ <p id=\"worker-state\">{state}</p>", "+ 'unbundled-worker'", "- DiagnosticId::Error(" ]
[ 24, 82, 99 ]
{ "additions": 65, "author": "mischnic", "deletions": 27, "html_url": "https://github.com/vercel/next.js/pull/78010", "issue_id": 78010, "merged_at": "2025-04-10T19:27:28Z", "omission_probability": 0.1, "pr_number": 78010, "repo": "vercel/next.js", "title": "Turbopack: bundle only `new Worker` with `new URL`", "total_changes": 92 }
317
diff --git a/Cargo.lock b/Cargo.lock index ac6cfacff7a05..be4ebea6f3f80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10145,6 +10145,7 @@ dependencies = [ "anyhow", "either", "flate2", + "hashbrown 0.14.5", "indexmap 2.7.1", "itertools 0.10.5", "postcard", diff --git a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs index e003b024b4f5c..41998db9992d9 100644 --- a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs +++ b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs @@ -1,4 +1,3 @@ -#![feature(hash_raw_entry)] #![feature(hash_extract_if)] pub mod map; diff --git a/turbopack/crates/turbopack-trace-server/Cargo.toml b/turbopack/crates/turbopack-trace-server/Cargo.toml index 423133b510cc2..799dab84c7614 100644 --- a/turbopack/crates/turbopack-trace-server/Cargo.toml +++ b/turbopack/crates/turbopack-trace-server/Cargo.toml @@ -15,6 +15,7 @@ bench = false anyhow = { workspace = true, features = ["backtrace"] } either = { workspace = true } flate2 = { version = "1.0.28" } +hashbrown = { workspace = true, features = ["raw"] } indexmap = { workspace = true, features = ["serde"] } itertools = { workspace = true } postcard = { workspace = true } diff --git a/turbopack/crates/turbopack-trace-server/src/bottom_up.rs b/turbopack/crates/turbopack-trace-server/src/bottom_up.rs index 26ebf157b88ee..76397fc0ea558 100644 --- a/turbopack/crates/turbopack-trace-server/src/bottom_up.rs +++ b/turbopack/crates/turbopack-trace-server/src/bottom_up.rs @@ -1,6 +1,6 @@ use std::{env, sync::Arc}; -use rustc_hash::FxHashMap; +use hashbrown::HashMap; use crate::{ span::{SpanBottomUp, SpanIndex}, @@ -10,7 +10,7 @@ use crate::{ pub struct SpanBottomUpBuilder { // These values won't change after creation: pub self_spans: Vec<SpanIndex>, - pub children: FxHashMap<String, SpanBottomUpBuilder>, + pub children: HashMap<String, SpanBottomUpBuilder>, pub example_span: SpanIndex, } @@ -18,7 +18,7 @@ impl SpanBottomUpBuilder { pub fn new(example_span: SpanIndex) -> Self { Self { self_spans: vec![], - children: FxHashMap::default(), + children: HashMap::default(), example_span, } } @@ -42,7 +42,7 @@ pub fn build_bottom_up_graph<'a>( .ok() .and_then(|s| s.parse().ok()) .unwrap_or(usize::MAX); - let mut roots = FxHashMap::default(); + let mut roots: HashMap<String, SpanBottomUpBuilder> = HashMap::default(); // unfortunately there is a rustc bug that fails the typechecking here // when using Either<impl Iterator, impl Iterator>. This error appears diff --git a/turbopack/crates/turbopack-trace-server/src/lib.rs b/turbopack/crates/turbopack-trace-server/src/lib.rs index 0afff5689eb13..ef164659a8a6e 100644 --- a/turbopack/crates/turbopack-trace-server/src/lib.rs +++ b/turbopack/crates/turbopack-trace-server/src/lib.rs @@ -1,5 +1,4 @@ #![feature(iter_intersperse)] -#![feature(hash_raw_entry)] #![feature(box_patterns)] use std::{hash::BuildHasherDefault, path::PathBuf, sync::Arc}; diff --git a/turbopack/crates/turbopack-trace-server/src/main.rs b/turbopack/crates/turbopack-trace-server/src/main.rs index 1cb04575731d3..6e49291fca768 100644 --- a/turbopack/crates/turbopack-trace-server/src/main.rs +++ b/turbopack/crates/turbopack-trace-server/src/main.rs @@ -1,5 +1,4 @@ #![feature(iter_intersperse)] -#![feature(hash_raw_entry)] #![feature(box_patterns)] use std::{hash::BuildHasherDefault, sync::Arc}; diff --git a/turbopack/crates/turbopack-trace-server/src/span.rs b/turbopack/crates/turbopack-trace-server/src/span.rs index 20d025862b3af..0cca4825fbb42 100644 --- a/turbopack/crates/turbopack-trace-server/src/span.rs +++ b/turbopack/crates/turbopack-trace-server/src/span.rs @@ -3,7 +3,7 @@ use std::{ sync::{Arc, OnceLock}, }; -use rustc_hash::FxHashMap; +use hashbrown::HashMap; use crate::timestamp::Timestamp; @@ -64,7 +64,7 @@ pub struct SpanTimeData { pub struct SpanExtra { pub graph: OnceLock<Vec<SpanGraphEvent>>, pub bottom_up: OnceLock<Vec<Arc<SpanBottomUp>>>, - pub search_index: OnceLock<FxHashMap<String, Vec<SpanIndex>>>, + pub search_index: OnceLock<HashMap<String, Vec<SpanIndex>>>, } #[derive(Default)] diff --git a/turbopack/crates/turbopack-trace-server/src/span_ref.rs b/turbopack/crates/turbopack-trace-server/src/span_ref.rs index 300c0c15032cc..8f42f30527a70 100644 --- a/turbopack/crates/turbopack-trace-server/src/span_ref.rs +++ b/turbopack/crates/turbopack-trace-server/src/span_ref.rs @@ -5,8 +5,9 @@ use std::{ vec, }; +use hashbrown::HashMap; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::FxHashSet; use crate::{ bottom_up::build_bottom_up_graph, @@ -414,9 +415,9 @@ impl<'a> SpanRef<'a> { }) } - fn search_index(&self) -> &FxHashMap<String, Vec<SpanIndex>> { + fn search_index(&self) -> &HashMap<String, Vec<SpanIndex>> { self.extra().search_index.get_or_init(|| { - let mut index: FxHashMap<String, Vec<SpanIndex>> = FxHashMap::default(); + let mut index: HashMap<String, Vec<SpanIndex>> = HashMap::default(); let mut queue = VecDeque::with_capacity(8); queue.push_back(*self); while let Some(span) = queue.pop_front() {
diff --git a/Cargo.lock b/Cargo.lock index ac6cfacff7a05..be4ebea6f3f80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10145,6 +10145,7 @@ dependencies = [ "anyhow", "either", "flate2", + "hashbrown 0.14.5", "indexmap 2.7.1", "itertools 0.10.5", "postcard", diff --git a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs index e003b024b4f5c..41998db9992d9 100644 --- a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs +++ b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs @@ -1,4 +1,3 @@ #![feature(hash_extract_if)] pub mod map; diff --git a/turbopack/crates/turbopack-trace-server/Cargo.toml b/turbopack/crates/turbopack-trace-server/Cargo.toml index 423133b510cc2..799dab84c7614 100644 --- a/turbopack/crates/turbopack-trace-server/Cargo.toml +++ b/turbopack/crates/turbopack-trace-server/Cargo.toml @@ -15,6 +15,7 @@ bench = false anyhow = { workspace = true, features = ["backtrace"] } either = { workspace = true } flate2 = { version = "1.0.28" } +hashbrown = { workspace = true, features = ["raw"] } indexmap = { workspace = true, features = ["serde"] } itertools = { workspace = true } postcard = { workspace = true } diff --git a/turbopack/crates/turbopack-trace-server/src/bottom_up.rs b/turbopack/crates/turbopack-trace-server/src/bottom_up.rs index 26ebf157b88ee..76397fc0ea558 100644 --- a/turbopack/crates/turbopack-trace-server/src/bottom_up.rs +++ b/turbopack/crates/turbopack-trace-server/src/bottom_up.rs @@ -1,6 +1,6 @@ use std::{env, sync::Arc}; span::{SpanBottomUp, SpanIndex}, @@ -10,7 +10,7 @@ use crate::{ pub struct SpanBottomUpBuilder { // These values won't change after creation: pub self_spans: Vec<SpanIndex>, - pub children: FxHashMap<String, SpanBottomUpBuilder>, + pub children: HashMap<String, SpanBottomUpBuilder>, pub example_span: SpanIndex, @@ -18,7 +18,7 @@ impl SpanBottomUpBuilder { pub fn new(example_span: SpanIndex) -> Self { Self { self_spans: vec![], - children: FxHashMap::default(), example_span, } @@ -42,7 +42,7 @@ pub fn build_bottom_up_graph<'a>( .ok() .and_then(|s| s.parse().ok()) .unwrap_or(usize::MAX); + let mut roots: HashMap<String, SpanBottomUpBuilder> = HashMap::default(); // unfortunately there is a rustc bug that fails the typechecking here // when using Either<impl Iterator, impl Iterator>. This error appears diff --git a/turbopack/crates/turbopack-trace-server/src/lib.rs b/turbopack/crates/turbopack-trace-server/src/lib.rs index 0afff5689eb13..ef164659a8a6e 100644 --- a/turbopack/crates/turbopack-trace-server/src/lib.rs +++ b/turbopack/crates/turbopack-trace-server/src/lib.rs use std::{hash::BuildHasherDefault, path::PathBuf, sync::Arc}; diff --git a/turbopack/crates/turbopack-trace-server/src/main.rs b/turbopack/crates/turbopack-trace-server/src/main.rs index 1cb04575731d3..6e49291fca768 100644 --- a/turbopack/crates/turbopack-trace-server/src/main.rs +++ b/turbopack/crates/turbopack-trace-server/src/main.rs use std::{hash::BuildHasherDefault, sync::Arc}; diff --git a/turbopack/crates/turbopack-trace-server/src/span.rs b/turbopack/crates/turbopack-trace-server/src/span.rs index 20d025862b3af..0cca4825fbb42 100644 --- a/turbopack/crates/turbopack-trace-server/src/span.rs +++ b/turbopack/crates/turbopack-trace-server/src/span.rs @@ -3,7 +3,7 @@ use std::{ sync::{Arc, OnceLock}, use crate::timestamp::Timestamp; @@ -64,7 +64,7 @@ pub struct SpanTimeData { pub struct SpanExtra { pub graph: OnceLock<Vec<SpanGraphEvent>>, pub bottom_up: OnceLock<Vec<Arc<SpanBottomUp>>>, - pub search_index: OnceLock<FxHashMap<String, Vec<SpanIndex>>>, + pub search_index: OnceLock<HashMap<String, Vec<SpanIndex>>>, #[derive(Default)] diff --git a/turbopack/crates/turbopack-trace-server/src/span_ref.rs b/turbopack/crates/turbopack-trace-server/src/span_ref.rs index 300c0c15032cc..8f42f30527a70 100644 --- a/turbopack/crates/turbopack-trace-server/src/span_ref.rs +++ b/turbopack/crates/turbopack-trace-server/src/span_ref.rs @@ -5,8 +5,9 @@ use std::{ vec, use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; -use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_hash::FxHashSet; bottom_up::build_bottom_up_graph, @@ -414,9 +415,9 @@ impl<'a> SpanRef<'a> { }) - fn search_index(&self) -> &FxHashMap<String, Vec<SpanIndex>> { + fn search_index(&self) -> &HashMap<String, Vec<SpanIndex>> { self.extra().search_index.get_or_init(|| { - let mut index: FxHashMap<String, Vec<SpanIndex>> = FxHashMap::default(); + let mut index: HashMap<String, Vec<SpanIndex>> = HashMap::default(); let mut queue = VecDeque::with_capacity(8); queue.push_back(*self); while let Some(span) = queue.pop_front() {
[ "+ children: HashMap::default(),", "- let mut roots = FxHashMap::default();" ]
[ 59, 67 ]
{ "additions": 12, "author": "wbinnssmith", "deletions": 12, "html_url": "https://github.com/vercel/next.js/pull/78032", "issue_id": 78032, "merged_at": "2025-04-10T20:12:19Z", "omission_probability": 0.1, "pr_number": 78032, "repo": "vercel/next.js", "title": "Turbopack: use hashbrown HashMaps instead of now-removed std raw entry api", "total_changes": 24 }
318
diff --git a/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs b/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs index f877ba4245bff..6aa0ec2cb076c 100644 --- a/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs +++ b/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs @@ -35,8 +35,8 @@ pub async fn get_swc_ecma_transform_rule_impl( plugin_configs: &[(RcStr, serde_json::Value)], enable_mdx_rs: bool, ) -> Result<Option<ModuleRule>> { - use anyhow::{bail, Context}; - use turbo_tasks::{TryJoinIterExt, Value}; + use anyhow::bail; + use turbo_tasks::{TryFlatJoinIterExt, Value}; use turbo_tasks_fs::FileContent; use turbopack::{resolve_options, resolve_options_context::ResolveOptionsContext}; use turbopack_core::{ @@ -78,30 +78,34 @@ pub async fn get_swc_ecma_transform_rule_impl( ) .as_raw_module_result(), Value::new(ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined)), + // TODO proper error location *project_path, request, resolve_options, false, + // TODO proper error location None, ) .await?; - let plugin_module = plugin_wasm_module_resolve_result - .first_module() - .await? - .context("Expected to find module")?; - let content = &*plugin_module.content().file_content().await?; + let Some(plugin_module) = &*plugin_wasm_module_resolve_result.first_module().await? + else { + // Ignore unresolveable plugin modules, handle_resolve_error has already emitted an + // issue. + return Ok(None); + }; + let content = &*plugin_module.content().file_content().await?; let FileContent::Content(file) = content else { bail!("Expected file content for plugin module"); }; - Ok(( + Ok(Some(( SwcPluginModule::new(name, file.content().to_bytes()?.to_vec()).resolved_cell(), config.clone(), - )) + ))) }) - .try_join() + .try_flat_join() .await?; Ok(Some(get_ecma_transform_rule( diff --git a/test/e2e/swc-plugins/app/layout.js b/test/e2e/swc-plugins/app/layout.js new file mode 100644 index 0000000000000..9342eed18c78f --- /dev/null +++ b/test/e2e/swc-plugins/app/layout.js @@ -0,0 +1,9 @@ +import React from 'react' + +export default function RootLayout({ children }) { + return ( + <html lang="en"> + <body>{children}</body> + </html> + ) +} diff --git a/test/e2e/swc-plugins/app/page.js b/test/e2e/swc-plugins/app/page.js new file mode 100644 index 0000000000000..e5e30cce60408 --- /dev/null +++ b/test/e2e/swc-plugins/app/page.js @@ -0,0 +1,5 @@ +import React from 'react' + +export default function Page({ children }) { + return <div data-custom-attribute>Hello World</div> +} diff --git a/test/e2e/swc-plugins/index.test.ts b/test/e2e/swc-plugins/index.test.ts new file mode 100644 index 0000000000000..8c5c70af08ebe --- /dev/null +++ b/test/e2e/swc-plugins/index.test.ts @@ -0,0 +1,58 @@ +import { nextTestSetup, isNextDev } from 'e2e-utils' + +describe('swcPlugins', () => { + describe('supports swcPlugins', () => { + const { next, skipped } = nextTestSetup({ + files: __dirname, + skipDeployment: true, + dependencies: { + '@swc/plugin-react-remove-properties': '7.0.2', + }, + }) + if (skipped) return + + it('basic case', async () => { + const html = await next.render('/') + expect(html).toContain('Hello World') + expect(html).not.toContain('data-custom-attribute') + }) + }) + ;(isNextDev ? describe : describe.skip)('invalid plugin name', () => { + const { next, skipped, isTurbopack } = nextTestSetup({ + files: __dirname, + skipDeployment: true, + overrideFiles: { + 'next.config.js': ` +module.exports = { + experimental: { + swcPlugins: [['@swc/plugin-nonexistent', {}]], + }, +}`, + }, + }) + if (skipped) return + + it('shows a redbox in dev', async () => { + const browser = await next.browser('/') + + if (isTurbopack) { + await expect(browser).toDisplayRedbox(` + { + "description": "Module not found: Can't resolve '@swc/plugin-nonexistent'", + "environmentLabel": null, + "label": "Build Error", + "source": "./ + Module not found: Can't resolve '@swc/plugin-nonexistent' + https://nextjs.org/docs/messages/module-not-found", + "stack": [], + } + `) + } else { + // TODO missing proper error with Webpack + await expect(browser).toDisplayRedbox( + `"Expected Redbox but found no visible one."` + ) + } + }) + }) +}) diff --git a/test/e2e/swc-plugins/next.config.js b/test/e2e/swc-plugins/next.config.js new file mode 100644 index 0000000000000..3acbf16005e7a --- /dev/null +++ b/test/e2e/swc-plugins/next.config.js @@ -0,0 +1,13 @@ +/** @type {import('next').NextConfig} */ +module.exports = { + experimental: { + swcPlugins: [ + [ + '@swc/plugin-react-remove-properties', + { + properties: ['^data-custom-attribute$'], + }, + ], + ], + }, +}
diff --git a/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs b/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs index f877ba4245bff..6aa0ec2cb076c 100644 --- a/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs +++ b/crates/next-core/src/next_shared/transforms/swc_ecma_transform_plugins.rs @@ -35,8 +35,8 @@ pub async fn get_swc_ecma_transform_rule_impl( plugin_configs: &[(RcStr, serde_json::Value)], enable_mdx_rs: bool, ) -> Result<Option<ModuleRule>> { - use anyhow::{bail, Context}; + use anyhow::bail; + use turbo_tasks::{TryFlatJoinIterExt, Value}; use turbo_tasks_fs::FileContent; use turbopack::{resolve_options, resolve_options_context::ResolveOptionsContext}; use turbopack_core::{ @@ -78,30 +78,34 @@ pub async fn get_swc_ecma_transform_rule_impl( ) .as_raw_module_result(), Value::new(ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined)), *project_path, request, resolve_options, false, None, ) .await?; - .first_module() - .await? - let content = &*plugin_module.content().file_content().await?; + let Some(plugin_module) = &*plugin_wasm_module_resolve_result.first_module().await? + else { + // Ignore unresolveable plugin modules, handle_resolve_error has already emitted an + // issue. + return Ok(None); + }; + let content = &*plugin_module.content().file_content().await?; let FileContent::Content(file) = content else { bail!("Expected file content for plugin module"); }; - Ok(( + Ok(Some(( SwcPluginModule::new(name, file.content().to_bytes()?.to_vec()).resolved_cell(), config.clone(), - )) + ))) }) - .try_join() + .try_flat_join() .await?; Ok(Some(get_ecma_transform_rule( diff --git a/test/e2e/swc-plugins/app/layout.js b/test/e2e/swc-plugins/app/layout.js index 0000000000000..9342eed18c78f +++ b/test/e2e/swc-plugins/app/layout.js @@ -0,0 +1,9 @@ +export default function RootLayout({ children }) { + return ( + <body>{children}</body> + </html> + ) diff --git a/test/e2e/swc-plugins/app/page.js b/test/e2e/swc-plugins/app/page.js index 0000000000000..e5e30cce60408 +++ b/test/e2e/swc-plugins/app/page.js @@ -0,0 +1,5 @@ +export default function Page({ children }) { + return <div data-custom-attribute>Hello World</div> diff --git a/test/e2e/swc-plugins/index.test.ts b/test/e2e/swc-plugins/index.test.ts index 0000000000000..8c5c70af08ebe +++ b/test/e2e/swc-plugins/index.test.ts @@ -0,0 +1,58 @@ +import { nextTestSetup, isNextDev } from 'e2e-utils' +describe('swcPlugins', () => { + describe('supports swcPlugins', () => { + const { next, skipped } = nextTestSetup({ + '@swc/plugin-react-remove-properties': '7.0.2', + const html = await next.render('/') + expect(html).toContain('Hello World') + expect(html).not.toContain('data-custom-attribute') + ;(isNextDev ? describe : describe.skip)('invalid plugin name', () => { + const { next, skipped, isTurbopack } = nextTestSetup({ + overrideFiles: { + 'next.config.js': ` + swcPlugins: [['@swc/plugin-nonexistent', {}]], +}`, + it('shows a redbox in dev', async () => { + const browser = await next.browser('/') + if (isTurbopack) { + await expect(browser).toDisplayRedbox(` + { + "description": "Module not found: Can't resolve '@swc/plugin-nonexistent'", + "environmentLabel": null, + "label": "Build Error", + "source": "./ + Module not found: Can't resolve '@swc/plugin-nonexistent' + https://nextjs.org/docs/messages/module-not-found", + "stack": [], + } + `) + } else { + // TODO missing proper error with Webpack + `"Expected Redbox but found no visible one."` + ) + } diff --git a/test/e2e/swc-plugins/next.config.js b/test/e2e/swc-plugins/next.config.js index 0000000000000..3acbf16005e7a +++ b/test/e2e/swc-plugins/next.config.js @@ -0,0 +1,13 @@ +/** @type {import('next').NextConfig} */ + swcPlugins: [ + [ + '@swc/plugin-react-remove-properties', + properties: ['^data-custom-attribute$'], + }, + ],
[ "- use turbo_tasks::{TryJoinIterExt, Value};", "- let plugin_module = plugin_wasm_module_resolve_result", "- .context(\"Expected to find module\")?;", "+ <html lang=\"en\">", "+ dependencies: {", "+ it('basic case', async () => {", "+ await expect(browser).toDisplayRedbox(", "+})", "+ {", "+ ]," ]
[ 9, 28, 31, 68, 97, 103, 141, 147, 160, 163 ]
{ "additions": 99, "author": "mischnic", "deletions": 10, "html_url": "https://github.com/vercel/next.js/pull/77990", "issue_id": 77990, "merged_at": "2025-04-10T20:17:24Z", "omission_probability": 0.1, "pr_number": 77990, "repo": "vercel/next.js", "title": "Turbopack: proper error message for swcPlugins", "total_changes": 109 }
319
diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index df29672da0216..463d270953f4f 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -390,6 +390,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => prerenderEarlyExit: z.boolean().optional(), proxyTimeout: z.number().gte(0).optional(), routerBFCache: z.boolean().optional(), + removeUnhandledRejectionListeners: z.boolean().optional(), scrollRestoration: z.boolean().optional(), sri: z .object({ diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index 2837e6e28dee1..b975d18039f3c 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -509,6 +509,16 @@ export interface ExperimentalConfig { */ routerBFCache?: boolean + /** + * Uninstalls all "unhandledRejection" listeners from the global process so + * that we can override the behavior, which in some runtimes is to exit the + * process on an unhandled rejection. + * + * This is experimental until we've considered the impact in various + * deployment environments. + */ + removeUnhandledRejectionListeners?: boolean + serverActions?: { /** * Allows adjusting body parser size limit for server actions. @@ -1302,6 +1312,7 @@ export const defaultConfig: NextConfig = { useEarlyImport: false, viewTransition: false, routerBFCache: false, + removeUnhandledRejectionListeners: false, staleTimes: { dynamic: 0, static: 300, diff --git a/packages/next/src/server/lib/start-server.ts b/packages/next/src/server/lib/start-server.ts index f19cdd24a5309..35f1e5af30d3c 100644 --- a/packages/next/src/server/lib/start-server.ts +++ b/packages/next/src/server/lib/start-server.ts @@ -30,7 +30,6 @@ import { CONFIG_FILES } from '../../shared/lib/constants' import { getStartServerInfo, logStartInfo } from './app-info-log' import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { type Span, trace, flushAllTraces } from '../../trace' -import { isPostpone } from './router-utils/is-postpone' import { isIPv6 } from './is-ipv6' import { AsyncCallbackSet } from './async-callback-set' import type { NextServer } from '../next' @@ -331,29 +330,13 @@ export async function startServer( process.exit(0) })() } - const exception = (err: Error) => { - if (isPostpone(err)) { - // React postpones that are unhandled might end up logged here but they're - // not really errors. They're just part of rendering. - return - } - // This is the render worker, we keep the process alive - console.error(err) - } // Make sure commands gracefully respect termination signals (e.g. from Docker) // Allow the graceful termination to be manually configurable if (!process.env.NEXT_MANUAL_SIG_HANDLE) { process.on('SIGINT', cleanup) process.on('SIGTERM', cleanup) } - process.on('rejectionHandled', () => { - // It is ok to await a Promise late in Next.js as it allows for better - // prefetching patterns to avoid waterfalls. We ignore loggining these. - // We should've already errored in anyway unhandledRejection. - }) - process.on('uncaughtException', exception) - process.on('unhandledRejection', exception) const initResult = await getRequestHandlers({ dir, diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index eb98fd4bc565e..a66633b09efee 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -112,6 +112,7 @@ import { AsyncCallbackSet } from './lib/async-callback-set' import { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers' import type { UnwrapPromise } from '../lib/coalesced-function' import { populateStaticEnv } from '../lib/static-env' +import { isPostpone } from './lib/router-utils/is-postpone' export * from './base-server' @@ -159,6 +160,87 @@ function getMiddlewareMatcher( return matcher } +function installProcessErrorHandlers( + shouldRemoveUnhandledRejectionListeners: boolean +) { + // The conventional wisdom of Node.js and other runtimes is to treat + // unhandled errors as fatal and exit the process. + // + // But Next.js is not a generic JS runtime — it's a specialized runtime for + // React Server Components. + // + // Many unhandled rejections are due to the late-awaiting pattern for + // prefetching data. In Next.js it's OK to call an async function without + // immediately awaiting it, to start the request as soon as possible + // without blocking unncessarily on the result. These can end up + // triggering an "unhandledRejection" if it later turns out that the + // data is not needed to render the page. Example: + // + // const promise = fetchData() + // const shouldShow = await checkCondition() + // if (shouldShow) { + // return <Component promise={promise} /> + // } + // + // In this example, `fetchData` is called immediately to start the request + // as soon as possible, but if `shouldShow` is false, then it will be + // discarded without unwrapping its result. If it errors, it will trigger + // an "unhandledRejection" event. + // + // Ideally, we would suppress these rejections completely without warning, + // because we don't consider them real errors. (TODO: Currently we do warn.) + // + // But regardless of whether we do or don't warn, we definitely shouldn't + // crash the entire process. + // + // Even a "legit" unhandled error unrelated to prefetching shouldn't + // prevent the rest of the page from rendering. + // + // So, we're going to intentionally override the default error handling + // behavior of the outer JS runtime to be more forgiving + + // Remove any existing "unhandledRejection" handlers. This is gated behind + // an experimental flag until we've considered the impact in various + // deployment environments. It's possible this may always need to + // be configurable. + if (shouldRemoveUnhandledRejectionListeners) { + process.removeAllListeners('unhandledRejection') + } + + // Install a new handler to prevent the process from crashing. + process.on('unhandledRejection', (reason: unknown) => { + if (isPostpone(reason)) { + // React postpones that are unhandled might end up logged here but they're + // not really errors. They're just part of rendering. + return + } + // Immediately log the error. + // TODO: Ideally, if we knew that this error was triggered by application + // code, we would suppress it entirely without logging. We can't reliably + // detect all of these, but when dynamicIO is enabled, we could suppress + // at least some of them by waiting to log the error until after all in- + // progress renders have completed. Then, only log errors for which there + // was not a corresponding "rejectionHandled" event. + console.error(reason) + }) + + process.on('rejectionHandled', () => { + // TODO: See note in the unhandledRejection handler above. In the future, + // we may use the "rejectionHandled" event to de-queue an error from + // being logged. + }) + + // Unhandled exceptions are errors triggered by non-async functions, so this + // is unrelated to the late-awaiting pattern. However, for similar reasons, + // we still shouldn't crash the process. Just log it. + process.on('uncaughtException', (reason: unknown) => { + if (isPostpone(reason)) { + return + } + console.error(reason) + }) +} + export default class NextNodeServer extends BaseServer< Options, NodeNextRequest, @@ -287,6 +369,11 @@ export default class NextNodeServer extends BaseServer< if (this.renderOpts.isExperimentalCompile) { populateStaticEnv(this.nextConfig) } + + const shouldRemoveUnhandledRejectionListeners = Boolean( + options.conf.experimental?.removeUnhandledRejectionListeners + ) + installProcessErrorHandlers(shouldRemoveUnhandledRejectionListeners) } public async unstable_preloadEntries(): Promise<void> {
diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index df29672da0216..463d270953f4f 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -390,6 +390,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => prerenderEarlyExit: z.boolean().optional(), proxyTimeout: z.number().gte(0).optional(), routerBFCache: z.boolean().optional(), + removeUnhandledRejectionListeners: z.boolean().optional(), scrollRestoration: z.boolean().optional(), sri: z .object({ diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index 2837e6e28dee1..b975d18039f3c 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -509,6 +509,16 @@ export interface ExperimentalConfig { */ routerBFCache?: boolean + /** + * Uninstalls all "unhandledRejection" listeners from the global process so + * that we can override the behavior, which in some runtimes is to exit the + * process on an unhandled rejection. + * + * This is experimental until we've considered the impact in various + * deployment environments. + */ + removeUnhandledRejectionListeners?: boolean serverActions?: { /** * Allows adjusting body parser size limit for server actions. @@ -1302,6 +1312,7 @@ export const defaultConfig: NextConfig = { useEarlyImport: false, viewTransition: false, routerBFCache: false, + removeUnhandledRejectionListeners: false, staleTimes: { dynamic: 0, static: 300, diff --git a/packages/next/src/server/lib/start-server.ts b/packages/next/src/server/lib/start-server.ts index f19cdd24a5309..35f1e5af30d3c 100644 --- a/packages/next/src/server/lib/start-server.ts +++ b/packages/next/src/server/lib/start-server.ts @@ -30,7 +30,6 @@ import { CONFIG_FILES } from '../../shared/lib/constants' import { getStartServerInfo, logStartInfo } from './app-info-log' import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { type Span, trace, flushAllTraces } from '../../trace' -import { isPostpone } from './router-utils/is-postpone' import { isIPv6 } from './is-ipv6' import { AsyncCallbackSet } from './async-callback-set' import type { NextServer } from '../next' @@ -331,29 +330,13 @@ export async function startServer( process.exit(0) })() - const exception = (err: Error) => { - if (isPostpone(err)) { - // not really errors. They're just part of rendering. - return - // This is the render worker, we keep the process alive - console.error(err) - } // Make sure commands gracefully respect termination signals (e.g. from Docker) // Allow the graceful termination to be manually configurable if (!process.env.NEXT_MANUAL_SIG_HANDLE) { process.on('SIGINT', cleanup) process.on('SIGTERM', cleanup) - process.on('rejectionHandled', () => { - // It is ok to await a Promise late in Next.js as it allows for better - // prefetching patterns to avoid waterfalls. We ignore loggining these. - // We should've already errored in anyway unhandledRejection. - }) - process.on('uncaughtException', exception) - process.on('unhandledRejection', exception) const initResult = await getRequestHandlers({ dir, diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index eb98fd4bc565e..a66633b09efee 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -112,6 +112,7 @@ import { AsyncCallbackSet } from './lib/async-callback-set' import { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers' import type { UnwrapPromise } from '../lib/coalesced-function' import { populateStaticEnv } from '../lib/static-env' +import { isPostpone } from './lib/router-utils/is-postpone' export * from './base-server' @@ -159,6 +160,87 @@ function getMiddlewareMatcher( return matcher } + shouldRemoveUnhandledRejectionListeners: boolean +) { + // The conventional wisdom of Node.js and other runtimes is to treat + // unhandled errors as fatal and exit the process. + // But Next.js is not a generic JS runtime — it's a specialized runtime for + // React Server Components. + // Many unhandled rejections are due to the late-awaiting pattern for + // prefetching data. In Next.js it's OK to call an async function without + // immediately awaiting it, to start the request as soon as possible + // without blocking unncessarily on the result. These can end up + // triggering an "unhandledRejection" if it later turns out that the + // data is not needed to render the page. Example: + // const promise = fetchData() + // const shouldShow = await checkCondition() + // return <Component promise={promise} /> + // } + // In this example, `fetchData` is called immediately to start the request + // as soon as possible, but if `shouldShow` is false, then it will be + // discarded without unwrapping its result. If it errors, it will trigger + // Ideally, we would suppress these rejections completely without warning, + // because we don't consider them real errors. (TODO: Currently we do warn.) + // But regardless of whether we do or don't warn, we definitely shouldn't + // crash the entire process. + // Even a "legit" unhandled error unrelated to prefetching shouldn't + // prevent the rest of the page from rendering. + // So, we're going to intentionally override the default error handling + // an experimental flag until we've considered the impact in various + // deployment environments. It's possible this may always need to + // be configurable. + if (shouldRemoveUnhandledRejectionListeners) { + process.removeAllListeners('unhandledRejection') + } + // Install a new handler to prevent the process from crashing. + process.on('unhandledRejection', (reason: unknown) => { + // not really errors. They're just part of rendering. + // Immediately log the error. + // TODO: Ideally, if we knew that this error was triggered by application + // code, we would suppress it entirely without logging. We can't reliably + // at least some of them by waiting to log the error until after all in- + // progress renders have completed. Then, only log errors for which there + // was not a corresponding "rejectionHandled" event. + process.on('rejectionHandled', () => { + // TODO: See note in the unhandledRejection handler above. In the future, + // we may use the "rejectionHandled" event to de-queue an error from + // being logged. + // Unhandled exceptions are errors triggered by non-async functions, so this + // is unrelated to the late-awaiting pattern. However, for similar reasons, + // we still shouldn't crash the process. Just log it. + process.on('uncaughtException', (reason: unknown) => { +} export default class NextNodeServer extends BaseServer< Options, NodeNextRequest, @@ -287,6 +369,11 @@ export default class NextNodeServer extends BaseServer< if (this.renderOpts.isExperimentalCompile) { populateStaticEnv(this.nextConfig) } + const shouldRemoveUnhandledRejectionListeners = Boolean( + options.conf.experimental?.removeUnhandledRejectionListeners + ) + installProcessErrorHandlers(shouldRemoveUnhandledRejectionListeners) } public async unstable_preloadEntries(): Promise<void> {
[ "- // React postpones that are unhandled might end up logged here but they're", "- }", "+function installProcessErrorHandlers(", "+ // if (shouldShow) {", "+ // an \"unhandledRejection\" event.", "+ // behavior of the outer JS runtime to be more forgiving", "+ // Remove any existing \"unhandledRejection\" handlers. This is gated behind", "+ // React postpones that are unhandled might end up logged here but they're", "+ // detect all of these, but when dynamicIO is enabled, we could suppress" ]
[ 59, 62, 99, 117, 124, 136, 138, 149, 156 ]
{ "additions": 99, "author": "acdlite", "deletions": 17, "html_url": "https://github.com/vercel/next.js/pull/77997", "issue_id": 77997, "merged_at": "2025-04-10T20:31:28Z", "omission_probability": 0.1, "pr_number": 77997, "repo": "vercel/next.js", "title": "Move unhandled rejection handling to shared path", "total_changes": 116 }
320
diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 41eb67abca569..e7fbc0c176d98 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2025-02-12" +channel = "nightly-2025-04-10" components = ["rustfmt", "clippy", "rust-analyzer"] profile = "minimal" diff --git a/turbopack/crates/turbo-static/src/main.rs b/turbopack/crates/turbo-static/src/main.rs index 8b996f62c08c5..498f80be8056a 100644 --- a/turbopack/crates/turbo-static/src/main.rs +++ b/turbopack/crates/turbo-static/src/main.rs @@ -194,6 +194,7 @@ fn resolve_concurrency( for (ident, references) in dep_tree { for reference in references { + #[allow(clippy::map_entry)] // This doesn't insert into dep_tree, so entry isn't useful if !dep_tree.contains_key(&reference.identifier) { // this is a task that is not in the task list // so we can't resolve it diff --git a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs index 41998db9992d9..42526ed9e2b25 100644 --- a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs +++ b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs @@ -1,5 +1,3 @@ -#![feature(hash_extract_if)] - pub mod map; pub mod set; diff --git a/turbopack/crates/turbo-tasks-fs/src/lib.rs b/turbopack/crates/turbo-tasks-fs/src/lib.rs index 464f8d3867e95..20f8395e8b2f0 100644 --- a/turbopack/crates/turbo-tasks-fs/src/lib.rs +++ b/turbopack/crates/turbo-tasks-fs/src/lib.rs @@ -1,6 +1,5 @@ #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![feature(trivial_bounds)] -#![feature(hash_extract_if)] #![feature(min_specialization)] #![feature(iter_advance_by)] #![feature(io_error_more)] diff --git a/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr b/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr index 7fb9a0baa3031..0a167e2e1632d 100644 --- a/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr +++ b/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr @@ -4,6 +4,15 @@ error: methods taking `self` are not supported with `operation` 13 | fn arbitrary_self_type(self: OperationVc<Self>) -> Vc<()> { | ^^^^^^^^^^^^^^^^^^^^^^^ +error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>` + --> tests/function/fail_operation_method_self_type.rs:13:34 + | +13 | fn arbitrary_self_type(self: OperationVc<Self>) -> Vc<()> { + | ^^^^^^^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or some type implementing `Receiver` + = help: consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>` + error[E0277]: the trait bound `fn(...) -> ... {...::arbitrary_self_type_turbo_tasks_function_inline}: IntoTaskFnWithThis<_, _, _>` is not satisfied --> tests/function/fail_operation_method_self_type.rs:10:1 | @@ -22,12 +31,3 @@ note: required by a bound in `NativeFunction::new_method` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `NativeFunction::new_method` = note: consider using `--verbose` to print the full type name to the console = note: this error originates in the attribute macro `turbo_tasks::value_impl` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>` - --> tests/function/fail_operation_method_self_type.rs:13:34 - | -13 | fn arbitrary_self_type(self: OperationVc<Self>) -> Vc<()> { - | ^^^^^^^^^^^^^^^^^ - | - = note: type of `self` must be `Self` or some type implementing `Receiver` - = help: consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>` diff --git a/turbopack/crates/turbo-tasks-memory/src/lib.rs b/turbopack/crates/turbo-tasks-memory/src/lib.rs index 9f1f3e3ba67e4..bd2a5476b5b40 100644 --- a/turbopack/crates/turbo-tasks-memory/src/lib.rs +++ b/turbopack/crates/turbo-tasks-memory/src/lib.rs @@ -1,4 +1,3 @@ -#![feature(hash_extract_if)] #![feature(type_alias_impl_trait)] #![feature(box_patterns)] #![feature(int_roundings)] diff --git a/turbopack/crates/turbo-tasks/src/lib.rs b/turbopack/crates/turbo-tasks/src/lib.rs index 35a34f3e3f493..c76166d663222 100644 --- a/turbopack/crates/turbo-tasks/src/lib.rs +++ b/turbopack/crates/turbo-tasks/src/lib.rs @@ -29,7 +29,6 @@ #![feature(trivial_bounds)] #![feature(min_specialization)] #![feature(try_trait_v2)] -#![feature(hash_extract_if)] #![deny(unsafe_op_in_unsafe_fn)] #![feature(result_flattening)] #![feature(error_generic_member_access)] diff --git a/turbopack/crates/turbopack-css/src/process.rs b/turbopack/crates/turbopack-css/src/process.rs index 81120ec02f420..1ca595ce6779b 100644 --- a/turbopack/crates/turbopack-css/src/process.rs +++ b/turbopack/crates/turbopack-css/src/process.rs @@ -112,6 +112,7 @@ impl StyleSheetLike<'_, '_> { pub struct UnresolvedUrlReferences(pub Vec<(String, ResolvedVc<UrlAssetReference>)>); #[turbo_tasks::value(shared, serialization = "none", eq = "manual", cell = "new")] +#[allow(clippy::large_enum_variant)] // This is a turbo-tasks value pub enum ParseCssResult { Ok { code: ResolvedVc<FileContent>, diff --git a/turbopack/crates/turbopack-dev-server/src/http.rs b/turbopack/crates/turbopack-dev-server/src/http.rs index 62b2acac33f1e..84d6657396f2b 100644 --- a/turbopack/crates/turbopack-dev-server/src/http.rs +++ b/turbopack/crates/turbopack-dev-server/src/http.rs @@ -1,5 +1,3 @@ -use std::io::{Error, ErrorKind}; - use anyhow::{anyhow, Result}; use auto_hash_map::AutoSet; use futures::{StreamExt, TryStreamExt}; @@ -177,10 +175,7 @@ pub async fn process_request_with_content_source( header_map.insert(CONTENT_ENCODING, HeaderValue::from_static("gzip")); // Grab ropereader stream, coerce anyhow::Error to std::io::Error - let stream_ext = content - .read() - .into_stream() - .map_err(|err| Error::new(ErrorKind::Other, err)); + let stream_ext = content.read().into_stream().map_err(std::io::Error::other); let gzipped_stream = ReaderStream::new(async_compression::tokio::bufread::GzipEncoder::new( diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs index ad799d688e226..f9e314008fbba 100644 --- a/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs +++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs @@ -1516,10 +1516,9 @@ impl VisitAstPath for Analyzer<'_> { decl: &'ast FnDecl, ast_path: &mut AstNodePath<AstParentNodeRef<'r>>, ) { - let old = replace( - &mut self.cur_fn_return_values, - Some(get_fn_init_return_vals(decl.function.body.as_ref())), - ); + let old = self + .cur_fn_return_values + .replace(get_fn_init_return_vals(decl.function.body.as_ref())); let old_ident = self.cur_fn_ident; self.cur_fn_ident = decl.function.span.lo.0; decl.visit_children_with_ast_path(self, ast_path); @@ -1540,10 +1539,9 @@ impl VisitAstPath for Analyzer<'_> { expr: &'ast FnExpr, ast_path: &mut AstNodePath<AstParentNodeRef<'r>>, ) { - let old = replace( - &mut self.cur_fn_return_values, - Some(get_fn_init_return_vals(expr.function.body.as_ref())), - ); + let old = self + .cur_fn_return_values + .replace(get_fn_init_return_vals(expr.function.body.as_ref())); let old_ident = self.cur_fn_ident; self.cur_fn_ident = expr.function.span.lo.0; expr.visit_children_with_ast_path(self, ast_path); diff --git a/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs b/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs index 4c9000aa06aed..e42c497047d90 100644 --- a/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs +++ b/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs @@ -191,8 +191,8 @@ impl Comments for ImmutableComments { } pub struct CowComments<'a> { - leading: RefCell<FxHashMap<BytePos, Cow<'a, Vec<Comment>>>>, - trailing: RefCell<FxHashMap<BytePos, Cow<'a, Vec<Comment>>>>, + leading: RefCell<FxHashMap<BytePos, Cow<'a, [Comment]>>>, + trailing: RefCell<FxHashMap<BytePos, Cow<'a, [Comment]>>>, } impl<'a> CowComments<'a> { @@ -202,14 +202,14 @@ impl<'a> CowComments<'a> { comments .leading .iter() - .map(|(&key, value)| (key, Cow::Borrowed(value))) + .map(|(&key, value)| (key, Cow::Borrowed(&value[..]))) .collect(), ), trailing: RefCell::new( comments .trailing .iter() - .map(|(&key, value)| (key, Cow::Borrowed(value))) + .map(|(&key, value)| (key, Cow::Borrowed(&value[..]))) .collect(), ), } @@ -274,7 +274,7 @@ impl Comments for CowComments<'_> { &self, pos: swc_core::common::BytePos, ) -> Option<Vec<swc_core::common::comments::Comment>> { - self.leading.borrow().get(&pos).map(|v| (**v).clone()) + self.leading.borrow().get(&pos).map(|v| (**v).to_vec()) } fn add_trailing( @@ -315,7 +315,7 @@ impl Comments for CowComments<'_> { &self, pos: swc_core::common::BytePos, ) -> Option<Vec<swc_core::common::comments::Comment>> { - self.trailing.borrow().get(&pos).map(|v| (**v).clone()) + self.trailing.borrow().get(&pos).map(|v| (**v).to_vec()) } fn add_pure_comment(&self, _pos: swc_core::common::BytePos) { diff --git a/turbopack/crates/turbopack-ecmascript/src/utils.rs b/turbopack/crates/turbopack-ecmascript/src/utils.rs index a8ccc105be5ab..2e83eb5a654dd 100644 --- a/turbopack/crates/turbopack-ecmascript/src/utils.rs +++ b/turbopack/crates/turbopack-ecmascript/src/utils.rs @@ -114,11 +114,8 @@ where impl std::io::Write for DisplayWriter<'_, '_> { fn write(&mut self, bytes: &[u8]) -> std::result::Result<usize, std::io::Error> { self.f - .write_str( - std::str::from_utf8(bytes) - .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?, - ) - .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?; + .write_str(std::str::from_utf8(bytes).map_err(std::io::Error::other)?) + .map_err(std::io::Error::other)?; Ok(bytes.len()) } diff --git a/turbopack/crates/turbopack-node/src/lib.rs b/turbopack/crates/turbopack-node/src/lib.rs index 672736fca9388..606c9022e2b4e 100644 --- a/turbopack/crates/turbopack-node/src/lib.rs +++ b/turbopack/crates/turbopack-node/src/lib.rs @@ -1,7 +1,6 @@ #![feature(min_specialization)] #![feature(arbitrary_self_types)] #![feature(arbitrary_self_types_pointers)] -#![feature(extract_if)] use std::{iter::once, thread::available_parallelism}; diff --git a/turbopack/crates/turbopack-trace-server/src/store.rs b/turbopack/crates/turbopack-trace-server/src/store.rs index e520e187aaa0c..b37892907b3c2 100644 --- a/turbopack/crates/turbopack-trace-server/src/store.rs +++ b/turbopack/crates/turbopack-trace-server/src/store.rs @@ -1,7 +1,6 @@ use std::{ cmp::{max, min}, env, - mem::replace, num::NonZeroUsize, sync::{atomic::AtomicU64, OnceLock}, }; @@ -266,7 +265,7 @@ impl Store { outdated_spans.insert(span_index); let span = &mut self.spans[span_index.get()]; - let old_parent = replace(&mut span.parent, Some(parent)); + let old_parent = span.parent.replace(parent); let old_parent = if let Some(parent) = old_parent { outdated_spans.insert(parent); &mut self.spans[parent.get()]
diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 41eb67abca569..e7fbc0c176d98 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2025-02-12" +channel = "nightly-2025-04-10" components = ["rustfmt", "clippy", "rust-analyzer"] profile = "minimal" diff --git a/turbopack/crates/turbo-static/src/main.rs b/turbopack/crates/turbo-static/src/main.rs index 8b996f62c08c5..498f80be8056a 100644 --- a/turbopack/crates/turbo-static/src/main.rs +++ b/turbopack/crates/turbo-static/src/main.rs @@ -194,6 +194,7 @@ fn resolve_concurrency( for (ident, references) in dep_tree { for reference in references { + #[allow(clippy::map_entry)] // This doesn't insert into dep_tree, so entry isn't useful if !dep_tree.contains_key(&reference.identifier) { // this is a task that is not in the task list // so we can't resolve it diff --git a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs index 41998db9992d9..42526ed9e2b25 100644 --- a/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs +++ b/turbopack/crates/turbo-tasks-auto-hash-map/src/lib.rs pub mod map; pub mod set; diff --git a/turbopack/crates/turbo-tasks-fs/src/lib.rs b/turbopack/crates/turbo-tasks-fs/src/lib.rs index 464f8d3867e95..20f8395e8b2f0 100644 --- a/turbopack/crates/turbo-tasks-fs/src/lib.rs +++ b/turbopack/crates/turbo-tasks-fs/src/lib.rs @@ -1,6 +1,5 @@ #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![feature(iter_advance_by)] #![feature(io_error_more)] diff --git a/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr b/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr index 7fb9a0baa3031..0a167e2e1632d 100644 --- a/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr +++ b/turbopack/crates/turbo-tasks-macros-tests/tests/function/fail_operation_method_self_type.stderr @@ -4,6 +4,15 @@ error: methods taking `self` are not supported with `operation` 13 | fn arbitrary_self_type(self: OperationVc<Self>) -> Vc<()> { | ^^^^^^^^^^^^^^^^^^^^^^^ +error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>` + --> tests/function/fail_operation_method_self_type.rs:13:34 +13 | fn arbitrary_self_type(self: OperationVc<Self>) -> Vc<()> { + | ^^^^^^^^^^^^^^^^^ + = note: type of `self` must be `Self` or some type implementing `Receiver` + = help: consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>` + error[E0277]: the trait bound `fn(...) -> ... {...::arbitrary_self_type_turbo_tasks_function_inline}: IntoTaskFnWithThis<_, _, _>` is not satisfied --> tests/function/fail_operation_method_self_type.rs:10:1 | @@ -22,12 +31,3 @@ note: required by a bound in `NativeFunction::new_method` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `NativeFunction::new_method` = note: consider using `--verbose` to print the full type name to the console = note: this error originates in the attribute macro `turbo_tasks::value_impl` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>` - --> tests/function/fail_operation_method_self_type.rs:13:34 -13 | fn arbitrary_self_type(self: OperationVc<Self>) -> Vc<()> { - | ^^^^^^^^^^^^^^^^^ - = note: type of `self` must be `Self` or some type implementing `Receiver` - = help: consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>` diff --git a/turbopack/crates/turbo-tasks-memory/src/lib.rs b/turbopack/crates/turbo-tasks-memory/src/lib.rs index 9f1f3e3ba67e4..bd2a5476b5b40 100644 --- a/turbopack/crates/turbo-tasks-memory/src/lib.rs +++ b/turbopack/crates/turbo-tasks-memory/src/lib.rs @@ -1,4 +1,3 @@ #![feature(type_alias_impl_trait)] #![feature(box_patterns)] #![feature(int_roundings)] diff --git a/turbopack/crates/turbo-tasks/src/lib.rs b/turbopack/crates/turbo-tasks/src/lib.rs index 35a34f3e3f493..c76166d663222 100644 --- a/turbopack/crates/turbo-tasks/src/lib.rs +++ b/turbopack/crates/turbo-tasks/src/lib.rs @@ -29,7 +29,6 @@ #![feature(try_trait_v2)] #![deny(unsafe_op_in_unsafe_fn)] #![feature(result_flattening)] #![feature(error_generic_member_access)] diff --git a/turbopack/crates/turbopack-css/src/process.rs b/turbopack/crates/turbopack-css/src/process.rs index 81120ec02f420..1ca595ce6779b 100644 --- a/turbopack/crates/turbopack-css/src/process.rs +++ b/turbopack/crates/turbopack-css/src/process.rs @@ -112,6 +112,7 @@ impl StyleSheetLike<'_, '_> { pub struct UnresolvedUrlReferences(pub Vec<(String, ResolvedVc<UrlAssetReference>)>); #[turbo_tasks::value(shared, serialization = "none", eq = "manual", cell = "new")] pub enum ParseCssResult { Ok { code: ResolvedVc<FileContent>, diff --git a/turbopack/crates/turbopack-dev-server/src/http.rs b/turbopack/crates/turbopack-dev-server/src/http.rs index 62b2acac33f1e..84d6657396f2b 100644 --- a/turbopack/crates/turbopack-dev-server/src/http.rs +++ b/turbopack/crates/turbopack-dev-server/src/http.rs -use std::io::{Error, ErrorKind}; use anyhow::{anyhow, Result}; use auto_hash_map::AutoSet; use futures::{StreamExt, TryStreamExt}; @@ -177,10 +175,7 @@ pub async fn process_request_with_content_source( header_map.insert(CONTENT_ENCODING, HeaderValue::from_static("gzip")); // Grab ropereader stream, coerce anyhow::Error to std::io::Error - let stream_ext = content - .read() - .into_stream() - .map_err(|err| Error::new(ErrorKind::Other, err)); + let stream_ext = content.read().into_stream().map_err(std::io::Error::other); let gzipped_stream = ReaderStream::new(async_compression::tokio::bufread::GzipEncoder::new( diff --git a/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs b/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs index ad799d688e226..f9e314008fbba 100644 --- a/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs +++ b/turbopack/crates/turbopack-ecmascript/src/analyzer/graph.rs @@ -1516,10 +1516,9 @@ impl VisitAstPath for Analyzer<'_> { decl: &'ast FnDecl, - Some(get_fn_init_return_vals(decl.function.body.as_ref())), + .replace(get_fn_init_return_vals(decl.function.body.as_ref())); self.cur_fn_ident = decl.function.span.lo.0; decl.visit_children_with_ast_path(self, ast_path); @@ -1540,10 +1539,9 @@ impl VisitAstPath for Analyzer<'_> { expr: &'ast FnExpr, - Some(get_fn_init_return_vals(expr.function.body.as_ref())), + .replace(get_fn_init_return_vals(expr.function.body.as_ref())); self.cur_fn_ident = expr.function.span.lo.0; expr.visit_children_with_ast_path(self, ast_path); diff --git a/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs b/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs index 4c9000aa06aed..e42c497047d90 100644 --- a/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs +++ b/turbopack/crates/turbopack-ecmascript/src/swc_comments.rs @@ -191,8 +191,8 @@ impl Comments for ImmutableComments { pub struct CowComments<'a> { - leading: RefCell<FxHashMap<BytePos, Cow<'a, Vec<Comment>>>>, - trailing: RefCell<FxHashMap<BytePos, Cow<'a, Vec<Comment>>>>, + leading: RefCell<FxHashMap<BytePos, Cow<'a, [Comment]>>>, + trailing: RefCell<FxHashMap<BytePos, Cow<'a, [Comment]>>>, impl<'a> CowComments<'a> { @@ -202,14 +202,14 @@ impl<'a> CowComments<'a> { .leading trailing: RefCell::new( .trailing } @@ -274,7 +274,7 @@ impl Comments for CowComments<'_> { - self.leading.borrow().get(&pos).map(|v| (**v).clone()) + self.leading.borrow().get(&pos).map(|v| (**v).to_vec()) fn add_trailing( @@ -315,7 +315,7 @@ impl Comments for CowComments<'_> { - self.trailing.borrow().get(&pos).map(|v| (**v).clone()) + self.trailing.borrow().get(&pos).map(|v| (**v).to_vec()) fn add_pure_comment(&self, _pos: swc_core::common::BytePos) { diff --git a/turbopack/crates/turbopack-ecmascript/src/utils.rs b/turbopack/crates/turbopack-ecmascript/src/utils.rs index a8ccc105be5ab..2e83eb5a654dd 100644 --- a/turbopack/crates/turbopack-ecmascript/src/utils.rs +++ b/turbopack/crates/turbopack-ecmascript/src/utils.rs @@ -114,11 +114,8 @@ where impl std::io::Write for DisplayWriter<'_, '_> { fn write(&mut self, bytes: &[u8]) -> std::result::Result<usize, std::io::Error> { self.f - .write_str( - std::str::from_utf8(bytes) - .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?, - ) - .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?; + .write_str(std::str::from_utf8(bytes).map_err(std::io::Error::other)?) + .map_err(std::io::Error::other)?; Ok(bytes.len()) } diff --git a/turbopack/crates/turbopack-node/src/lib.rs b/turbopack/crates/turbopack-node/src/lib.rs index 672736fca9388..606c9022e2b4e 100644 --- a/turbopack/crates/turbopack-node/src/lib.rs +++ b/turbopack/crates/turbopack-node/src/lib.rs #![feature(arbitrary_self_types)] #![feature(arbitrary_self_types_pointers)] -#![feature(extract_if)] use std::{iter::once, thread::available_parallelism}; diff --git a/turbopack/crates/turbopack-trace-server/src/store.rs b/turbopack/crates/turbopack-trace-server/src/store.rs index e520e187aaa0c..b37892907b3c2 100644 --- a/turbopack/crates/turbopack-trace-server/src/store.rs +++ b/turbopack/crates/turbopack-trace-server/src/store.rs use std::{ cmp::{max, min}, env, - mem::replace, num::NonZeroUsize, sync::{atomic::AtomicU64, OnceLock}, }; @@ -266,7 +265,7 @@ impl Store { outdated_spans.insert(span_index); let span = &mut self.spans[span_index.get()]; - let old_parent = replace(&mut span.parent, Some(parent)); + let old_parent = span.parent.replace(parent); let old_parent = if let Some(parent) = old_parent { outdated_spans.insert(parent); &mut self.spans[parent.get()]
[ "+#[allow(clippy::large_enum_variant)] // This is a turbo-tasks value" ]
[ 105 ]
{ "additions": 28, "author": "wbinnssmith", "deletions": 43, "html_url": "https://github.com/vercel/next.js/pull/78039", "issue_id": 78039, "merged_at": "2025-04-10T21:51:23Z", "omission_probability": 0.1, "pr_number": 78039, "repo": "vercel/next.js", "title": "Update Rust toolchain to nightly-2025-04-10", "total_changes": 71 }
321
diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index 9d85556ab49c0..f7cbf822fff76 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -3301,6 +3301,16 @@ export default async function build( orig, path.join(distDir, 'server', updatedRelativeDest) ) + + // since the app router not found is prioritized over pages router, + // we have to ensure the app router entries are available for all locales + if (i18n) { + for (const locale of i18n.locales) { + const curPath = `/${locale}/404` + pagesManifest[curPath] = updatedRelativeDest + } + } + pagesManifest['/404'] = updatedRelativeDest } }) diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx new file mode 100644 index 0000000000000..84e51b866c775 --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx @@ -0,0 +1,44 @@ +import { notFound } from 'next/navigation' + +export async function generateStaticParams() { + return [] +} + +async function validateSlug(slug: string[]) { + try { + const isValidPath = + slug.length === 1 && (slug[0] === 'about' || slug[0] === 'contact') + + if (!isValidPath) { + return false + } + + return true + } catch (error) { + throw error + } +} + +export default async function CatchAll({ + params, +}: { + params: Promise<{ slug: string[] }> +}) { + const { slug } = await params + const slugArray = Array.isArray(slug) ? slug : [slug] + + // Validate the slug + const isValid = await validateSlug(slugArray) + + // If not valid, show 404 + if (!isValid) { + notFound() + } + + return ( + <div> + <h1>Catch All</h1> + <p>This is a catch all page added to the APP router</p> + </div> + ) +} diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/app/layout.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/app/layout.tsx new file mode 100644 index 0000000000000..a14e64fcd5e33 --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/app/layout.tsx @@ -0,0 +1,16 @@ +export const metadata = { + title: 'Next.js', + description: 'Generated by Next.js', +} + +export default function RootLayout({ + children, +}: { + children: React.ReactNode +}) { + return ( + <html lang="en"> + <body>{children}</body> + </html> + ) +} diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/app/not-found.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/app/not-found.tsx new file mode 100644 index 0000000000000..9e2f20f4cca7c --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/app/not-found.tsx @@ -0,0 +1,10 @@ +import React from 'react' + +const NotFound = () => ( + <div> + <h1>APP ROUTER - 404 PAGE</h1> + <p>This page is using the APP ROUTER</p> + </div> +) + +export default NotFound diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/next.config.js b/test/e2e/app-dir/not-found-with-pages-i18n/next.config.js new file mode 100644 index 0000000000000..ee7663cef2d2b --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/next.config.js @@ -0,0 +1,12 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + i18n: { + locales: ['en-GB', 'en'], + defaultLocale: 'en', + localeDetection: false, + }, +} + +module.exports = nextConfig diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts b/test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts new file mode 100644 index 0000000000000..5b6a635bd3d6b --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts @@ -0,0 +1,31 @@ +import { nextTestSetup } from 'e2e-utils' + +describe('not-found-with-pages', () => { + const { next, isNextStart } = nextTestSetup({ + files: __dirname, + }) + + if (isNextStart) { + it('should write all locales to the pages manifest', async () => { + const pagesManifest = JSON.parse( + await next.readFile('.next/server/pages-manifest.json') + ) + + expect(pagesManifest['/404']).toBe('pages/404.html') + expect(pagesManifest['/en/404']).toBe('pages/404.html') + expect(pagesManifest['/en-GB/404']).toBe('pages/404.html') + }) + } + + it('should prefer the app router 404 over the pages router 404 when both are present', async () => { + const browser = await next.browser('/app-dir/foo') + expect(await browser.elementByCss('h1').text()).toBe( + 'APP ROUTER - 404 PAGE' + ) + + await browser.loadPage(next.url) + expect(await browser.elementByCss('h1').text()).toBe( + 'APP ROUTER - 404 PAGE' + ) + }) +}) diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/pages/404.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/pages/404.tsx new file mode 100644 index 0000000000000..be5a6a9368ef2 --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/pages/404.tsx @@ -0,0 +1,24 @@ +import React from 'react' +import { GetStaticProps } from 'next' + +interface NotFoundProps { + message: string +} + +const NotFound = ({ message }: NotFoundProps) => ( + <div> + <h1>PAGES ROUTER - 404 PAGE</h1> + <p>This page is using the PAGES ROUTER</p> + <p>{message}</p> + </div> +) + +export const getStaticProps: GetStaticProps<NotFoundProps> = async () => { + return { + props: { + message: 'Custom message fetched at build time', + }, + } +} + +export default NotFound diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/pages/[[...slug]].tsx b/test/e2e/app-dir/not-found-with-pages-i18n/pages/[[...slug]].tsx new file mode 100644 index 0000000000000..2da5fd5f318d5 --- /dev/null +++ b/test/e2e/app-dir/not-found-with-pages-i18n/pages/[[...slug]].tsx @@ -0,0 +1,39 @@ +import React from 'react' + +export const getStaticProps = ({ params }: { params: { slug: string[] } }) => { + try { + const slugArray = Array.isArray(params.slug) ? params.slug : [params.slug] + + const isValidPath = + slugArray.length === 1 && + (slugArray[0] === 'about' || slugArray[0] === 'contact') + + if (!isValidPath) { + return { + notFound: true, + } + } + + return { + props: { + slug: params.slug, + }, + } + } catch (error) { + throw error + } +} + +export const getStaticPaths = async () => ({ + paths: [], + fallback: 'blocking', +}) + +const CatchAll = () => ( + <div> + <h1>Catch All</h1> + <p>This is a catch all page added to the pages router</p> + </div> +) + +export default CatchAll
diff --git a/packages/next/src/build/index.ts b/packages/next/src/build/index.ts index 9d85556ab49c0..f7cbf822fff76 100644 --- a/packages/next/src/build/index.ts +++ b/packages/next/src/build/index.ts @@ -3301,6 +3301,16 @@ export default async function build( orig, path.join(distDir, 'server', updatedRelativeDest) ) + // since the app router not found is prioritized over pages router, + // we have to ensure the app router entries are available for all locales + if (i18n) { + const curPath = `/${locale}/404` + pagesManifest[curPath] = updatedRelativeDest + } + } pagesManifest['/404'] = updatedRelativeDest } }) diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx index 0000000000000..84e51b866c775 +++ b/test/e2e/app-dir/not-found-with-pages-i18n/app/app-dir/[[...slug]]/page.tsx @@ -0,0 +1,44 @@ +import { notFound } from 'next/navigation' +export async function generateStaticParams() { + return [] +async function validateSlug(slug: string[]) { + slug.length === 1 && (slug[0] === 'about' || slug[0] === 'contact') + return false + return true +export default async function CatchAll({ + params: Promise<{ slug: string[] }> + const { slug } = await params + const slugArray = Array.isArray(slug) ? slug : [slug] + // Validate the slug + const isValid = await validateSlug(slugArray) + if (!isValid) { + notFound() + <div> + <h1>Catch All</h1> + <p>This is a catch all page added to the APP router</p> + </div> diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/app/layout.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/app/layout.tsx index 0000000000000..a14e64fcd5e33 +++ b/test/e2e/app-dir/not-found-with-pages-i18n/app/layout.tsx @@ -0,0 +1,16 @@ +export const metadata = { + title: 'Next.js', + description: 'Generated by Next.js', +export default function RootLayout({ + children, + children: React.ReactNode + <html lang="en"> + <body>{children}</body> + </html> diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/app/not-found.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/app/not-found.tsx index 0000000000000..9e2f20f4cca7c +++ b/test/e2e/app-dir/not-found-with-pages-i18n/app/not-found.tsx @@ -0,0 +1,10 @@ +const NotFound = () => ( + <h1>APP ROUTER - 404 PAGE</h1> + <p>This page is using the APP ROUTER</p> diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/next.config.js b/test/e2e/app-dir/not-found-with-pages-i18n/next.config.js index 0000000000000..ee7663cef2d2b +++ b/test/e2e/app-dir/not-found-with-pages-i18n/next.config.js @@ -0,0 +1,12 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + i18n: { + locales: ['en-GB', 'en'], + defaultLocale: 'en', + localeDetection: false, + }, +module.exports = nextConfig diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts b/test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts index 0000000000000..5b6a635bd3d6b +++ b/test/e2e/app-dir/not-found-with-pages-i18n/not-found-with-pages.test.ts @@ -0,0 +1,31 @@ +import { nextTestSetup } from 'e2e-utils' +describe('not-found-with-pages', () => { + const { next, isNextStart } = nextTestSetup({ + files: __dirname, + if (isNextStart) { + it('should write all locales to the pages manifest', async () => { + await next.readFile('.next/server/pages-manifest.json') + ) + expect(pagesManifest['/404']).toBe('pages/404.html') + expect(pagesManifest['/en-GB/404']).toBe('pages/404.html') + }) + it('should prefer the app router 404 over the pages router 404 when both are present', async () => { + const browser = await next.browser('/app-dir/foo') + await browser.loadPage(next.url) diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/pages/404.tsx b/test/e2e/app-dir/not-found-with-pages-i18n/pages/404.tsx index 0000000000000..be5a6a9368ef2 +++ b/test/e2e/app-dir/not-found-with-pages-i18n/pages/404.tsx @@ -0,0 +1,24 @@ +import { GetStaticProps } from 'next' +interface NotFoundProps { + message: string +const NotFound = ({ message }: NotFoundProps) => ( + <h1>PAGES ROUTER - 404 PAGE</h1> + <p>This page is using the PAGES ROUTER</p> + return { + props: { + message: 'Custom message fetched at build time', + }, diff --git a/test/e2e/app-dir/not-found-with-pages-i18n/pages/[[...slug]].tsx b/test/e2e/app-dir/not-found-with-pages-i18n/pages/[[...slug]].tsx index 0000000000000..2da5fd5f318d5 +++ b/test/e2e/app-dir/not-found-with-pages-i18n/pages/[[...slug]].tsx @@ -0,0 +1,39 @@ +export const getStaticProps = ({ params }: { params: { slug: string[] } }) => { + slugArray.length === 1 && + (slugArray[0] === 'about' || slugArray[0] === 'contact') + return { + notFound: true, + } + return { + props: { + slug: params.slug, + }, +export const getStaticPaths = async () => ({ + paths: [], + fallback: 'blocking', +const CatchAll = () => ( + <h1>Catch All</h1> + <p>This is a catch all page added to the pages router</p> +export default CatchAll
[ "+ for (const locale of i18n.locales) {", "+ params,", "+ // If not valid, show 404", "+ const pagesManifest = JSON.parse(", "+ expect(pagesManifest['/en/404']).toBe('pages/404.html')", "+ <p>{message}</p>", "+export const getStaticProps: GetStaticProps<NotFoundProps> = async () => {", "+ const slugArray = Array.isArray(params.slug) ? params.slug : [params.slug]" ]
[ 12, 49, 59, 142, 147, 181, 185, 204 ]
{ "additions": 186, "author": "ztanner", "deletions": 0, "html_url": "https://github.com/vercel/next.js/pull/77905", "issue_id": 77905, "merged_at": "2025-04-10T22:44:59Z", "omission_probability": 0.1, "pr_number": 77905, "repo": "vercel/next.js", "title": "fix: ensure app router not found works when deployed with pages i18n config", "total_changes": 186 }
322
diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index 463d270953f4f..6db12ca87290e 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -390,7 +390,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => prerenderEarlyExit: z.boolean().optional(), proxyTimeout: z.number().gte(0).optional(), routerBFCache: z.boolean().optional(), - removeUnhandledRejectionListeners: z.boolean().optional(), + removeUncaughtErrorAndRejectionListeners: z.boolean().optional(), scrollRestoration: z.boolean().optional(), sri: z .object({ diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index b975d18039f3c..fc8c63442106b 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -510,14 +510,14 @@ export interface ExperimentalConfig { routerBFCache?: boolean /** - * Uninstalls all "unhandledRejection" listeners from the global process so - * that we can override the behavior, which in some runtimes is to exit the - * process on an unhandled rejection. + * Uninstalls all "unhandledRejection" and "uncaughtException" listeners from + * the global process so that we can override the behavior, which in some + * runtimes is to exit the process. * * This is experimental until we've considered the impact in various * deployment environments. */ - removeUnhandledRejectionListeners?: boolean + removeUncaughtErrorAndRejectionListeners?: boolean serverActions?: { /** @@ -1312,7 +1312,7 @@ export const defaultConfig: NextConfig = { useEarlyImport: false, viewTransition: false, routerBFCache: false, - removeUnhandledRejectionListeners: false, + removeUncaughtErrorAndRejectionListeners: false, staleTimes: { dynamic: 0, static: 300, diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index a66633b09efee..a08e2db8b9eba 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -161,7 +161,7 @@ function getMiddlewareMatcher( } function installProcessErrorHandlers( - shouldRemoveUnhandledRejectionListeners: boolean + shouldRemoveUncaughtErrorAndRejectionListeners: boolean ) { // The conventional wisdom of Node.js and other runtimes is to treat // unhandled errors as fatal and exit the process. @@ -199,11 +199,12 @@ function installProcessErrorHandlers( // So, we're going to intentionally override the default error handling // behavior of the outer JS runtime to be more forgiving - // Remove any existing "unhandledRejection" handlers. This is gated behind - // an experimental flag until we've considered the impact in various - // deployment environments. It's possible this may always need to + // Remove any existing "unhandledRejection" and "uncaughtException" handlers. + // This is gated behind an experimental flag until we've considered the impact + // in various deployment environments. It's possible this may always need to // be configurable. - if (shouldRemoveUnhandledRejectionListeners) { + if (shouldRemoveUncaughtErrorAndRejectionListeners) { + process.removeAllListeners('uncaughtException') process.removeAllListeners('unhandledRejection') } @@ -370,10 +371,10 @@ export default class NextNodeServer extends BaseServer< populateStaticEnv(this.nextConfig) } - const shouldRemoveUnhandledRejectionListeners = Boolean( - options.conf.experimental?.removeUnhandledRejectionListeners + const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean( + options.conf.experimental?.removeUncaughtErrorAndRejectionListeners ) - installProcessErrorHandlers(shouldRemoveUnhandledRejectionListeners) + installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners) } public async unstable_preloadEntries(): Promise<void> {
diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index 463d270953f4f..6db12ca87290e 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -390,7 +390,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => prerenderEarlyExit: z.boolean().optional(), proxyTimeout: z.number().gte(0).optional(), routerBFCache: z.boolean().optional(), - removeUnhandledRejectionListeners: z.boolean().optional(), + removeUncaughtErrorAndRejectionListeners: z.boolean().optional(), scrollRestoration: z.boolean().optional(), sri: z .object({ diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index b975d18039f3c..fc8c63442106b 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -510,14 +510,14 @@ export interface ExperimentalConfig { routerBFCache?: boolean /** - * Uninstalls all "unhandledRejection" listeners from the global process so - * that we can override the behavior, which in some runtimes is to exit the - * process on an unhandled rejection. + * Uninstalls all "unhandledRejection" and "uncaughtException" listeners from + * the global process so that we can override the behavior, which in some + * runtimes is to exit the process. * * This is experimental until we've considered the impact in various * deployment environments. */ - removeUnhandledRejectionListeners?: boolean + removeUncaughtErrorAndRejectionListeners?: boolean serverActions?: { /** @@ -1312,7 +1312,7 @@ export const defaultConfig: NextConfig = { useEarlyImport: false, viewTransition: false, routerBFCache: false, + removeUncaughtErrorAndRejectionListeners: false, staleTimes: { dynamic: 0, static: 300, diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index a66633b09efee..a08e2db8b9eba 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -161,7 +161,7 @@ function getMiddlewareMatcher( } function installProcessErrorHandlers( - shouldRemoveUnhandledRejectionListeners: boolean + shouldRemoveUncaughtErrorAndRejectionListeners: boolean ) { // The conventional wisdom of Node.js and other runtimes is to treat // unhandled errors as fatal and exit the process. @@ -199,11 +199,12 @@ function installProcessErrorHandlers( // So, we're going to intentionally override the default error handling // behavior of the outer JS runtime to be more forgiving - // Remove any existing "unhandledRejection" handlers. This is gated behind - // deployment environments. It's possible this may always need to + // Remove any existing "unhandledRejection" and "uncaughtException" handlers. + // This is gated behind an experimental flag until we've considered the impact + // in various deployment environments. It's possible this may always need to // be configurable. - if (shouldRemoveUnhandledRejectionListeners) { + if (shouldRemoveUncaughtErrorAndRejectionListeners) { + process.removeAllListeners('uncaughtException') process.removeAllListeners('unhandledRejection') @@ -370,10 +371,10 @@ export default class NextNodeServer extends BaseServer< populateStaticEnv(this.nextConfig) } - const shouldRemoveUnhandledRejectionListeners = Boolean( - options.conf.experimental?.removeUnhandledRejectionListeners + const shouldRemoveUncaughtErrorAndRejectionListeners = Boolean( + options.conf.experimental?.removeUncaughtErrorAndRejectionListeners ) - installProcessErrorHandlers(shouldRemoveUnhandledRejectionListeners) + installProcessErrorHandlers(shouldRemoveUncaughtErrorAndRejectionListeners) public async unstable_preloadEntries(): Promise<void> {
[ "- removeUnhandledRejectionListeners: false,", "- // an experimental flag until we've considered the impact in various" ]
[ 40, 63 ]
{ "additions": 15, "author": "acdlite", "deletions": 14, "html_url": "https://github.com/vercel/next.js/pull/78042", "issue_id": 78042, "merged_at": "2025-04-10T23:09:38Z", "omission_probability": 0.1, "pr_number": 78042, "repo": "vercel/next.js", "title": "Uninstall existing uncaughtException listeners to prevent the process from crashing", "total_changes": 29 }
323
diff --git a/test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts b/test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts new file mode 100644 index 0000000000000..4826f9ebc34e0 --- /dev/null +++ b/test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts @@ -0,0 +1,76 @@ +import { nextTestSetup } from 'e2e-utils' + +describe('react@experimental', () => { + const { next } = nextTestSetup({ + files: __dirname, + overrideFiles: { + 'next.config.js': ` + module.exports = { + experimental: { + taint: true, + } + } + `, + }, + }) + + it('should opt into the react@experimental when enabling $flag', async () => { + const resPages$ = await next.render$('/app-react') + const [ + ssrReact, + ssrReactDOM, + ssrClientReact, + ssrClientReactDOM, + ssrClientReactDOMServer, + ] = [ + resPages$('#react').text(), + resPages$('#react-dom').text(), + resPages$('#client-react').text(), + resPages$('#client-react-dom').text(), + resPages$('#client-react-dom-server').text(), + ] + expect({ + ssrReact, + ssrReactDOM, + ssrClientReact, + ssrClientReactDOM, + ssrClientReactDOMServer, + }).toEqual({ + ssrReact: expect.stringMatching('-experimental-'), + ssrReactDOM: expect.stringMatching('-experimental-'), + ssrClientReact: expect.stringMatching('-experimental-'), + ssrClientReactDOM: expect.stringMatching('-experimental-'), + ssrClientReactDOMServer: expect.stringMatching('-experimental-'), + }) + + const browser = await next.browser('/app-react') + const [ + browserReact, + browserReactDOM, + browserClientReact, + browserClientReactDOM, + browserClientReactDOMServer, + ] = await browser.eval(` + [ + document.querySelector('#react').innerText, + document.querySelector('#react-dom').innerText, + document.querySelector('#client-react').innerText, + document.querySelector('#client-react-dom').innerText, + document.querySelector('#client-react-dom-server').innerText, + ] + `) + expect({ + browserReact, + browserReactDOM, + browserClientReact, + browserClientReactDOM, + browserClientReactDOMServer, + }).toEqual({ + browserReact: expect.stringMatching('-experimental-'), + browserReactDOM: expect.stringMatching('-experimental-'), + browserClientReact: expect.stringMatching('-experimental-'), + browserClientReactDOM: expect.stringMatching('-experimental-'), + browserClientReactDOMServer: expect.stringMatching('-experimental-'), + }) + }) +}) diff --git a/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts b/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts index 2df3252119e5c..46a52b0d180b3 100644 --- a/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts +++ b/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts @@ -621,84 +621,4 @@ describe('app dir - rsc basics', () => { await Promise.all(promises) }) } - - describe('react@experimental', () => { - it.each([{ flag: 'ppr' }, { flag: 'taint' }])( - 'should opt into the react@experimental when enabling $flag', - async ({ flag }) => { - await next.stop() - await next.patchFile( - 'next.config.js', - ` - module.exports = { - experimental: { - ${flag}: true - } - } - `, - async () => { - await next.start() - const resPages$ = await next.render$('/app-react') - const [ - ssrReact, - ssrReactDOM, - ssrClientReact, - ssrClientReactDOM, - ssrClientReactDOMServer, - ] = [ - resPages$('#react').text(), - resPages$('#react-dom').text(), - resPages$('#client-react').text(), - resPages$('#client-react-dom').text(), - resPages$('#client-react-dom-server').text(), - ] - expect({ - ssrReact, - ssrReactDOM, - ssrClientReact, - ssrClientReactDOM, - ssrClientReactDOMServer, - }).toEqual({ - ssrReact: expect.stringMatching('-experimental-'), - ssrReactDOM: expect.stringMatching('-experimental-'), - ssrClientReact: expect.stringMatching('-experimental-'), - ssrClientReactDOM: expect.stringMatching('-experimental-'), - ssrClientReactDOMServer: expect.stringMatching('-experimental-'), - }) - - const browser = await next.browser('/app-react') - const [ - browserReact, - browserReactDOM, - browserClientReact, - browserClientReactDOM, - browserClientReactDOMServer, - ] = await browser.eval(` - [ - document.querySelector('#react').innerText, - document.querySelector('#react-dom').innerText, - document.querySelector('#client-react').innerText, - document.querySelector('#client-react-dom').innerText, - document.querySelector('#client-react-dom-server').innerText, - ] - `) - expect({ - browserReact, - browserReactDOM, - browserClientReact, - browserClientReactDOM, - browserClientReactDOMServer, - }).toEqual({ - browserReact: expect.stringMatching('-experimental-'), - browserReactDOM: expect.stringMatching('-experimental-'), - browserClientReact: expect.stringMatching('-experimental-'), - browserClientReactDOM: expect.stringMatching('-experimental-'), - browserClientReactDOMServer: - expect.stringMatching('-experimental-'), - }) - } - ) - } - ) - }) })
diff --git a/test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts b/test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts new file mode 100644 index 0000000000000..4826f9ebc34e0 --- /dev/null +++ b/test/e2e/app-dir/rsc-basic/rsc-basic-react-experimental.test.ts @@ -0,0 +1,76 @@ +import { nextTestSetup } from 'e2e-utils' + const { next } = nextTestSetup({ + files: __dirname, + overrideFiles: { + module.exports = { + experimental: { + taint: true, + } + `, + }, + it('should opt into the react@experimental when enabling $flag', async () => { + const resPages$ = await next.render$('/app-react') + resPages$('#react').text(), + resPages$('#react-dom').text(), + resPages$('#client-react-dom').text(), + resPages$('#client-react-dom-server').text(), + ] + ssrReact: expect.stringMatching('-experimental-'), + ssrReactDOM: expect.stringMatching('-experimental-'), + ssrClientReact: expect.stringMatching('-experimental-'), + ssrClientReactDOM: expect.stringMatching('-experimental-'), + ssrClientReactDOMServer: expect.stringMatching('-experimental-'), + const browser = await next.browser('/app-react') + ] = await browser.eval(` + [ + document.querySelector('#react').innerText, + document.querySelector('#react-dom').innerText, + document.querySelector('#client-react').innerText, + document.querySelector('#client-react-dom').innerText, + document.querySelector('#client-react-dom-server').innerText, + ] + `) + browserReact: expect.stringMatching('-experimental-'), + browserReactDOM: expect.stringMatching('-experimental-'), + browserClientReact: expect.stringMatching('-experimental-'), + browserClientReactDOM: expect.stringMatching('-experimental-'), + browserClientReactDOMServer: expect.stringMatching('-experimental-'), +}) diff --git a/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts b/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts index 2df3252119e5c..46a52b0d180b3 100644 --- a/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts +++ b/test/e2e/app-dir/rsc-basic/rsc-basic.test.ts @@ -621,84 +621,4 @@ describe('app dir - rsc basics', () => { await Promise.all(promises) }) } - describe('react@experimental', () => { - it.each([{ flag: 'ppr' }, { flag: 'taint' }])( - async ({ flag }) => { - await next.stop() - await next.patchFile( - 'next.config.js', - ` - module.exports = { - experimental: { - ${flag}: true - } - `, - await next.start() - const resPages$ = await next.render$('/app-react') - ] = [ - resPages$('#react').text(), - resPages$('#react-dom').text(), - resPages$('#client-react-dom').text(), - resPages$('#client-react-dom-server').text(), - ] - ssrReact: expect.stringMatching('-experimental-'), - ssrReactDOM: expect.stringMatching('-experimental-'), - ssrClientReact: expect.stringMatching('-experimental-'), - ssrClientReactDOM: expect.stringMatching('-experimental-'), - ssrClientReactDOMServer: expect.stringMatching('-experimental-'), - const browser = await next.browser('/app-react') - ] = await browser.eval(` - document.querySelector('#react').innerText, - document.querySelector('#react-dom').innerText, - document.querySelector('#client-react').innerText, - document.querySelector('#client-react-dom').innerText, - document.querySelector('#client-react-dom-server').innerText, - ] - `) - browserReact: expect.stringMatching('-experimental-'), - browserClientReact: expect.stringMatching('-experimental-'), - browserClientReactDOM: expect.stringMatching('-experimental-'), - browserClientReactDOMServer: - expect.stringMatching('-experimental-'), - ) - } - ) - }) })
[ "+describe('react@experimental', () => {", "+ 'next.config.js': `", "+ }", "+ ] = [", "+ resPages$('#client-react').text(),", "- 'should opt into the react@experimental when enabling $flag',", "- async () => {", "- resPages$('#client-react').text(),", "- [", "- browserReactDOM: expect.stringMatching('-experimental-')," ]
[ 8, 12, 17, 30, 33, 93, 105, 117, 143, 159 ]
{ "additions": 76, "author": "huozhi", "deletions": 80, "html_url": "https://github.com/vercel/next.js/pull/78038", "issue_id": 78038, "merged_at": "2025-04-10T23:36:20Z", "omission_probability": 0.1, "pr_number": 78038, "repo": "vercel/next.js", "title": "[test] separate rsc-basic tests", "total_changes": 156 }
324
diff --git a/docs/01-app/03-building-your-application/07-configuring/index.mdx b/docs/01-app/03-building-your-application/07-configuring/index.mdx deleted file mode 100644 index 1cbae5fdfb266..0000000000000 --- a/docs/01-app/03-building-your-application/07-configuring/index.mdx +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Configuring -description: Learn how to configure your Next.js application. ---- - -{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} - -Next.js allows you to customize your project to meet specific requirements. This includes integrations with TypeScript, ESlint, and more, as well as internal configuration options such as Absolute Imports and Environment Variables. diff --git a/docs/01-app/03-building-your-application/index.mdx b/docs/01-app/03-building-your-application/index.mdx index e71ad3eeb3c0b..75945ccf1f360 100644 --- a/docs/01-app/03-building-your-application/index.mdx +++ b/docs/01-app/03-building-your-application/index.mdx @@ -11,7 +11,7 @@ The sections and pages are organized sequentially, from basic to advanced, so yo <AppOnly> -If you're new to Next.js, we recommend starting with the [Routing](/docs/app/building-your-application/routing), [Rendering](/docs/app/building-your-application/rendering), [Data Fetching](/docs/app/building-your-application/data-fetching) and [Styling](/docs/app/building-your-application/styling) sections, as they introduce the fundamental Next.js and web concepts to help you get started. Then, you can dive deeper into the other sections such as [Optimizing](/docs/app/building-your-application/optimizing) and [Configuring](/docs/app/building-your-application/configuring). Finally, once you're ready, checkout the [Deploying](/docs/app/getting-started/deploying) and [Upgrading](/docs/app/guides/upgrading) sections. +If you're new to Next.js, we recommend starting with the [Routing](/docs/app/building-your-application/routing), [Rendering](/docs/app/building-your-application/rendering), [Data Fetching](/docs/app/building-your-application/data-fetching) and [Styling](/docs/app/building-your-application/styling) sections, as they introduce the fundamental Next.js and web concepts to help you get started. Then, you can dive deeper into the other sections such as [Optimizing](/docs/app/building-your-application/optimizing). Finally, once you're ready, checkout the [Deploying](/docs/app/getting-started/deploying) and [Upgrading](/docs/app/guides/upgrading) sections. </AppOnly> diff --git a/docs/02-pages/03-building-your-application/06-configuring/index.mdx b/docs/02-pages/03-building-your-application/06-configuring/index.mdx index c903a16a33233..326ea00a21513 100644 --- a/docs/02-pages/03-building-your-application/06-configuring/index.mdx +++ b/docs/02-pages/03-building-your-application/06-configuring/index.mdx @@ -1,7 +1,6 @@ --- title: Configuring description: Learn how to configure your Next.js application. -source: app/building-your-application/configuring --- -{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} +Next.js allows you to customize your project to meet specific requirements. This includes integrations with TypeScript, ESlint, and more, as well as internal configuration options such as Absolute Imports and Environment Variables.
diff --git a/docs/01-app/03-building-your-application/07-configuring/index.mdx b/docs/01-app/03-building-your-application/07-configuring/index.mdx deleted file mode 100644 index 1cbae5fdfb266..0000000000000 --- a/docs/01-app/03-building-your-application/07-configuring/index.mdx +++ /dev/null @@ -1,8 +0,0 @@ -title: Configuring -description: Learn how to configure your Next.js application. -{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -Next.js allows you to customize your project to meet specific requirements. This includes integrations with TypeScript, ESlint, and more, as well as internal configuration options such as Absolute Imports and Environment Variables. diff --git a/docs/01-app/03-building-your-application/index.mdx b/docs/01-app/03-building-your-application/index.mdx index e71ad3eeb3c0b..75945ccf1f360 100644 --- a/docs/01-app/03-building-your-application/index.mdx +++ b/docs/01-app/03-building-your-application/index.mdx @@ -11,7 +11,7 @@ The sections and pages are organized sequentially, from basic to advanced, so yo <AppOnly> -If you're new to Next.js, we recommend starting with the [Routing](/docs/app/building-your-application/routing), [Rendering](/docs/app/building-your-application/rendering), [Data Fetching](/docs/app/building-your-application/data-fetching) and [Styling](/docs/app/building-your-application/styling) sections, as they introduce the fundamental Next.js and web concepts to help you get started. Then, you can dive deeper into the other sections such as [Optimizing](/docs/app/building-your-application/optimizing) and [Configuring](/docs/app/building-your-application/configuring). Finally, once you're ready, checkout the [Deploying](/docs/app/getting-started/deploying) and [Upgrading](/docs/app/guides/upgrading) sections. +If you're new to Next.js, we recommend starting with the [Routing](/docs/app/building-your-application/routing), [Rendering](/docs/app/building-your-application/rendering), [Data Fetching](/docs/app/building-your-application/data-fetching) and [Styling](/docs/app/building-your-application/styling) sections, as they introduce the fundamental Next.js and web concepts to help you get started. Then, you can dive deeper into the other sections such as [Optimizing](/docs/app/building-your-application/optimizing). Finally, once you're ready, checkout the [Deploying](/docs/app/getting-started/deploying) and [Upgrading](/docs/app/guides/upgrading) sections. </AppOnly> diff --git a/docs/02-pages/03-building-your-application/06-configuring/index.mdx b/docs/02-pages/03-building-your-application/06-configuring/index.mdx index c903a16a33233..326ea00a21513 100644 --- a/docs/02-pages/03-building-your-application/06-configuring/index.mdx +++ b/docs/02-pages/03-building-your-application/06-configuring/index.mdx @@ -1,7 +1,6 @@ title: Configuring description: Learn how to configure your Next.js application. -source: app/building-your-application/configuring -{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} +Next.js allows you to customize your project to meet specific requirements. This includes integrations with TypeScript, ESlint, and more, as well as internal configuration options such as Absolute Imports and Environment Variables.
[]
[]
{ "additions": 2, "author": "delbaoliveira", "deletions": 9, "html_url": "https://github.com/vercel/next.js/pull/78521", "issue_id": 78521, "merged_at": "2025-04-24T19:08:34Z", "omission_probability": 0.1, "pr_number": 78521, "repo": "vercel/next.js", "title": "Docs IA 2.0: Delete config page in app docs", "total_changes": 11 }
325
diff --git a/docs/01-app/01-getting-started/02-project-structure.mdx b/docs/01-app/01-getting-started/02-project-structure.mdx index 085745f2137d4..bf1931022b151 100644 --- a/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/docs/01-app/01-getting-started/02-project-structure.mdx @@ -31,22 +31,22 @@ Top-level folders are used to organize your application's code and static assets Top-level files are used to configure your application, manage dependencies, run middleware, integrate monitoring tools, and define environment variables. -| | | -| -------------------------------------------------------------------------------------- | --------------------------------------- | -| **Next.js** | | -| [`next.config.js`](/docs/app/api-reference/config/next-config-js) | Configuration file for Next.js | -| [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts | -| [`instrumentation.ts`](/docs/app/building-your-application/optimizing/instrumentation) | OpenTelemetry and Instrumentation file | -| [`middleware.ts`](/docs/app/building-your-application/routing/middleware) | Next.js request middleware | -| [`.env`](/docs/app/guides/environment-variables) | Environment variables | -| [`.env.local`](/docs/app/guides/environment-variables) | Local environment variables | -| [`.env.production`](/docs/app/guides/environment-variables) | Production environment variables | -| [`.env.development`](/docs/app/guides/environment-variables) | Development environment variables | -| [`.eslintrc.json`](/docs/app/api-reference/config/eslint) | Configuration file for ESLint | -| `.gitignore` | Git files and folders to ignore | -| `next-env.d.ts` | TypeScript declaration file for Next.js | -| `tsconfig.json` | Configuration file for TypeScript | -| `jsconfig.json` | Configuration file for JavaScript | +| | | +| ---------------------------------------------------------------------------- | --------------------------------------- | +| **Next.js** | | +| [`next.config.js`](/docs/app/api-reference/config/next-config-js) | Configuration file for Next.js | +| [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts | +| [`instrumentation.ts`](/docs/app/guides/instrumentation) | OpenTelemetry and Instrumentation file | +| [`middleware.ts`](/docs/app/building-your-application/routing/middleware) | Next.js request middleware | +| [`.env`](/docs/app/guides/environment-variables) | Environment variables | +| [`.env.local`](/docs/app/guides/environment-variables) | Local environment variables | +| [`.env.production`](/docs/app/guides/environment-variables) | Production environment variables | +| [`.env.development`](/docs/app/guides/environment-variables) | Development environment variables | +| [`.eslintrc.json`](/docs/app/api-reference/config/eslint) | Configuration file for ESLint | +| `.gitignore` | Git files and folders to ignore | +| `next-env.d.ts` | TypeScript declaration file for Next.js | +| `tsconfig.json` | Configuration file for TypeScript | +| `jsconfig.json` | Configuration file for JavaScript | <AppOnly> diff --git a/docs/01-app/03-building-your-application/06-optimizing/08-analytics.mdx b/docs/01-app/02-guides/analytics.mdx similarity index 93% rename from docs/01-app/03-building-your-application/06-optimizing/08-analytics.mdx rename to docs/01-app/02-guides/analytics.mdx index 49ff948349a07..0cdf80fe9196b 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/08-analytics.mdx +++ b/docs/01-app/02-guides/analytics.mdx @@ -1,11 +1,12 @@ --- -title: Analytics +title: How to add analytics to your Next.js application +nav_title: Analytics description: Measure and track page performance using Next.js Speed Insights --- {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -Next.js has built-in support for measuring and reporting performance metrics. You can either use the `useReportWebVitals` hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) to automatically collect and visualize metrics for you. +Next.js has built-in support for measuring and reporting performance metrics. You can either use the [`useReportWebVitals`](/docs/app/api-reference/functions/use-report-web-vitals) hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) to automatically collect and visualize metrics for you. ## Client Instrumentation diff --git a/docs/01-app/02-guides/environment-variables.mdx b/docs/01-app/02-guides/environment-variables.mdx index e6bd12e2f1943..6e4489c6adcbe 100644 --- a/docs/01-app/02-guides/environment-variables.mdx +++ b/docs/01-app/02-guides/environment-variables.mdx @@ -227,7 +227,7 @@ This allows you to use a singular Docker image that can be promoted through mult **Good to know:** -- You can run code on server startup using the [`register` function](/docs/app/building-your-application/optimizing/instrumentation). +- You can run code on server startup using the [`register` function](/docs/app/guides/instrumentation). - We do not recommend using the [`runtimeConfig`](/docs/pages/api-reference/config/next-config-js/runtime-configuration) option, as this does not work with the standalone output mode. Instead, we recommend [incrementally adopting](/docs/app/guides/migrating/app-router-migration) the App Router if you need this feature. ## Environment Variables on Vercel diff --git a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx b/docs/01-app/02-guides/instrumentation.mdx similarity index 98% rename from docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx rename to docs/01-app/02-guides/instrumentation.mdx index d4bc45bffbf2b..86a6b538b0dc8 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx +++ b/docs/01-app/02-guides/instrumentation.mdx @@ -1,5 +1,6 @@ --- -title: Instrumentation +title: How to set up instrumentation +nav_title: Instrumentation description: Learn how to use instrumentation to run code at server startup in your Next.js app related: title: Learn more about Instrumentation diff --git a/docs/01-app/03-building-your-application/06-optimizing/07-lazy-loading.mdx b/docs/01-app/02-guides/lazy-loading.mdx similarity index 99% rename from docs/01-app/03-building-your-application/06-optimizing/07-lazy-loading.mdx rename to docs/01-app/02-guides/lazy-loading.mdx index 9c98f4c15563a..4e0b477a0cc76 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/07-lazy-loading.mdx +++ b/docs/01-app/02-guides/lazy-loading.mdx @@ -1,5 +1,6 @@ --- -title: Lazy Loading +title: How to lazy load Client Components and libraries +nav_title: Lazy Loading description: Lazy load imported libraries and React Components to improve your application's loading performance. --- diff --git a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx b/docs/01-app/02-guides/local-development.mdx similarity index 95% rename from docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx rename to docs/01-app/02-guides/local-development.mdx index 35e2b9a191140..c09a43a7a2ef5 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx +++ b/docs/01-app/02-guides/local-development.mdx @@ -1,5 +1,6 @@ --- -title: Local Development +title: How to optimize your local development environment +nav_title: Development Environment description: Learn how to optimize your local development environment with Next.js. --- @@ -34,7 +35,7 @@ npm run dev --turbopack ### 3. Check your imports -The way you import code can greatly affect compilation and bundling time. Learn more about [optimizing package bundling](/docs/app/building-your-application/optimizing/package-bundling) and explore tools like [Dependency Cruiser](https://github.com/sverweij/dependency-cruiser) or [Madge](https://github.com/pahen/madge). +The way you import code can greatly affect compilation and bundling time. Learn more about [optimizing package bundling](/docs/app/guides/package-bundling) and explore tools like [Dependency Cruiser](https://github.com/sverweij/dependency-cruiser) or [Madge](https://github.com/pahen/madge). ### Icon libraries @@ -122,7 +123,7 @@ Consider if you really need them for local development. You can optionally only If your app is very large, it might need more memory. -[Learn more about optimizing memory usage](/docs/app/building-your-application/optimizing/memory-usage). +[Learn more about optimizing memory usage](/docs/app/guides/memory-usage). ### 7. Server Components and data fetching diff --git a/docs/01-app/03-building-your-application/06-optimizing/13-memory-usage.mdx b/docs/01-app/02-guides/memory-usage.mdx similarity index 96% rename from docs/01-app/03-building-your-application/06-optimizing/13-memory-usage.mdx rename to docs/01-app/02-guides/memory-usage.mdx index 46011e262c17c..d625c3b342155 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/13-memory-usage.mdx +++ b/docs/01-app/02-guides/memory-usage.mdx @@ -1,5 +1,6 @@ --- -title: Memory Usage +title: How to optimize memory usage +nav_title: Memory Usage description: Optimize memory used by your application in development and production. --- @@ -11,7 +12,7 @@ Let's explore some strategies and techniques to optimize memory and address comm Applications with a large amount of dependencies will use more memory. -The [Bundle Analyzer](/docs/app/building-your-application/optimizing/package-bundling) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage. +The [Bundle Analyzer](/docs/app/guides/package-bundling) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage. ## Try `experimental.webpackMemoryOptimizations` diff --git a/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/docs/01-app/02-guides/migrating/from-create-react-app.mdx index e7cf97f761a1c..348bccc1c893f 100644 --- a/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/docs/01-app/02-guides/migrating/from-create-react-app.mdx @@ -43,7 +43,7 @@ Depending on your needs, Next.js allows you to choose your data fetching strateg ### Built-in Optimizations -[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/building-your-application/optimizing/scripts) often have a large impact on an application’s performance. Next.js includes specialized components and APIs that automatically optimize them for you. +[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/guides/scripts) often have a large impact on an application’s performance. Next.js includes specialized components and APIs that automatically optimize them for you. ## Migration Steps @@ -575,7 +575,7 @@ If everything worked, you now have a functioning Next.js application running as - [React Server Components](/docs/app/building-your-application/rendering/server-components) - **Optimize images** with the [`<Image>` component](/docs/app/building-your-application/optimizing/images) - **Optimize fonts** with [`next/font`](/docs/app/building-your-application/optimizing/fonts) -- **Optimize third-party scripts** with the [`<Script>` component](/docs/app/building-your-application/optimizing/scripts) +- **Optimize third-party scripts** with the [`<Script>` component](/docs/app/guides/scripts) - **Enable ESLint** with Next.js recommended rules by running `npx next lint` and configuring it to match your project’s needs > **Note**: Using a static export (`output: 'export'`) [does not currently support](https://github.com/vercel/next.js/issues/54393) the `useParams` hook or other server features. To use all Next.js features, remove `output: 'export'` from your `next.config.ts`. diff --git a/docs/01-app/02-guides/migrating/from-vite.mdx b/docs/01-app/02-guides/migrating/from-vite.mdx index 7cf79078a8f34..d50a4432c63d2 100644 --- a/docs/01-app/02-guides/migrating/from-vite.mdx +++ b/docs/01-app/02-guides/migrating/from-vite.mdx @@ -43,7 +43,7 @@ Depending on your needs, Next.js allows you to choose your data fetching strateg ### Built-in Optimizations -[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/building-your-application/optimizing/scripts) often have significant impact on an application's performance. Next.js comes with built-in components that automatically optimize those for you. +[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/guides/scripts) often have significant impact on an application's performance. Next.js comes with built-in components that automatically optimize those for you. ## Migration Steps @@ -598,5 +598,5 @@ do next: - [React Server Components](/docs/app/building-your-application/rendering/server-components) - [Optimize images with the `<Image>` component](/docs/app/building-your-application/optimizing/images) - [Optimize fonts with `next/font`](/docs/app/building-your-application/optimizing/fonts) -- [Optimize third-party scripts with the `<Script>` component](/docs/app/building-your-application/optimizing/scripts) +- [Optimize third-party scripts with the `<Script>` component](/docs/app/guides/scripts) - [Update your ESLint configuration to support Next.js rules](/docs/app/api-reference/config/eslint) diff --git a/docs/01-app/03-building-your-application/06-optimizing/10-open-telemetry.mdx b/docs/01-app/02-guides/open-telemetry.mdx similarity index 95% rename from docs/01-app/03-building-your-application/06-optimizing/10-open-telemetry.mdx rename to docs/01-app/02-guides/open-telemetry.mdx index 39839f5fc1c2a..b7b61a1afdd7e 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/10-open-telemetry.mdx +++ b/docs/01-app/02-guides/open-telemetry.mdx @@ -1,5 +1,6 @@ --- -title: OpenTelemetry +title: How to set up instrumentation with OpenTelemetry +nav_title: OpenTelemetry description: Learn how to instrument your Next.js app with OpenTelemetry. --- @@ -16,7 +17,11 @@ Read [Official OpenTelemetry docs](https://opentelemetry.io/docs/) for more info This documentation uses terms like _Span_, _Trace_ or _Exporter_ throughout this doc, all of which can be found in [the OpenTelemetry Observability Primer](https://opentelemetry.io/docs/concepts/observability-primer/). Next.js supports OpenTelemetry instrumentation out of the box, which means that we already instrumented Next.js itself. -When you enable OpenTelemetry we will automatically wrap all your code like `getStaticProps` in _spans_ with helpful attributes. + +<PagesOnly> + When you enable OpenTelemetry we will automatically wrap all your code like + `getStaticProps` in _spans_ with helpful attributes. +</PagesOnly> ## Getting Started @@ -33,13 +38,13 @@ npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opente <AppOnly> -Next, create a custom [`instrumentation.ts`](/docs/app/building-your-application/optimizing/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): +Next, create a custom [`instrumentation.ts`](/docs/app/guides/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): </AppOnly> <PagesOnly> -Next, create a custom [`instrumentation.ts`](/docs/pages/building-your-application/optimizing/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): +Next, create a custom [`instrumentation.ts`](/docs/pages/guides/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): </PagesOnly> diff --git a/docs/01-app/03-building-your-application/06-optimizing/06-package-bundling.mdx b/docs/01-app/02-guides/package-bundling.mdx similarity index 98% rename from docs/01-app/03-building-your-application/06-optimizing/06-package-bundling.mdx rename to docs/01-app/02-guides/package-bundling.mdx index 81f50e04b08d7..fe93d18b91a10 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/06-package-bundling.mdx +++ b/docs/01-app/02-guides/package-bundling.mdx @@ -1,5 +1,5 @@ --- -title: Optimizing Package Bundling +title: How to optimize package bundling nav_title: Package Bundling description: Learn how to optimize your application's server and client bundles. related: @@ -12,7 +12,7 @@ Bundling external packages can significantly improve the performance of your app ## Analyzing JavaScript bundles -[`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your application bundles. It generates a visual report of the size of each package and their dependencies. You can use the information to remove large dependencies, split, or [lazy-load](/docs/app/building-your-application/optimizing/lazy-loading) your code. +[`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your application bundles. It generates a visual report of the size of each package and their dependencies. You can use the information to remove large dependencies, split, or [lazy-load](/docs/app/guides/lazy-loading) your code. ### Installation diff --git a/docs/01-app/02-guides/production-checklist.mdx b/docs/01-app/02-guides/production-checklist.mdx index fedc577f652bc..e5db5d649143c 100644 --- a/docs/01-app/02-guides/production-checklist.mdx +++ b/docs/01-app/02-guides/production-checklist.mdx @@ -15,7 +15,7 @@ These Next.js optimizations are enabled by default and require no configuration: <AppOnly> - **[Server Components](/docs/app/building-your-application/rendering/server-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/building-your-application/rendering/client-components) as needed for interactivity. -- **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/building-your-application/optimizing/lazy-loading) Client Components and third-party libraries, where appropriate. +- **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. - **[Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Static Rendering](/docs/app/building-your-application/rendering/server-components#static-rendering-default):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} - **[Caching](/docs/app/building-your-application/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. @@ -24,7 +24,7 @@ These Next.js optimizations are enabled by default and require no configuration: <PagesOnly> -- **[Code-splitting](/docs/pages/building-your-application/routing/pages-and-layouts):** Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider [lazy loading](/docs/pages/building-your-application/optimizing/lazy-loading) third-party libraries, where appropriate. +- **[Code-splitting](/docs/pages/building-your-application/routing/pages-and-layouts):** Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider [lazy loading](/docs/pages/guides/lazy-loading) third-party libraries, where appropriate. - **[Prefetching](/docs/pages/api-reference/components/link#prefetch):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization):** Next.js automatically determines that a page is static (can be pre-rendered) if it has no blocking data requirements. Optimized pages can be cached, and served to the end-user from multiple CDN locations. You may opt into [Server-side Rendering](/docs/pages/building-your-application/data-fetching/get-server-side-props), where appropriate. @@ -89,7 +89,7 @@ While building your application, we recommend using the following features to en - **[Font Module](/docs/app/building-your-application/optimizing/fonts):** Optimize fonts by using the Font Module, which automatically hosts your font files with other static assets, removes external network requests, and reduces [layout shift](https://web.dev/articles/cls). - **[`<Image>` Component](/docs/app/building-your-application/optimizing/images):** Optimize images by using the Image Component, which automatically optimizes images, prevents layout shift, and serves them in modern formats like WebP. -- **[`<Script>` Component](/docs/app/building-your-application/optimizing/scripts):** Optimize third-party scripts by using the Script Component, which automatically defers scripts and prevents them from blocking the main thread. +- **[`<Script>` Component](/docs/app/guides/scripts):** Optimize third-party scripts by using the Script Component, which automatically defers scripts and prevents them from blocking the main thread. - **[ESLint](/docs/architecture/accessibility#linting):** Use the built-in `eslint-plugin-jsx-a11y` plugin to catch accessibility issues early. ### Security @@ -140,7 +140,7 @@ Before going to production, you can run `next build` to build your application l ### Analyzing bundles -Use the [`@next/bundle-analyzer` plugin](/docs/app/building-your-application/optimizing/package-bundling#analyzing-javascript-bundles) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance. +Use the [`@next/bundle-analyzer` plugin](/docs/app/guides/package-bundling#analyzing-javascript-bundles) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance. Additionally, the following tools can help you understand the impact of adding new dependencies to your application: diff --git a/docs/01-app/03-building-your-application/06-optimizing/05-scripts.mdx b/docs/01-app/02-guides/scripts.mdx similarity index 99% rename from docs/01-app/03-building-your-application/06-optimizing/05-scripts.mdx rename to docs/01-app/02-guides/scripts.mdx index 20304295fbc72..e2a6b7a68802d 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/05-scripts.mdx +++ b/docs/01-app/02-guides/scripts.mdx @@ -1,5 +1,5 @@ --- -title: Script Optimization +title: How to load and optimize scripts nav_title: Scripts description: Optimize 3rd party scripts with the built-in Script component. related: diff --git a/docs/01-app/02-guides/self-hosting.mdx b/docs/01-app/02-guides/self-hosting.mdx index e5fc4405b7544..4af4c61a2fcc0 100644 --- a/docs/01-app/02-guides/self-hosting.mdx +++ b/docs/01-app/02-guides/self-hosting.mdx @@ -127,7 +127,7 @@ This allows you to use a singular Docker image that can be promoted through mult > **Good to know:** > -> - You can run code on server startup using the [`register` function](/docs/app/building-your-application/optimizing/instrumentation). +> - You can run code on server startup using the [`register` function](/docs/app/guides/instrumentation). > - We do not recommend using the [runtimeConfig](/docs/pages/api-reference/config/next-config-js/runtime-configuration) option, as this does not work with the standalone output mode. Instead, we recommend [incrementally adopting](/docs/app/guides/migrating/app-router-migration) the App Router. ### Caching and ISR diff --git a/docs/01-app/02-guides/single-page-applications.mdx b/docs/01-app/02-guides/single-page-applications.mdx index be96f71d1316b..9640cbb0977f2 100644 --- a/docs/01-app/02-guides/single-page-applications.mdx +++ b/docs/01-app/02-guides/single-page-applications.mdx @@ -281,7 +281,7 @@ Learn more in the [React Query documentation](https://tanstack.com/query/latest/ ### Rendering components only in the browser -Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic): +Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/guides/lazy-loading#nextdynamic): ```jsx import dynamic from 'next/dynamic' diff --git a/docs/01-app/02-guides/static-exports.mdx b/docs/01-app/02-guides/static-exports.mdx index 24902e3cfe70a..e3a09186c5826 100644 --- a/docs/01-app/02-guides/static-exports.mdx +++ b/docs/01-app/02-guides/static-exports.mdx @@ -157,7 +157,7 @@ The majority of core Next.js features needed to build a static site are supporte - [Dynamic Routes when using `getStaticPaths`](/docs/app/building-your-application/routing/dynamic-routes) - Prefetching with `next/link` - Preloading JavaScript -- [Dynamic Imports](/docs/pages/building-your-application/optimizing/lazy-loading) +- [Dynamic Imports](/docs/pages/guides/lazy-loading) - Any styling options (e.g. CSS Modules, styled-jsx) - [Client-side data fetching](/docs/pages/building-your-application/data-fetching/client-side) - [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) diff --git a/docs/01-app/03-building-your-application/06-optimizing/12-third-party-libraries.mdx b/docs/01-app/02-guides/third-party-libraries.mdx similarity index 99% rename from docs/01-app/03-building-your-application/06-optimizing/12-third-party-libraries.mdx rename to docs/01-app/02-guides/third-party-libraries.mdx index 41080bae27540..d6f7e08a2c77e 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/12-third-party-libraries.mdx +++ b/docs/01-app/02-guides/third-party-libraries.mdx @@ -1,5 +1,6 @@ --- -title: Third Party Libraries +title: How to optimize third-party libraries +nav_title: Third Party Libraries description: Optimize the performance of third-party libraries in your application with the `@next/third-parties` package. --- diff --git a/docs/01-app/03-building-your-application/06-optimizing/02-videos.mdx b/docs/01-app/02-guides/videos.mdx similarity index 99% rename from docs/01-app/03-building-your-application/06-optimizing/02-videos.mdx rename to docs/01-app/02-guides/videos.mdx index d945036bf80f6..8d05a53b1cd72 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/02-videos.mdx +++ b/docs/01-app/02-guides/videos.mdx @@ -1,5 +1,5 @@ --- -title: Video Optimization +title: How to use and optimize videos nav_title: Videos description: Recommendations and best practices for optimizing videos in your Next.js application. --- diff --git a/docs/01-app/03-building-your-application/06-optimizing/index.mdx b/docs/01-app/03-building-your-application/06-optimizing/index.mdx index 61f98715e1468..35077ab0384a9 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/index.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/index.mdx @@ -43,4 +43,4 @@ Next.js `/public` folder can be used to serve static assets like images, fonts, ## Analytics and Monitoring -For large applications, Next.js integrates with popular analytics and monitoring tools to help you understand how your application is performing. Learn more in the <PagesOnly>[Analytics](/docs/app/building-your-application/optimizing/analytics), </PagesOnly> [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry)<PagesOnly>,</PagesOnly> and [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) guides. +For large applications, Next.js integrates with popular analytics and monitoring tools to help you understand how your application is performing. Learn more in the <PagesOnly>[Analytics](/docs/app/guides/analytics), </PagesOnly> [OpenTelemetry](/docs/pages/guides/open-telemetry)<PagesOnly>,</PagesOnly> and [Instrumentation](/docs/pages/guides/instrumentation) guides. diff --git a/docs/01-app/05-api-reference/02-components/script.mdx b/docs/01-app/05-api-reference/02-components/script.mdx index e0889195ad7d5..7027549c45b39 100644 --- a/docs/01-app/05-api-reference/02-components/script.mdx +++ b/docs/01-app/05-api-reference/02-components/script.mdx @@ -5,7 +5,7 @@ description: Optimize third-party scripts in your Next.js application using the {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -This API reference will help you understand how to use [props](#props) available for the Script Component. For features and usage, please see the [Optimizing Scripts](/docs/app/building-your-application/optimizing/scripts) page. +This API reference will help you understand how to use [props](#props) available for the Script Component. For features and usage, please see the [Optimizing Scripts](/docs/app/guides/scripts) page. ```tsx filename="app/dashboard/page.tsx" switcher import Script from 'next/script' diff --git a/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx b/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx index 8242c91c57be1..91945946be977 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx @@ -9,7 +9,7 @@ To use it, place the file in the **root** of your application or inside a `src` ## Usage -Unlike [server-side instrumentation](/docs/app/building-your-application/optimizing/instrumentation), you do not need to export any specific functions. You can write your monitoring code directly in the file: +Unlike [server-side instrumentation](/docs/app/guides/instrumentation), you do not need to export any specific functions. You can write your monitoring code directly in the file: ```ts filename="instrumentation-client.ts" switcher // Set up performance monitoring diff --git a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx index be35961615758..88522f1767d0f 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx @@ -4,7 +4,7 @@ description: API reference for the instrumentation.js file. related: title: Learn more about Instrumentation links: - - app/building-your-application/optimizing/instrumentation + - app/guides/instrumentation --- The `instrumentation.js|ts` file is used to integrate observability tools into your application, allowing you to track the performance and behavior, and to debug issues in production. diff --git a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx index 3820aa4e4e257..ab1d590cbbbf2 100644 --- a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx +++ b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx @@ -1047,7 +1047,7 @@ The following metadata types do not currently have built-in support. However, th | `<base>` | Render the tag in the layout or page itself. | | `<noscript>` | Render the tag in the layout or page itself. | | `<style>` | Learn more about [styling in Next.js](/docs/app/building-your-application/styling/css). | -| `<script>` | Learn more about [using scripts](/docs/app/building-your-application/optimizing/scripts). | +| `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). | | `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. | | `<link rel="preload />` | Use [ReactDOM preload method](#link-relpreload) | | `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) | diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx index 47121b85b8363..160c53b7b1ba8 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx @@ -5,7 +5,7 @@ description: Use the `crossOrigin` option to add a crossOrigin tag on the `scrip {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -Use the `crossOrigin` option to add a [`crossOrigin` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) in all `<script>` tags generated by the <AppOnly>[`next/script`](/docs/app/building-your-application/optimizing/scripts) component</AppOnly> <PagesOnly>[`next/script`](/docs/pages/building-your-application/optimizing/scripts) and [`next/head`](/docs/pages/api-reference/components/head)components</PagesOnly>, and define how cross-origin requests should be handled. +Use the `crossOrigin` option to add a [`crossOrigin` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) in all `<script>` tags generated by the <AppOnly>[`next/script`](/docs/app/guides/scripts) component</AppOnly> <PagesOnly>[`next/script`](/docs/pages/guides/scripts) and [`next/head`](/docs/pages/api-reference/components/head)components</PagesOnly>, and define how cross-origin requests should be handled. ```js filename="next.config.js" module.exports = { diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx index 682c89aa23864..fe87768a68c30 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx @@ -35,7 +35,7 @@ module.exports = { Changing these values affects _all_ Next.js pages, including the following: - [`middleware.js`](/docs/pages/building-your-application/routing/middleware) -- [`instrumentation.js`](/docs/pages/building-your-application/optimizing/instrumentation) +- [`instrumentation.js`](/docs/pages/guides/instrumentation) - `pages/_document.js` - `pages/_app.js` - `pages/api/` diff --git a/docs/02-pages/03-building-your-application/05-optimizing/07-analytics.mdx b/docs/02-pages/02-guides/analytics.mdx similarity index 68% rename from docs/02-pages/03-building-your-application/05-optimizing/07-analytics.mdx rename to docs/02-pages/02-guides/analytics.mdx index 1a53e5a59bf73..a43f65cb5a9c5 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/07-analytics.mdx +++ b/docs/02-pages/02-guides/analytics.mdx @@ -1,7 +1,8 @@ --- -title: Analytics -description: Measure and track page performance using Next.js Speed Insights -source: app/building-your-application/optimizing/analytics +title: How to set up analytics +nav_title: Analytics +description: Measure and track page performance using Next.js +source: app/guides/analytics --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/05-optimizing/09-instrumentation.mdx b/docs/02-pages/02-guides/instrumentation.mdx similarity index 81% rename from docs/02-pages/03-building-your-application/05-optimizing/09-instrumentation.mdx rename to docs/02-pages/02-guides/instrumentation.mdx index cb2aae5e2a151..9ff275d1a6f18 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/09-instrumentation.mdx +++ b/docs/02-pages/02-guides/instrumentation.mdx @@ -1,7 +1,8 @@ --- -title: Instrumentation +title: How to set up instrumentation +nav_title: Instrumentation description: Learn how to use instrumentation to run code at server startup in your Next.js app -source: app/building-your-application/optimizing/instrumentation +source: app/guides/instrumentation --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/05-optimizing/08-lazy-loading.mdx b/docs/02-pages/02-guides/lazy-loading.mdx similarity index 80% rename from docs/02-pages/03-building-your-application/05-optimizing/08-lazy-loading.mdx rename to docs/02-pages/02-guides/lazy-loading.mdx index f78374e9db239..bdb3065506241 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/08-lazy-loading.mdx +++ b/docs/02-pages/02-guides/lazy-loading.mdx @@ -1,7 +1,8 @@ --- -title: Lazy Loading +title: How to lazy load Client Components and libraries +nav_title: Lazy Loading description: Lazy load imported libraries and React Components to improve your application's overall loading performance. -source: app/building-your-application/optimizing/lazy-loading +source: app/guides/lazy-loading --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/05-optimizing/10-open-telemetry.mdx b/docs/02-pages/02-guides/open-telemetry.mdx similarity index 77% rename from docs/02-pages/03-building-your-application/05-optimizing/10-open-telemetry.mdx rename to docs/02-pages/02-guides/open-telemetry.mdx index 0c3d0b505720c..84c6d14a5cb09 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/10-open-telemetry.mdx +++ b/docs/02-pages/02-guides/open-telemetry.mdx @@ -1,7 +1,8 @@ --- -title: OpenTelemetry +title: How to instrument your Next.js app with OpenTelemetry +nav_title: OpenTelemetry description: Learn how to instrument your Next.js app with OpenTelemetry. -source: app/building-your-application/optimizing/open-telemetry +source: app/guides/open-telemetry --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/05-optimizing/06-package-bundling.mdx b/docs/02-pages/02-guides/package-bundling.mdx similarity index 83% rename from docs/02-pages/03-building-your-application/05-optimizing/06-package-bundling.mdx rename to docs/02-pages/02-guides/package-bundling.mdx index b2ba7dd2af64f..9c35d04697845 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/06-package-bundling.mdx +++ b/docs/02-pages/02-guides/package-bundling.mdx @@ -1,8 +1,8 @@ --- -title: Optimizing Bundling -nav_title: Bundling +title: How to optimize package bundling +nav_title: Package Bundling description: Learn how to optimize your application's server and client bundles. -source: app/building-your-application/optimizing/package-bundling +source: app/guides/package-bundling related: description: Learn more about optimizing your application for production. links: diff --git a/docs/02-pages/03-building-your-application/05-optimizing/03-scripts.mdx b/docs/02-pages/02-guides/scripts.mdx similarity index 83% rename from docs/02-pages/03-building-your-application/05-optimizing/03-scripts.mdx rename to docs/02-pages/02-guides/scripts.mdx index 1609a617fb8d9..e1579efc014eb 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/03-scripts.mdx +++ b/docs/02-pages/02-guides/scripts.mdx @@ -1,8 +1,8 @@ --- -title: Script Optimization +title: How to load and optimize scripts nav_title: Scripts description: Optimize 3rd party scripts with the built-in Script component. -source: app/building-your-application/optimizing/scripts +source: app/guides/scripts --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/05-optimizing/11-third-party-libraries.mdx b/docs/02-pages/02-guides/third-party-libraries.mdx similarity index 79% rename from docs/02-pages/03-building-your-application/05-optimizing/11-third-party-libraries.mdx rename to docs/02-pages/02-guides/third-party-libraries.mdx index 0ca3a1ece15dc..48a5b97f67cb2 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/11-third-party-libraries.mdx +++ b/docs/02-pages/02-guides/third-party-libraries.mdx @@ -1,7 +1,8 @@ --- -title: Third Party Libraries +title: How to optimize third-party libraries +nav_title: Third Party Libraries description: Optimize the performance of third-party libraries in your application with the `@next/third-parties` package. -source: app/building-your-application/optimizing/third-party-libraries +source: app/guides/third-party-libraries --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/04-api-reference/01-components/head.mdx b/docs/02-pages/04-api-reference/01-components/head.mdx index d34dc48310ee4..be5ac7ec981bf 100644 --- a/docs/02-pages/04-api-reference/01-components/head.mdx +++ b/docs/02-pages/04-api-reference/01-components/head.mdx @@ -60,7 +60,7 @@ or wrapped into maximum one level of `<React.Fragment>` or arrays—otherwise th ## Use `next/script` for scripts -We recommend using [`next/script`](/docs/pages/building-your-application/optimizing/scripts) in your component instead of manually creating a `<script>` in `next/head`. +We recommend using [`next/script`](/docs/pages/guides/scripts) in your component instead of manually creating a `<script>` in `next/head`. ## No `html` or `body` tags diff --git a/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx b/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx index c5d15324d50e1..a547329f3d4ac 100644 --- a/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx +++ b/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx @@ -6,7 +6,7 @@ description: Add client and server runtime configuration to your Next.js app. > **Warning:** > > - **This feature is deprecated.** We recommend using [environment variables](/docs/pages/guides/environment-variables) instead, which also can support reading runtime values. -> - You can run code on server startup using the [`register` function](/docs/app/building-your-application/optimizing/instrumentation). +> - You can run code on server startup using the [`register` function](/docs/app/guides/instrumentation). > - This feature does not work with [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization), [Output File Tracing](/docs/pages/api-reference/config/next-config-js/output#automatically-copying-traced-files), or [React Server Components](/docs/app/building-your-application/rendering/server-components). To add runtime configuration to your app, open `next.config.js` and add the `publicRuntimeConfig` and `serverRuntimeConfig` configs: diff --git a/errors/inline-script-id.mdx b/errors/inline-script-id.mdx index ba15bf31363ee..94e06d97b6ca0 100644 --- a/errors/inline-script-id.mdx +++ b/errors/inline-script-id.mdx @@ -27,4 +27,4 @@ export default function App({ Component, pageProps }) { ## Useful links -- [Docs for Next.js Script component](/docs/pages/building-your-application/optimizing/scripts) +- [Docs for Next.js Script component](/docs/pages/guides/scripts) diff --git a/errors/invalid-dynamic-options-type.mdx b/errors/invalid-dynamic-options-type.mdx index f6fe20caaafe0..5610b51ab0c5c 100644 --- a/errors/invalid-dynamic-options-type.mdx +++ b/errors/invalid-dynamic-options-type.mdx @@ -30,4 +30,4 @@ const DynamicComponent = dynamic(() => import('../components/hello'), { ## Useful Links -- [Dynamic Import](/docs/pages/building-your-application/optimizing/lazy-loading) +- [Dynamic Import](/docs/pages/guides/lazy-loading) diff --git a/errors/invalid-dynamic-suspense.mdx b/errors/invalid-dynamic-suspense.mdx index 0785dc7356245..09b18abd8889b 100644 --- a/errors/invalid-dynamic-suspense.mdx +++ b/errors/invalid-dynamic-suspense.mdx @@ -30,4 +30,4 @@ You should remove `loading` from `next/dynamic` usages, and use `<Suspense />`'s ## Useful Links -- [Dynamic Import Suspense Usage](/docs/pages/building-your-application/optimizing/lazy-loading#nextdynamic) +- [Dynamic Import Suspense Usage](/docs/pages/guides/lazy-loading#nextdynamic) diff --git a/errors/invalid-script.mdx b/errors/invalid-script.mdx index 18806b1fa6b19..70495b0e376ec 100644 --- a/errors/invalid-script.mdx +++ b/errors/invalid-script.mdx @@ -37,4 +37,4 @@ Look for any usage of the `next/script` component and make sure that `src` is pr ## Useful Links -- [Script Component in Documentation](/docs/pages/building-your-application/optimizing/scripts) +- [Script Component in Documentation](/docs/pages/guides/scripts) diff --git a/errors/next-script-for-ga.mdx b/errors/next-script-for-ga.mdx index 6c86d2497e3a1..55292193558ff 100644 --- a/errors/next-script-for-ga.mdx +++ b/errors/next-script-for-ga.mdx @@ -65,11 +65,11 @@ export default function Page() { > **Good to know:** > -> - If you are using the Pages Router, please refer to the [`pages/` documentation](/docs/pages/building-your-application/optimizing/third-party-libraries). -> - `@next/third-parties` also supports [Google Tag Manager](/docs/app/building-your-application/optimizing/third-party-libraries#google-tag-manager) and other third parties. -> - Using `@next/third-parties` is not required. You can also use the `next/script` component directly. Refer to the [`next/script` documentation](/docs/app/building-your-application/optimizing/scripts) to learn more. +> - If you are using the Pages Router, please refer to the [`pages/` documentation](/docs/pages/guides/third-party-libraries). +> - `@next/third-parties` also supports [Google Tag Manager](/docs/app/guides/third-party-libraries#google-tag-manager) and other third parties. +> - Using `@next/third-parties` is not required. You can also use the `next/script` component directly. Refer to the [`next/script` documentation](/docs/app/guides/scripts) to learn more. ## Useful Links -- [`@next/third-parties` Documentation](/docs/app/building-your-application/optimizing/third-party-libraries) -- [`next/script` Documentation](/docs/app/building-your-application/optimizing/scripts) +- [`@next/third-parties` Documentation](/docs/app/guides/third-party-libraries) +- [`next/script` Documentation](/docs/app/guides/scripts) diff --git a/errors/no-before-interactive-script-outside-document.mdx b/errors/no-before-interactive-script-outside-document.mdx index c939ade1a8113..68965e6758d64 100644 --- a/errors/no-before-interactive-script-outside-document.mdx +++ b/errors/no-before-interactive-script-outside-document.mdx @@ -57,5 +57,5 @@ export default function Document() { ## Useful Links -- [App Router Script Optimization](/docs/app/building-your-application/optimizing/scripts) -- [Pages Router Script Optimization](/docs/pages/building-your-application/optimizing/scripts) +- [App Router Script Optimization](/docs/app/guides/scripts) +- [Pages Router Script Optimization](/docs/pages/guides/scripts) diff --git a/errors/no-script-component-in-head.mdx b/errors/no-script-component-in-head.mdx index 5d0709fa81ebf..6bb790ab89a3e 100644 --- a/errors/no-script-component-in-head.mdx +++ b/errors/no-script-component-in-head.mdx @@ -49,4 +49,4 @@ export default function Index() { ## Useful Links - [next/head](/docs/pages/api-reference/components/head) -- [next/script](/docs/pages/building-your-application/optimizing/scripts) +- [next/script](/docs/pages/guides/scripts) diff --git a/errors/no-script-in-document.mdx b/errors/no-script-in-document.mdx index f0dd04c3e759e..2831d614117e4 100644 --- a/errors/no-script-in-document.mdx +++ b/errors/no-script-in-document.mdx @@ -32,4 +32,4 @@ export default MyApp ## Useful Links - [custom-app](/docs/pages/building-your-application/routing/custom-app) -- [next-script](/docs/pages/building-your-application/optimizing/scripts) +- [next-script](/docs/pages/guides/scripts) diff --git a/errors/no-script-tags-in-head-component.mdx b/errors/no-script-tags-in-head-component.mdx index bbdd837ad98f2..71763c23f683d 100644 --- a/errors/no-script-tags-in-head-component.mdx +++ b/errors/no-script-tags-in-head-component.mdx @@ -28,5 +28,5 @@ export default function Dashboard() { ## Useful Links -- [Optimizing Scripts](/docs/pages/building-your-application/optimizing/scripts) +- [Optimizing Scripts](/docs/pages/guides/scripts) - [`next/script` API Reference](/docs/pages/api-reference/components/script) diff --git a/errors/react-hydration-error.mdx b/errors/react-hydration-error.mdx index e1c5e12ff2cf8..594139089fbdb 100644 --- a/errors/react-hydration-error.mdx +++ b/errors/react-hydration-error.mdx @@ -51,7 +51,7 @@ During React hydration, `useEffect` is called. This means browser APIs like `win ### Solution 2: Disabling SSR on specific components -Next.js allows you to [disable prerendering](/docs/app/building-your-application/optimizing/lazy-loading#skipping-ssr) on specific components, which can prevent hydration mismatches. +Next.js allows you to [disable prerendering](/docs/app/guides/lazy-loading#skipping-ssr) on specific components, which can prevent hydration mismatches. ```jsx import dynamic from 'next/dynamic'
diff --git a/docs/01-app/01-getting-started/02-project-structure.mdx b/docs/01-app/01-getting-started/02-project-structure.mdx index 085745f2137d4..bf1931022b151 100644 --- a/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/docs/01-app/01-getting-started/02-project-structure.mdx @@ -31,22 +31,22 @@ Top-level folders are used to organize your application's code and static assets Top-level files are used to configure your application, manage dependencies, run middleware, integrate monitoring tools, and define environment variables. -| -------------------------------------------------------------------------------------- | --------------------------------------- | -| **Next.js** | | -| [`next.config.js`](/docs/app/api-reference/config/next-config-js) | Configuration file for Next.js | -| [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts | -| [`instrumentation.ts`](/docs/app/building-your-application/optimizing/instrumentation) | OpenTelemetry and Instrumentation file | -| [`middleware.ts`](/docs/app/building-your-application/routing/middleware) | Next.js request middleware | -| [`.env`](/docs/app/guides/environment-variables) | Environment variables | -| [`.env.local`](/docs/app/guides/environment-variables) | Local environment variables | -| [`.env.production`](/docs/app/guides/environment-variables) | Production environment variables | -| [`.env.development`](/docs/app/guides/environment-variables) | Development environment variables | -| [`.eslintrc.json`](/docs/app/api-reference/config/eslint) | Configuration file for ESLint | -| `.gitignore` | Git files and folders to ignore | -| `tsconfig.json` | Configuration file for TypeScript | -| `jsconfig.json` | Configuration file for JavaScript | +| | | +| ---------------------------------------------------------------------------- | --------------------------------------- | +| **Next.js** | | +| [`next.config.js`](/docs/app/api-reference/config/next-config-js) | Configuration file for Next.js | +| [`package.json`](/docs/app/getting-started/installation#manual-installation) | Project dependencies and scripts | +| [`instrumentation.ts`](/docs/app/guides/instrumentation) | OpenTelemetry and Instrumentation file | +| [`middleware.ts`](/docs/app/building-your-application/routing/middleware) | Next.js request middleware | +| [`.env`](/docs/app/guides/environment-variables) | Environment variables | +| [`.env.local`](/docs/app/guides/environment-variables) | Local environment variables | +| [`.env.production`](/docs/app/guides/environment-variables) | Production environment variables | +| [`.eslintrc.json`](/docs/app/api-reference/config/eslint) | Configuration file for ESLint | +| `.gitignore` | Git files and folders to ignore | +| `next-env.d.ts` | TypeScript declaration file for Next.js | +| `tsconfig.json` | Configuration file for TypeScript | +| `jsconfig.json` | Configuration file for JavaScript | diff --git a/docs/01-app/03-building-your-application/06-optimizing/08-analytics.mdx b/docs/01-app/02-guides/analytics.mdx similarity index 93% rename from docs/01-app/03-building-your-application/06-optimizing/08-analytics.mdx rename to docs/01-app/02-guides/analytics.mdx index 49ff948349a07..0cdf80fe9196b 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/08-analytics.mdx +++ b/docs/01-app/02-guides/analytics.mdx @@ -1,11 +1,12 @@ +title: How to add analytics to your Next.js application description: Measure and track page performance using Next.js Speed Insights -Next.js has built-in support for measuring and reporting performance metrics. You can either use the `useReportWebVitals` hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) to automatically collect and visualize metrics for you. +Next.js has built-in support for measuring and reporting performance metrics. You can either use the [`useReportWebVitals`](/docs/app/api-reference/functions/use-report-web-vitals) hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) to automatically collect and visualize metrics for you. ## Client Instrumentation diff --git a/docs/01-app/02-guides/environment-variables.mdx b/docs/01-app/02-guides/environment-variables.mdx index e6bd12e2f1943..6e4489c6adcbe 100644 --- a/docs/01-app/02-guides/environment-variables.mdx +++ b/docs/01-app/02-guides/environment-variables.mdx @@ -227,7 +227,7 @@ This allows you to use a singular Docker image that can be promoted through mult **Good to know:** -- You can run code on server startup using the [`register` function](/docs/app/building-your-application/optimizing/instrumentation). +- You can run code on server startup using the [`register` function](/docs/app/guides/instrumentation). - We do not recommend using the [`runtimeConfig`](/docs/pages/api-reference/config/next-config-js/runtime-configuration) option, as this does not work with the standalone output mode. Instead, we recommend [incrementally adopting](/docs/app/guides/migrating/app-router-migration) the App Router if you need this feature. ## Environment Variables on Vercel diff --git a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx b/docs/01-app/02-guides/instrumentation.mdx rename from docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx rename to docs/01-app/02-guides/instrumentation.mdx index d4bc45bffbf2b..86a6b538b0dc8 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx +++ b/docs/01-app/02-guides/instrumentation.mdx diff --git a/docs/01-app/03-building-your-application/06-optimizing/07-lazy-loading.mdx b/docs/01-app/02-guides/lazy-loading.mdx rename from docs/01-app/03-building-your-application/06-optimizing/07-lazy-loading.mdx rename to docs/01-app/02-guides/lazy-loading.mdx index 9c98f4c15563a..4e0b477a0cc76 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/07-lazy-loading.mdx +++ b/docs/01-app/02-guides/lazy-loading.mdx description: Lazy load imported libraries and React Components to improve your application's loading performance. diff --git a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx b/docs/01-app/02-guides/local-development.mdx rename from docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx rename to docs/01-app/02-guides/local-development.mdx index 35e2b9a191140..c09a43a7a2ef5 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx +++ b/docs/01-app/02-guides/local-development.mdx -title: Local Development +title: How to optimize your local development environment +nav_title: Development Environment description: Learn how to optimize your local development environment with Next.js. @@ -34,7 +35,7 @@ npm run dev --turbopack ### 3. Check your imports ### Icon libraries @@ -122,7 +123,7 @@ Consider if you really need them for local development. You can optionally only If your app is very large, it might need more memory. +[Learn more about optimizing memory usage](/docs/app/guides/memory-usage). ### 7. Server Components and data fetching diff --git a/docs/01-app/03-building-your-application/06-optimizing/13-memory-usage.mdx b/docs/01-app/02-guides/memory-usage.mdx similarity index 96% rename from docs/01-app/03-building-your-application/06-optimizing/13-memory-usage.mdx rename to docs/01-app/02-guides/memory-usage.mdx index 46011e262c17c..d625c3b342155 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/13-memory-usage.mdx +++ b/docs/01-app/02-guides/memory-usage.mdx -title: Memory Usage +title: How to optimize memory usage +nav_title: Memory Usage description: Optimize memory used by your application in development and production. @@ -11,7 +12,7 @@ Let's explore some strategies and techniques to optimize memory and address comm Applications with a large amount of dependencies will use more memory. -The [Bundle Analyzer](/docs/app/building-your-application/optimizing/package-bundling) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage. +The [Bundle Analyzer](/docs/app/guides/package-bundling) can help you investigate large dependencies in your application that may be able to be removed to improve performance and memory usage. ## Try `experimental.webpackMemoryOptimizations` diff --git a/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/docs/01-app/02-guides/migrating/from-create-react-app.mdx index e7cf97f761a1c..348bccc1c893f 100644 --- a/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/docs/01-app/02-guides/migrating/from-create-react-app.mdx -[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/building-your-application/optimizing/scripts) often have a large impact on an application’s performance. Next.js includes specialized components and APIs that automatically optimize them for you. +[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/guides/scripts) often have a large impact on an application’s performance. Next.js includes specialized components and APIs that automatically optimize them for you. @@ -575,7 +575,7 @@ If everything worked, you now have a functioning Next.js application running as - **Optimize images** with the [`<Image>` component](/docs/app/building-your-application/optimizing/images) - **Optimize fonts** with [`next/font`](/docs/app/building-your-application/optimizing/fonts) -- **Optimize third-party scripts** with the [`<Script>` component](/docs/app/building-your-application/optimizing/scripts) +- **Optimize third-party scripts** with the [`<Script>` component](/docs/app/guides/scripts) - **Enable ESLint** with Next.js recommended rules by running `npx next lint` and configuring it to match your project’s needs > **Note**: Using a static export (`output: 'export'`) [does not currently support](https://github.com/vercel/next.js/issues/54393) the `useParams` hook or other server features. To use all Next.js features, remove `output: 'export'` from your `next.config.ts`. diff --git a/docs/01-app/02-guides/migrating/from-vite.mdx b/docs/01-app/02-guides/migrating/from-vite.mdx index 7cf79078a8f34..d50a4432c63d2 100644 --- a/docs/01-app/02-guides/migrating/from-vite.mdx +++ b/docs/01-app/02-guides/migrating/from-vite.mdx -[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/building-your-application/optimizing/scripts) often have significant impact on an application's performance. Next.js comes with built-in components that automatically optimize those for you. +[Images](/docs/app/building-your-application/optimizing/images), [fonts](/docs/app/building-your-application/optimizing/fonts), and [third-party scripts](/docs/app/guides/scripts) often have significant impact on an application's performance. Next.js comes with built-in components that automatically optimize those for you. @@ -598,5 +598,5 @@ do next: - [Optimize images with the `<Image>` component](/docs/app/building-your-application/optimizing/images) - [Optimize fonts with `next/font`](/docs/app/building-your-application/optimizing/fonts) -- [Optimize third-party scripts with the `<Script>` component](/docs/app/building-your-application/optimizing/scripts) +- [Optimize third-party scripts with the `<Script>` component](/docs/app/guides/scripts) - [Update your ESLint configuration to support Next.js rules](/docs/app/api-reference/config/eslint) diff --git a/docs/01-app/03-building-your-application/06-optimizing/10-open-telemetry.mdx b/docs/01-app/02-guides/open-telemetry.mdx rename from docs/01-app/03-building-your-application/06-optimizing/10-open-telemetry.mdx rename to docs/01-app/02-guides/open-telemetry.mdx index 39839f5fc1c2a..b7b61a1afdd7e 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/10-open-telemetry.mdx +++ b/docs/01-app/02-guides/open-telemetry.mdx +title: How to set up instrumentation with OpenTelemetry @@ -16,7 +17,11 @@ Read [Official OpenTelemetry docs](https://opentelemetry.io/docs/) for more info This documentation uses terms like _Span_, _Trace_ or _Exporter_ throughout this doc, all of which can be found in [the OpenTelemetry Observability Primer](https://opentelemetry.io/docs/concepts/observability-primer/). Next.js supports OpenTelemetry instrumentation out of the box, which means that we already instrumented Next.js itself. -When you enable OpenTelemetry we will automatically wrap all your code like `getStaticProps` in _spans_ with helpful attributes. + +<PagesOnly> + When you enable OpenTelemetry we will automatically wrap all your code like + `getStaticProps` in _spans_ with helpful attributes. +</PagesOnly> ## Getting Started @@ -33,13 +38,13 @@ npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opente -Next, create a custom [`instrumentation.ts`](/docs/app/building-your-application/optimizing/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): +Next, create a custom [`instrumentation.ts`](/docs/app/guides/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): </AppOnly> -Next, create a custom [`instrumentation.ts`](/docs/pages/building-your-application/optimizing/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): +Next, create a custom [`instrumentation.ts`](/docs/pages/guides/instrumentation) (or `.js`) file in the **root directory** of the project (or inside `src` folder if using one): </PagesOnly> diff --git a/docs/01-app/03-building-your-application/06-optimizing/06-package-bundling.mdx b/docs/01-app/02-guides/package-bundling.mdx rename from docs/01-app/03-building-your-application/06-optimizing/06-package-bundling.mdx rename to docs/01-app/02-guides/package-bundling.mdx index 81f50e04b08d7..fe93d18b91a10 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/06-package-bundling.mdx +++ b/docs/01-app/02-guides/package-bundling.mdx -title: Optimizing Package Bundling nav_title: Package Bundling @@ -12,7 +12,7 @@ Bundling external packages can significantly improve the performance of your app ## Analyzing JavaScript bundles -[`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your application bundles. It generates a visual report of the size of each package and their dependencies. You can use the information to remove large dependencies, split, or [lazy-load](/docs/app/building-your-application/optimizing/lazy-loading) your code. +[`@next/bundle-analyzer`](https://www.npmjs.com/package/@next/bundle-analyzer) is a plugin for Next.js that helps you manage the size of your application bundles. It generates a visual report of the size of each package and their dependencies. You can use the information to remove large dependencies, split, or [lazy-load](/docs/app/guides/lazy-loading) your code. ### Installation diff --git a/docs/01-app/02-guides/production-checklist.mdx b/docs/01-app/02-guides/production-checklist.mdx index fedc577f652bc..e5db5d649143c 100644 --- a/docs/01-app/02-guides/production-checklist.mdx +++ b/docs/01-app/02-guides/production-checklist.mdx @@ -15,7 +15,7 @@ These Next.js optimizations are enabled by default and require no configuration: - **[Server Components](/docs/app/building-your-application/rendering/server-components):** Next.js uses Server Components by default. Server Components run on the server, and don't require JavaScript to render on the client. As such, they have no impact on the size of your client-side JavaScript bundles. You can then use [Client Components](/docs/app/building-your-application/rendering/client-components) as needed for interactivity. -- **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/building-your-application/optimizing/lazy-loading) Client Components and third-party libraries, where appropriate. +- **[Code-splitting](/docs/app/building-your-application/routing/linking-and-navigating#how-routing-and-navigation-works):** Server Components enable automatic code-splitting by route segments. You may also consider [lazy loading](/docs/app/guides/lazy-loading) Client Components and third-party libraries, where appropriate. - **[Prefetching](/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Static Rendering](/docs/app/building-your-application/rendering/server-components#static-rendering-default):** Next.js statically renders Server and Client Components on the server at build time and caches the rendered result to improve your application's performance. You can opt into [Dynamic Rendering](/docs/app/building-your-application/rendering/server-components#dynamic-rendering) for specific routes, where appropriate. {/* TODO: Update when PPR is stable */} - **[Caching](/docs/app/building-your-application/caching):** Next.js caches data requests, the rendered result of Server and Client Components, static assets, and more, to reduce the number of network requests to your server, database, and backend services. You may opt out of caching, where appropriate. @@ -24,7 +24,7 @@ These Next.js optimizations are enabled by default and require no configuration: -- **[Code-splitting](/docs/pages/building-your-application/routing/pages-and-layouts):** Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider [lazy loading](/docs/pages/building-your-application/optimizing/lazy-loading) third-party libraries, where appropriate. +- **[Code-splitting](/docs/pages/building-your-application/routing/pages-and-layouts):** Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider [lazy loading](/docs/pages/guides/lazy-loading) third-party libraries, where appropriate. - **[Prefetching](/docs/pages/api-reference/components/link#prefetch):** When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate. - **[Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization):** Next.js automatically determines that a page is static (can be pre-rendered) if it has no blocking data requirements. Optimized pages can be cached, and served to the end-user from multiple CDN locations. You may opt into [Server-side Rendering](/docs/pages/building-your-application/data-fetching/get-server-side-props), where appropriate. @@ -89,7 +89,7 @@ While building your application, we recommend using the following features to en - **[Font Module](/docs/app/building-your-application/optimizing/fonts):** Optimize fonts by using the Font Module, which automatically hosts your font files with other static assets, removes external network requests, and reduces [layout shift](https://web.dev/articles/cls). - **[`<Image>` Component](/docs/app/building-your-application/optimizing/images):** Optimize images by using the Image Component, which automatically optimizes images, prevents layout shift, and serves them in modern formats like WebP. -- **[`<Script>` Component](/docs/app/building-your-application/optimizing/scripts):** Optimize third-party scripts by using the Script Component, which automatically defers scripts and prevents them from blocking the main thread. +- **[`<Script>` Component](/docs/app/guides/scripts):** Optimize third-party scripts by using the Script Component, which automatically defers scripts and prevents them from blocking the main thread. - **[ESLint](/docs/architecture/accessibility#linting):** Use the built-in `eslint-plugin-jsx-a11y` plugin to catch accessibility issues early. ### Security @@ -140,7 +140,7 @@ Before going to production, you can run `next build` to build your application l ### Analyzing bundles -Use the [`@next/bundle-analyzer` plugin](/docs/app/building-your-application/optimizing/package-bundling#analyzing-javascript-bundles) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance. +Use the [`@next/bundle-analyzer` plugin](/docs/app/guides/package-bundling#analyzing-javascript-bundles) to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance. Additionally, the following tools can help you understand the impact of adding new dependencies to your application: diff --git a/docs/01-app/03-building-your-application/06-optimizing/05-scripts.mdx b/docs/01-app/02-guides/scripts.mdx rename from docs/01-app/03-building-your-application/06-optimizing/05-scripts.mdx rename to docs/01-app/02-guides/scripts.mdx index 20304295fbc72..e2a6b7a68802d 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/05-scripts.mdx +++ b/docs/01-app/02-guides/scripts.mdx diff --git a/docs/01-app/02-guides/self-hosting.mdx b/docs/01-app/02-guides/self-hosting.mdx index e5fc4405b7544..4af4c61a2fcc0 100644 --- a/docs/01-app/02-guides/self-hosting.mdx +++ b/docs/01-app/02-guides/self-hosting.mdx @@ -127,7 +127,7 @@ This allows you to use a singular Docker image that can be promoted through mult > - We do not recommend using the [runtimeConfig](/docs/pages/api-reference/config/next-config-js/runtime-configuration) option, as this does not work with the standalone output mode. Instead, we recommend [incrementally adopting](/docs/app/guides/migrating/app-router-migration) the App Router. ### Caching and ISR diff --git a/docs/01-app/02-guides/single-page-applications.mdx b/docs/01-app/02-guides/single-page-applications.mdx index be96f71d1316b..9640cbb0977f2 100644 --- a/docs/01-app/02-guides/single-page-applications.mdx +++ b/docs/01-app/02-guides/single-page-applications.mdx @@ -281,7 +281,7 @@ Learn more in the [React Query documentation](https://tanstack.com/query/latest/ ### Rendering components only in the browser -Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic): +Client components are [prerendered](https://github.com/reactwg/server-components/discussions/4) during `next build`. If you want to disable prerendering for a Client Component and only load it in the browser environment, you can use [`next/dynamic`](/docs/app/guides/lazy-loading#nextdynamic): diff --git a/docs/01-app/02-guides/static-exports.mdx b/docs/01-app/02-guides/static-exports.mdx index 24902e3cfe70a..e3a09186c5826 100644 --- a/docs/01-app/02-guides/static-exports.mdx +++ b/docs/01-app/02-guides/static-exports.mdx @@ -157,7 +157,7 @@ The majority of core Next.js features needed to build a static site are supporte - [Dynamic Routes when using `getStaticPaths`](/docs/app/building-your-application/routing/dynamic-routes) - Prefetching with `next/link` - Preloading JavaScript -- [Dynamic Imports](/docs/pages/building-your-application/optimizing/lazy-loading) +- [Dynamic Imports](/docs/pages/guides/lazy-loading) - Any styling options (e.g. CSS Modules, styled-jsx) - [Client-side data fetching](/docs/pages/building-your-application/data-fetching/client-side) - [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) diff --git a/docs/01-app/03-building-your-application/06-optimizing/12-third-party-libraries.mdx b/docs/01-app/02-guides/third-party-libraries.mdx rename from docs/01-app/03-building-your-application/06-optimizing/12-third-party-libraries.mdx rename to docs/01-app/02-guides/third-party-libraries.mdx index 41080bae27540..d6f7e08a2c77e 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/12-third-party-libraries.mdx +++ b/docs/01-app/02-guides/third-party-libraries.mdx diff --git a/docs/01-app/03-building-your-application/06-optimizing/02-videos.mdx b/docs/01-app/02-guides/videos.mdx rename from docs/01-app/03-building-your-application/06-optimizing/02-videos.mdx rename to docs/01-app/02-guides/videos.mdx index d945036bf80f6..8d05a53b1cd72 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/02-videos.mdx +++ b/docs/01-app/02-guides/videos.mdx -title: Video Optimization +title: How to use and optimize videos nav_title: Videos description: Recommendations and best practices for optimizing videos in your Next.js application. diff --git a/docs/01-app/03-building-your-application/06-optimizing/index.mdx b/docs/01-app/03-building-your-application/06-optimizing/index.mdx index 61f98715e1468..35077ab0384a9 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/index.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/index.mdx @@ -43,4 +43,4 @@ Next.js `/public` folder can be used to serve static assets like images, fonts, ## Analytics and Monitoring -For large applications, Next.js integrates with popular analytics and monitoring tools to help you understand how your application is performing. Learn more in the <PagesOnly>[Analytics](/docs/app/building-your-application/optimizing/analytics), </PagesOnly> [OpenTelemetry](/docs/pages/building-your-application/optimizing/open-telemetry)<PagesOnly>,</PagesOnly> and [Instrumentation](/docs/pages/building-your-application/optimizing/instrumentation) guides. +For large applications, Next.js integrates with popular analytics and monitoring tools to help you understand how your application is performing. Learn more in the <PagesOnly>[Analytics](/docs/app/guides/analytics), </PagesOnly> [OpenTelemetry](/docs/pages/guides/open-telemetry)<PagesOnly>,</PagesOnly> and [Instrumentation](/docs/pages/guides/instrumentation) guides. diff --git a/docs/01-app/05-api-reference/02-components/script.mdx b/docs/01-app/05-api-reference/02-components/script.mdx index e0889195ad7d5..7027549c45b39 100644 --- a/docs/01-app/05-api-reference/02-components/script.mdx +++ b/docs/01-app/05-api-reference/02-components/script.mdx @@ -5,7 +5,7 @@ description: Optimize third-party scripts in your Next.js application using the -This API reference will help you understand how to use [props](#props) available for the Script Component. For features and usage, please see the [Optimizing Scripts](/docs/app/building-your-application/optimizing/scripts) page. +This API reference will help you understand how to use [props](#props) available for the Script Component. For features and usage, please see the [Optimizing Scripts](/docs/app/guides/scripts) page. ```tsx filename="app/dashboard/page.tsx" switcher import Script from 'next/script' diff --git a/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx b/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx index 8242c91c57be1..91945946be977 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/instrumentation-client.mdx @@ -9,7 +9,7 @@ To use it, place the file in the **root** of your application or inside a `src` ## Usage -Unlike [server-side instrumentation](/docs/app/building-your-application/optimizing/instrumentation), you do not need to export any specific functions. You can write your monitoring code directly in the file: +Unlike [server-side instrumentation](/docs/app/guides/instrumentation), you do not need to export any specific functions. You can write your monitoring code directly in the file: ```ts filename="instrumentation-client.ts" switcher // Set up performance monitoring diff --git a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx index be35961615758..88522f1767d0f 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx @@ -4,7 +4,7 @@ description: API reference for the instrumentation.js file. - - app/building-your-application/optimizing/instrumentation + - app/guides/instrumentation The `instrumentation.js|ts` file is used to integrate observability tools into your application, allowing you to track the performance and behavior, and to debug issues in production. diff --git a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx index 3820aa4e4e257..ab1d590cbbbf2 100644 --- a/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx +++ b/docs/01-app/05-api-reference/04-functions/generate-metadata.mdx @@ -1047,7 +1047,7 @@ The following metadata types do not currently have built-in support. However, th | `<base>` | Render the tag in the layout or page itself. | | `<noscript>` | Render the tag in the layout or page itself. | | `<style>` | Learn more about [styling in Next.js](/docs/app/building-your-application/styling/css). | -| `<script>` | Learn more about [using scripts](/docs/app/building-your-application/optimizing/scripts). | +| `<script>` | Learn more about [using scripts](/docs/app/guides/scripts). | | `<link rel="stylesheet" />` | `import` stylesheets directly in the layout or page itself. | | `<link rel="preload />` | Use [ReactDOM preload method](#link-relpreload) | | `<link rel="preconnect" />` | Use [ReactDOM preconnect method](#link-relpreconnect) | diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx index 47121b85b8363..160c53b7b1ba8 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/crossOrigin.mdx @@ -5,7 +5,7 @@ description: Use the `crossOrigin` option to add a crossOrigin tag on the `scrip -Use the `crossOrigin` option to add a [`crossOrigin` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) in all `<script>` tags generated by the <AppOnly>[`next/script`](/docs/app/building-your-application/optimizing/scripts) component</AppOnly> <PagesOnly>[`next/script`](/docs/pages/building-your-application/optimizing/scripts) and [`next/head`](/docs/pages/api-reference/components/head)components</PagesOnly>, and define how cross-origin requests should be handled. ```js filename="next.config.js" module.exports = { diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx index 682c89aa23864..fe87768a68c30 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/pageExtensions.mdx @@ -35,7 +35,7 @@ module.exports = { Changing these values affects _all_ Next.js pages, including the following: - [`middleware.js`](/docs/pages/building-your-application/routing/middleware) -- [`instrumentation.js`](/docs/pages/building-your-application/optimizing/instrumentation) +- [`instrumentation.js`](/docs/pages/guides/instrumentation) - `pages/_document.js` - `pages/_app.js` - `pages/api/` diff --git a/docs/02-pages/03-building-your-application/05-optimizing/07-analytics.mdx b/docs/02-pages/02-guides/analytics.mdx similarity index 68% rename from docs/02-pages/03-building-your-application/05-optimizing/07-analytics.mdx rename to docs/02-pages/02-guides/analytics.mdx index 1a53e5a59bf73..a43f65cb5a9c5 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/07-analytics.mdx +++ b/docs/02-pages/02-guides/analytics.mdx -description: Measure and track page performance using Next.js Speed Insights -source: app/building-your-application/optimizing/analytics +title: How to set up analytics +description: Measure and track page performance using Next.js +source: app/guides/analytics diff --git a/docs/02-pages/03-building-your-application/05-optimizing/09-instrumentation.mdx b/docs/02-pages/02-guides/instrumentation.mdx similarity index 81% rename from docs/02-pages/03-building-your-application/05-optimizing/09-instrumentation.mdx rename to docs/02-pages/02-guides/instrumentation.mdx index cb2aae5e2a151..9ff275d1a6f18 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/09-instrumentation.mdx +++ b/docs/02-pages/02-guides/instrumentation.mdx +source: app/guides/instrumentation diff --git a/docs/02-pages/03-building-your-application/05-optimizing/08-lazy-loading.mdx b/docs/02-pages/02-guides/lazy-loading.mdx similarity index 80% rename from docs/02-pages/03-building-your-application/05-optimizing/08-lazy-loading.mdx rename to docs/02-pages/02-guides/lazy-loading.mdx index f78374e9db239..bdb3065506241 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/08-lazy-loading.mdx +++ b/docs/02-pages/02-guides/lazy-loading.mdx description: Lazy load imported libraries and React Components to improve your application's overall loading performance. -source: app/building-your-application/optimizing/lazy-loading +source: app/guides/lazy-loading diff --git a/docs/02-pages/03-building-your-application/05-optimizing/10-open-telemetry.mdx b/docs/02-pages/02-guides/open-telemetry.mdx similarity index 77% rename from docs/02-pages/03-building-your-application/05-optimizing/10-open-telemetry.mdx rename to docs/02-pages/02-guides/open-telemetry.mdx index 0c3d0b505720c..84c6d14a5cb09 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/10-open-telemetry.mdx +++ b/docs/02-pages/02-guides/open-telemetry.mdx +title: How to instrument your Next.js app with OpenTelemetry -source: app/building-your-application/optimizing/open-telemetry +source: app/guides/open-telemetry diff --git a/docs/02-pages/03-building-your-application/05-optimizing/06-package-bundling.mdx b/docs/02-pages/02-guides/package-bundling.mdx rename from docs/02-pages/03-building-your-application/05-optimizing/06-package-bundling.mdx rename to docs/02-pages/02-guides/package-bundling.mdx index b2ba7dd2af64f..9c35d04697845 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/06-package-bundling.mdx +++ b/docs/02-pages/02-guides/package-bundling.mdx -title: Optimizing Bundling -nav_title: Bundling +nav_title: Package Bundling -source: app/building-your-application/optimizing/package-bundling +source: app/guides/package-bundling description: Learn more about optimizing your application for production. diff --git a/docs/02-pages/03-building-your-application/05-optimizing/03-scripts.mdx b/docs/02-pages/02-guides/scripts.mdx rename from docs/02-pages/03-building-your-application/05-optimizing/03-scripts.mdx rename to docs/02-pages/02-guides/scripts.mdx index 1609a617fb8d9..e1579efc014eb 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/03-scripts.mdx +++ b/docs/02-pages/02-guides/scripts.mdx -source: app/building-your-application/optimizing/scripts +source: app/guides/scripts diff --git a/docs/02-pages/03-building-your-application/05-optimizing/11-third-party-libraries.mdx b/docs/02-pages/02-guides/third-party-libraries.mdx similarity index 79% rename from docs/02-pages/03-building-your-application/05-optimizing/11-third-party-libraries.mdx rename to docs/02-pages/02-guides/third-party-libraries.mdx index 0ca3a1ece15dc..48a5b97f67cb2 100644 --- a/docs/02-pages/03-building-your-application/05-optimizing/11-third-party-libraries.mdx +++ b/docs/02-pages/02-guides/third-party-libraries.mdx -source: app/building-your-application/optimizing/third-party-libraries +source: app/guides/third-party-libraries diff --git a/docs/02-pages/04-api-reference/01-components/head.mdx b/docs/02-pages/04-api-reference/01-components/head.mdx index d34dc48310ee4..be5ac7ec981bf 100644 --- a/docs/02-pages/04-api-reference/01-components/head.mdx +++ b/docs/02-pages/04-api-reference/01-components/head.mdx @@ -60,7 +60,7 @@ or wrapped into maximum one level of `<React.Fragment>` or arrays—otherwise th ## Use `next/script` for scripts -We recommend using [`next/script`](/docs/pages/building-your-application/optimizing/scripts) in your component instead of manually creating a `<script>` in `next/head`. +We recommend using [`next/script`](/docs/pages/guides/scripts) in your component instead of manually creating a `<script>` in `next/head`. ## No `html` or `body` tags diff --git a/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx b/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx index c5d15324d50e1..a547329f3d4ac 100644 --- a/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx +++ b/docs/02-pages/04-api-reference/04-config/01-next-config-js/runtime-configuration.mdx @@ -6,7 +6,7 @@ description: Add client and server runtime configuration to your Next.js app. > **Warning:** > - **This feature is deprecated.** We recommend using [environment variables](/docs/pages/guides/environment-variables) instead, which also can support reading runtime values. > - This feature does not work with [Automatic Static Optimization](/docs/pages/building-your-application/rendering/automatic-static-optimization), [Output File Tracing](/docs/pages/api-reference/config/next-config-js/output#automatically-copying-traced-files), or [React Server Components](/docs/app/building-your-application/rendering/server-components). To add runtime configuration to your app, open `next.config.js` and add the `publicRuntimeConfig` and `serverRuntimeConfig` configs: diff --git a/errors/inline-script-id.mdx b/errors/inline-script-id.mdx index ba15bf31363ee..94e06d97b6ca0 100644 --- a/errors/inline-script-id.mdx +++ b/errors/inline-script-id.mdx @@ -27,4 +27,4 @@ export default function App({ Component, pageProps }) { ## Useful links -- [Docs for Next.js Script component](/docs/pages/building-your-application/optimizing/scripts) +- [Docs for Next.js Script component](/docs/pages/guides/scripts) diff --git a/errors/invalid-dynamic-options-type.mdx b/errors/invalid-dynamic-options-type.mdx index f6fe20caaafe0..5610b51ab0c5c 100644 --- a/errors/invalid-dynamic-options-type.mdx +++ b/errors/invalid-dynamic-options-type.mdx @@ -30,4 +30,4 @@ const DynamicComponent = dynamic(() => import('../components/hello'), { -- [Dynamic Import](/docs/pages/building-your-application/optimizing/lazy-loading) +- [Dynamic Import](/docs/pages/guides/lazy-loading) diff --git a/errors/invalid-dynamic-suspense.mdx b/errors/invalid-dynamic-suspense.mdx index 0785dc7356245..09b18abd8889b 100644 --- a/errors/invalid-dynamic-suspense.mdx +++ b/errors/invalid-dynamic-suspense.mdx @@ -30,4 +30,4 @@ You should remove `loading` from `next/dynamic` usages, and use `<Suspense />`'s -- [Dynamic Import Suspense Usage](/docs/pages/building-your-application/optimizing/lazy-loading#nextdynamic) +- [Dynamic Import Suspense Usage](/docs/pages/guides/lazy-loading#nextdynamic) diff --git a/errors/invalid-script.mdx b/errors/invalid-script.mdx index 18806b1fa6b19..70495b0e376ec 100644 --- a/errors/invalid-script.mdx +++ b/errors/invalid-script.mdx @@ -37,4 +37,4 @@ Look for any usage of the `next/script` component and make sure that `src` is pr -- [Script Component in Documentation](/docs/pages/building-your-application/optimizing/scripts) +- [Script Component in Documentation](/docs/pages/guides/scripts) diff --git a/errors/next-script-for-ga.mdx b/errors/next-script-for-ga.mdx index 6c86d2497e3a1..55292193558ff 100644 --- a/errors/next-script-for-ga.mdx +++ b/errors/next-script-for-ga.mdx @@ -65,11 +65,11 @@ export default function Page() { -> - If you are using the Pages Router, please refer to the [`pages/` documentation](/docs/pages/building-your-application/optimizing/third-party-libraries). -> - `@next/third-parties` also supports [Google Tag Manager](/docs/app/building-your-application/optimizing/third-party-libraries#google-tag-manager) and other third parties. -> - Using `@next/third-parties` is not required. You can also use the `next/script` component directly. Refer to the [`next/script` documentation](/docs/app/building-your-application/optimizing/scripts) to learn more. +> - If you are using the Pages Router, please refer to the [`pages/` documentation](/docs/pages/guides/third-party-libraries). +> - `@next/third-parties` also supports [Google Tag Manager](/docs/app/guides/third-party-libraries#google-tag-manager) and other third parties. -- [`next/script` Documentation](/docs/app/building-your-application/optimizing/scripts) +- [`next/script` Documentation](/docs/app/guides/scripts) diff --git a/errors/no-before-interactive-script-outside-document.mdx b/errors/no-before-interactive-script-outside-document.mdx index c939ade1a8113..68965e6758d64 100644 --- a/errors/no-before-interactive-script-outside-document.mdx +++ b/errors/no-before-interactive-script-outside-document.mdx @@ -57,5 +57,5 @@ export default function Document() { -- [App Router Script Optimization](/docs/app/building-your-application/optimizing/scripts) -- [Pages Router Script Optimization](/docs/pages/building-your-application/optimizing/scripts) +- [App Router Script Optimization](/docs/app/guides/scripts) +- [Pages Router Script Optimization](/docs/pages/guides/scripts) diff --git a/errors/no-script-component-in-head.mdx b/errors/no-script-component-in-head.mdx index 5d0709fa81ebf..6bb790ab89a3e 100644 --- a/errors/no-script-component-in-head.mdx +++ b/errors/no-script-component-in-head.mdx @@ -49,4 +49,4 @@ export default function Index() { - [next/head](/docs/pages/api-reference/components/head) -- [next/script](/docs/pages/building-your-application/optimizing/scripts) +- [next/script](/docs/pages/guides/scripts) diff --git a/errors/no-script-in-document.mdx b/errors/no-script-in-document.mdx index f0dd04c3e759e..2831d614117e4 100644 --- a/errors/no-script-in-document.mdx +++ b/errors/no-script-in-document.mdx @@ -32,4 +32,4 @@ export default MyApp - [custom-app](/docs/pages/building-your-application/routing/custom-app) -- [next-script](/docs/pages/building-your-application/optimizing/scripts) +- [next-script](/docs/pages/guides/scripts) diff --git a/errors/no-script-tags-in-head-component.mdx b/errors/no-script-tags-in-head-component.mdx index bbdd837ad98f2..71763c23f683d 100644 --- a/errors/no-script-tags-in-head-component.mdx +++ b/errors/no-script-tags-in-head-component.mdx @@ -28,5 +28,5 @@ export default function Dashboard() { -- [Optimizing Scripts](/docs/pages/building-your-application/optimizing/scripts) +- [Optimizing Scripts](/docs/pages/guides/scripts) - [`next/script` API Reference](/docs/pages/api-reference/components/script) diff --git a/errors/react-hydration-error.mdx b/errors/react-hydration-error.mdx index e1c5e12ff2cf8..594139089fbdb 100644 --- a/errors/react-hydration-error.mdx +++ b/errors/react-hydration-error.mdx @@ -51,7 +51,7 @@ During React hydration, `useEffect` is called. This means browser APIs like `win ### Solution 2: Disabling SSR on specific components -Next.js allows you to [disable prerendering](/docs/app/building-your-application/optimizing/lazy-loading#skipping-ssr) on specific components, which can prevent hydration mismatches. +Next.js allows you to [disable prerendering](/docs/app/guides/lazy-loading#skipping-ssr) on specific components, which can prevent hydration mismatches.
[ "-| | |", "-| `next-env.d.ts` | TypeScript declaration file for Next.js |", "+| [`.env.development`](/docs/app/guides/environment-variables) | Development environment variables |", "-The way you import code can greatly affect compilation and bundling time. Learn more about [optimizing package bundling](/docs/app/building-your-application/optimizing/package-bundling) and explore tools like [Dependency Cruiser](https://github.com/sverweij/dependency-cruiser) or [Madge](https://github.com/pahen/madge).", "+The way you import code can greatly affect compilation and bundling time. Learn more about [optimizing package bundling](/docs/app/guides/package-bundling) and explore tools like [Dependency Cruiser](https://github.com/sverweij/dependency-cruiser) or [Madge](https://github.com/pahen/madge).", "-[Learn more about optimizing memory usage](/docs/app/building-your-application/optimizing/memory-usage).", "+Use the `crossOrigin` option to add a [`crossOrigin` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) in all `<script>` tags generated by the <AppOnly>[`next/script`](/docs/app/guides/scripts) component</AppOnly> <PagesOnly>[`next/script`](/docs/pages/guides/scripts) and [`next/head`](/docs/pages/api-reference/components/head)components</PagesOnly>, and define how cross-origin requests should be handled.", "-source: app/building-your-application/optimizing/instrumentation", "+> - Using `@next/third-parties` is not required. You can also use the `next/script` component directly. Refer to the [`next/script` documentation](/docs/app/guides/scripts) to learn more.", "-- [`@next/third-parties` Documentation](/docs/app/building-your-application/optimizing/third-party-libraries)", "+- [`@next/third-parties` Documentation](/docs/app/guides/third-party-libraries)" ]
[ 8, 21, 34, 127, 128, 136, 467, 516, 691, 695, 697 ]
{ "additions": 102, "author": "delbaoliveira", "deletions": 86, "html_url": "https://github.com/vercel/next.js/pull/78500", "issue_id": 78500, "merged_at": "2025-04-24T18:40:55Z", "omission_probability": 0.1, "pr_number": 78500, "repo": "vercel/next.js", "title": "Docs IA 2.0: Move optimizing pages to guides", "total_changes": 188 }
326
diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts index 2b0ca1a8d2c47..9f6251c3212de 100644 --- a/packages/next/src/server/base-server.ts +++ b/packages/next/src/server/base-server.ts @@ -1720,9 +1720,11 @@ export default abstract class Server< public async prepare(): Promise<void> { if (this.prepared) return - if (this.preparedPromise === null) { - // Get instrumentation module + // Get instrumentation module + if (!this.instrumentation) { this.instrumentation = await this.loadInstrumentationModule() + } + if (this.preparedPromise === null) { this.preparedPromise = this.prepareImpl().then(() => { this.prepared = true this.preparedPromise = null diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index 26111cccc049d..f0b47dd480b72 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -376,6 +376,9 @@ export default class NextNodeServer extends BaseServer< } public async unstable_preloadEntries(): Promise<void> { + // Ensure prepare process will be finished before preloading entries. + await this.prepare() + const appPathsManifest = this.getAppPathsManifest() const pagesManifest = this.getPagesManifest() diff --git a/test/e2e/app-dir/instrumentation-order/app/layout.tsx b/test/e2e/app-dir/instrumentation-order/app/layout.tsx new file mode 100644 index 0000000000000..888614deda3ba --- /dev/null +++ b/test/e2e/app-dir/instrumentation-order/app/layout.tsx @@ -0,0 +1,8 @@ +import { ReactNode } from 'react' +export default function Root({ children }: { children: ReactNode }) { + return ( + <html> + <body>{children}</body> + </html> + ) +} diff --git a/test/e2e/app-dir/instrumentation-order/app/page.tsx b/test/e2e/app-dir/instrumentation-order/app/page.tsx new file mode 100644 index 0000000000000..0c7fea30c72f5 --- /dev/null +++ b/test/e2e/app-dir/instrumentation-order/app/page.tsx @@ -0,0 +1,8 @@ +import { connection } from 'next/server' + +console.log('global-side-effect:app-router-page') + +export default async function Page() { + await connection() + return <p>hello world</p> +} diff --git a/test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts b/test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts new file mode 100644 index 0000000000000..6cbb44769c29f --- /dev/null +++ b/test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts @@ -0,0 +1,35 @@ +import { nextTestSetup } from 'e2e-utils' +import { waitFor } from 'next-test-utils' + +const ORDERED_LOGS = [ + 'instrumentation:side-effect', + 'instrumentation:register:begin', + 'instrumentation:register:timeout', + 'instrumentation:register:end', + 'global-side-effect:app-router-page', +] + +describe('instrumentation-order', () => { + const { next, isNextDev } = nextTestSetup({ + files: __dirname, + skipDeployment: true, + }) + + it('should work using cheerio', async () => { + // Wait for the timeout in the instrumentation to complete + await waitFor(500) + + // Dev mode requires to render the page to trigger the build of the page + if (isNextDev) { + await next.render$('/') + } + + const serverLog = next.cliOutput.split('Starting...')[1] + const cliOutputLines = serverLog.split('\n') + const searchedLines = cliOutputLines.filter((line) => + ORDERED_LOGS.includes(line.trim()) + ) + + expect(searchedLines).toEqual(ORDERED_LOGS) + }) +}) diff --git a/test/e2e/app-dir/instrumentation-order/instrumentation.ts b/test/e2e/app-dir/instrumentation-order/instrumentation.ts new file mode 100644 index 0000000000000..daf1a12de8aa6 --- /dev/null +++ b/test/e2e/app-dir/instrumentation-order/instrumentation.ts @@ -0,0 +1,12 @@ +console.log('instrumentation:side-effect') + +export async function register() { + console.log('instrumentation:register:begin') + await new Promise((resolve) => { + setTimeout(() => { + console.log('instrumentation:register:timeout') + resolve(true) + }, 300) + }) + console.log('instrumentation:register:end') +} diff --git a/test/e2e/app-dir/instrumentation-order/next.config.js b/test/e2e/app-dir/instrumentation-order/next.config.js new file mode 100644 index 0000000000000..807126e4cf0bf --- /dev/null +++ b/test/e2e/app-dir/instrumentation-order/next.config.js @@ -0,0 +1,6 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = {} + +module.exports = nextConfig
diff --git a/packages/next/src/server/base-server.ts b/packages/next/src/server/base-server.ts index 2b0ca1a8d2c47..9f6251c3212de 100644 --- a/packages/next/src/server/base-server.ts +++ b/packages/next/src/server/base-server.ts @@ -1720,9 +1720,11 @@ export default abstract class Server< public async prepare(): Promise<void> { if (this.prepared) return - // Get instrumentation module + // Get instrumentation module + if (!this.instrumentation) { this.instrumentation = await this.loadInstrumentationModule() + if (this.preparedPromise === null) { this.preparedPromise = this.prepareImpl().then(() => { this.prepared = true this.preparedPromise = null diff --git a/packages/next/src/server/next-server.ts b/packages/next/src/server/next-server.ts index 26111cccc049d..f0b47dd480b72 100644 --- a/packages/next/src/server/next-server.ts +++ b/packages/next/src/server/next-server.ts @@ -376,6 +376,9 @@ export default class NextNodeServer extends BaseServer< } public async unstable_preloadEntries(): Promise<void> { + // Ensure prepare process will be finished before preloading entries. + await this.prepare() const appPathsManifest = this.getAppPathsManifest() const pagesManifest = this.getPagesManifest() diff --git a/test/e2e/app-dir/instrumentation-order/app/layout.tsx b/test/e2e/app-dir/instrumentation-order/app/layout.tsx index 0000000000000..888614deda3ba +++ b/test/e2e/app-dir/instrumentation-order/app/layout.tsx +import { ReactNode } from 'react' +export default function Root({ children }: { children: ReactNode }) { + return ( + <html> + <body>{children}</body> + </html> + ) diff --git a/test/e2e/app-dir/instrumentation-order/app/page.tsx b/test/e2e/app-dir/instrumentation-order/app/page.tsx index 0000000000000..0c7fea30c72f5 +++ b/test/e2e/app-dir/instrumentation-order/app/page.tsx +import { connection } from 'next/server' +console.log('global-side-effect:app-router-page') + await connection() + return <p>hello world</p> diff --git a/test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts b/test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts index 0000000000000..6cbb44769c29f +++ b/test/e2e/app-dir/instrumentation-order/instrumentation-order.test.ts @@ -0,0 +1,35 @@ +import { nextTestSetup } from 'e2e-utils' +import { waitFor } from 'next-test-utils' + 'instrumentation:register:begin', + 'instrumentation:register:timeout', + 'instrumentation:register:end', + 'global-side-effect:app-router-page', +] +describe('instrumentation-order', () => { + const { next, isNextDev } = nextTestSetup({ + files: __dirname, + skipDeployment: true, + it('should work using cheerio', async () => { + await waitFor(500) + // Dev mode requires to render the page to trigger the build of the page + if (isNextDev) { + await next.render$('/') + const serverLog = next.cliOutput.split('Starting...')[1] + const cliOutputLines = serverLog.split('\n') + const searchedLines = cliOutputLines.filter((line) => + ORDERED_LOGS.includes(line.trim()) + ) + expect(searchedLines).toEqual(ORDERED_LOGS) diff --git a/test/e2e/app-dir/instrumentation-order/instrumentation.ts b/test/e2e/app-dir/instrumentation-order/instrumentation.ts index 0000000000000..daf1a12de8aa6 +++ b/test/e2e/app-dir/instrumentation-order/instrumentation.ts @@ -0,0 +1,12 @@ +console.log('instrumentation:side-effect') +export async function register() { + console.log('instrumentation:register:begin') + await new Promise((resolve) => { + setTimeout(() => { + console.log('instrumentation:register:timeout') + resolve(true) + }, 300) + console.log('instrumentation:register:end') diff --git a/test/e2e/app-dir/instrumentation-order/next.config.js b/test/e2e/app-dir/instrumentation-order/next.config.js index 0000000000000..807126e4cf0bf +++ b/test/e2e/app-dir/instrumentation-order/next.config.js @@ -0,0 +1,6 @@ +/** + * @type {import('next').NextConfig} +const nextConfig = {} +module.exports = nextConfig
[ "- if (this.preparedPromise === null) {", "+export default async function Page() {", "+const ORDERED_LOGS = [", "+ 'instrumentation:side-effect',", "+ // Wait for the timeout in the instrumentation to complete", "+})", "+ */" ]
[ 8, 56, 69, 70, 84, 100, 127 ]
{ "additions": 76, "author": "huozhi", "deletions": 2, "html_url": "https://github.com/vercel/next.js/pull/78454", "issue_id": 78454, "merged_at": "2025-04-24T17:59:45Z", "omission_probability": 0.1, "pr_number": 78454, "repo": "vercel/next.js", "title": "[next-server] ensure prepare is done before preloading entry", "total_changes": 78 }
327
diff --git a/docs/01-app/01-getting-started/01-installation.mdx b/docs/01-app/01-getting-started/01-installation.mdx index cb9b84d437a19..3654e5c296c0e 100644 --- a/docs/01-app/01-getting-started/01-installation.mdx +++ b/docs/01-app/01-getting-started/01-installation.mdx @@ -124,7 +124,7 @@ Both `layout.tsx` and `page.tsx` will be rendered when the user visits the root > **Good to know**: > > - If you forget to create the root layout, Next.js will automatically create this file when running the development server with `next dev`. -> - You can optionally use a [`src` directory](/docs/app/building-your-application/configuring/src-directory) in the root of your project to separate your application's code from configuration files. +> - You can optionally use a [`src` folder](/docs/app/api-reference/file-conventions/src-folder) in the root of your project to separate your application's code from configuration files. </AppOnly> diff --git a/docs/01-app/01-getting-started/02-project-structure.mdx b/docs/01-app/01-getting-started/02-project-structure.mdx index 8ce4d11e1ecfd..085745f2137d4 100644 --- a/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/docs/01-app/01-getting-started/02-project-structure.mdx @@ -25,7 +25,7 @@ Top-level folders are used to organize your application's code and static assets | [`app`](/docs/app/building-your-application/routing) | App Router | | [`pages`](/docs/pages/building-your-application/routing) | Pages Router | | [`public`](/docs/app/building-your-application/optimizing/static-assets) | Static assets to be served | -| [`src`](/docs/app/building-your-application/configuring/src-directory) | Optional application source folder | +| [`src`](/docs/app/api-reference/file-conventions/src-folder) | Optional application source folder | ### Top-level files @@ -285,12 +285,12 @@ Route groups are useful for: - [Creating multiple nested layouts in the same segment, including multiple root layouts](#creating-multiple-root-layouts) - [Adding a layout to a subset of routes in a common segment](#opting-specific-segments-into-a-layout) -### `src` directory +### `src` folder -Next.js supports storing application code (including `app`) inside an optional [`src` directory](/docs/app/building-your-application/configuring/src-directory). This separates application code from project configuration files which mostly live in the root of a project. +Next.js supports storing application code (including `app`) inside an optional [`src` folder](/docs/app/api-reference/file-conventions/src-folder). This separates application code from project configuration files which mostly live in the root of a project. <Image - alt="An example folder structure with the `src` directory" + alt="An example folder structure with the `src` folder" srcLight="/docs/light/project-organization-src-directory.png" srcDark="/docs/dark/project-organization-src-directory.png" width="1600" diff --git a/docs/01-app/02-guides/environment-variables.mdx b/docs/01-app/02-guides/environment-variables.mdx index 5a92b19e1013c..e6bd12e2f1943 100644 --- a/docs/01-app/02-guides/environment-variables.mdx +++ b/docs/01-app/02-guides/environment-variables.mdx @@ -282,7 +282,7 @@ For example, if `NODE_ENV` is `development` and you define a variable in both `. ## Good to know -- If you are using a [`/src` directory](/docs/app/building-your-application/configuring/src-directory), `.env.*` files should remain in the root of your project. +- If you are using a [`/src` directory](/docs/app/api-reference/file-conventions/src-folder), `.env.*` files should remain in the root of your project. - If the environment variable `NODE_ENV` is unassigned, Next.js automatically assigns `development` when running the `next dev` command, or `production` for all other commands. ## Version History diff --git a/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/docs/01-app/02-guides/migrating/from-create-react-app.mdx index 1782c3b8fb370..e7cf97f761a1c 100644 --- a/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/docs/01-app/02-guides/migrating/from-create-react-app.mdx @@ -82,7 +82,7 @@ A Next.js [App Router](/docs/app) application must include a [root layout](/docs The closest equivalent of the root layout file in a CRA application is `public/index.html`, which includes your `<html>`, `<head>`, and `<body>` tags. -1. Create a new `app` directory inside your `src` directory (or at your project root if you prefer `app` at the root). +1. Create a new `app` directory inside your `src` folder (or at your project root if you prefer `app` at the root). 2. Inside the `app` directory, create a `layout.tsx` (or `layout.js`) file: ```tsx filename="app/layout.tsx" switcher diff --git a/docs/01-app/02-guides/migrating/from-vite.mdx b/docs/01-app/02-guides/migrating/from-vite.mdx index e31b54519c7d9..7cf79078a8f34 100644 --- a/docs/01-app/02-guides/migrating/from-vite.mdx +++ b/docs/01-app/02-guides/migrating/from-vite.mdx @@ -140,7 +140,7 @@ The closest equivalent to the root layout file in a Vite application is the In this step, you'll convert your `index.html` file into a root layout file: -1. Create a new `app` directory in your `src` directory. +1. Create a new `app` directory in your `src` folder. 2. Create a new `layout.tsx` file inside that `app` directory: ```tsx filename="app/layout.tsx" switcher diff --git a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx b/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx index f4113ac6bfa0a..d4bc45bffbf2b 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx @@ -13,7 +13,7 @@ Instrumentation is the process of using code to integrate monitoring and logging ## Convention -To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/building-your-application/configuring/src-directory) folder if using one). +To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/api-reference/file-conventions/src-folder) folder if using one). Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated. diff --git a/docs/01-app/05-api-reference/03-file-conventions/index.mdx b/docs/01-app/05-api-reference/03-file-conventions/index.mdx index d98cc138c5c3f..a69df3feeee97 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/index.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/index.mdx @@ -1,4 +1,4 @@ --- -title: File Conventions -description: API Reference for Next.js File Conventions. +title: File-system conventions +description: API Reference for Next.js file-system conventions. --- diff --git a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx index 1ed59e2a32524..be35961615758 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx @@ -9,7 +9,7 @@ related: The `instrumentation.js|ts` file is used to integrate observability tools into your application, allowing you to track the performance and behavior, and to debug issues in production. -To use it, place the file in the **root** of your application or inside a [`src` folder](/docs/app/building-your-application/configuring/src-directory) if using one. +To use it, place the file in the **root** of your application or inside a [`src` folder](/docs/app/api-reference/file-conventions/src-folder) if using one. ## Exports diff --git a/docs/01-app/03-building-your-application/07-configuring/06-src-directory.mdx b/docs/01-app/05-api-reference/03-file-conventions/src-folder.mdx similarity index 80% rename from docs/01-app/03-building-your-application/07-configuring/06-src-directory.mdx rename to docs/01-app/05-api-reference/03-file-conventions/src-folder.mdx index 1a7353c7e5c35..3350189966115 100644 --- a/docs/01-app/03-building-your-application/07-configuring/06-src-directory.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/src-folder.mdx @@ -1,6 +1,7 @@ --- -title: src Directory -description: Save pages under the `src` directory as an alternative to the root `pages` directory. +title: src Folder +nav_title: src +description: Save pages under the `src` folder as an alternative to the root `pages` directory. related: links: - app/getting-started/project-structure @@ -8,14 +9,14 @@ related: {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -As an alternative to having the special Next.js `app` or `pages` directories in the root of your project, Next.js also supports the common pattern of placing application code under the `src` directory. +As an alternative to having the special Next.js `app` or `pages` directories in the root of your project, Next.js also supports the common pattern of placing application code under the `src` folder. This separates application code from project configuration files which mostly live in the root of a project, which is preferred by some individuals and teams. -To use the `src` directory, move the `app` Router folder or `pages` Router folder to `src/app` or `src/pages` respectively. +To use the `src` folder, move the `app` Router folder or `pages` Router folder to `src/app` or `src/pages` respectively. <Image - alt="An example folder structure with the `src` directory" + alt="An example folder structure with the `src` folder" srcLight="/docs/light/project-organization-src-directory.png" srcDark="/docs/dark/project-organization-src-directory.png" width="1600" @@ -29,6 +30,6 @@ To use the `src` directory, move the `app` Router folder or `pages` Router folde > - `.env.*` files should remain in the root of your project. > - `src/app` or `src/pages` will be ignored if `app` or `pages` are present in the root directory. > - If you're using `src`, you'll probably also move other application folders such as `/components` or `/lib`. -> - If you're using Middleware, ensure it is placed inside the `src` directory. +> - If you're using Middleware, ensure it is placed inside the `src` folder. > - If you're using Tailwind CSS, you'll need to add the `/src` prefix to the `tailwind.config.js` file in the [content section](https://tailwindcss.com/docs/content-configuration). > - If you are using TypeScript paths for imports such as `@/*`, you should update the `paths` object in `tsconfig.json` to include `src/`. diff --git a/docs/02-pages/04-api-reference/02-file-conventions/index.mdx b/docs/02-pages/04-api-reference/02-file-conventions/index.mdx new file mode 100644 index 0000000000000..a69df3feeee97 --- /dev/null +++ b/docs/02-pages/04-api-reference/02-file-conventions/index.mdx @@ -0,0 +1,4 @@ +--- +title: File-system conventions +description: API Reference for Next.js file-system conventions. +--- diff --git a/docs/02-pages/03-building-your-application/06-configuring/05-src-directory.mdx b/docs/02-pages/04-api-reference/02-file-conventions/src-folder.mdx similarity index 68% rename from docs/02-pages/03-building-your-application/06-configuring/05-src-directory.mdx rename to docs/02-pages/04-api-reference/02-file-conventions/src-folder.mdx index fd8ea6a7c8a72..bd76fcaa385ef 100644 --- a/docs/02-pages/03-building-your-application/06-configuring/05-src-directory.mdx +++ b/docs/02-pages/04-api-reference/02-file-conventions/src-folder.mdx @@ -1,7 +1,7 @@ --- title: src Directory -description: Save pages under the `src` directory as an alternative to the root `pages` directory. -source: app/building-your-application/configuring/src-directory +description: Save pages under the `src` folder as an alternative to the root `pages` directory. +source: app/api-reference/file-conventions/src-folder --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
diff --git a/docs/01-app/01-getting-started/01-installation.mdx b/docs/01-app/01-getting-started/01-installation.mdx index cb9b84d437a19..3654e5c296c0e 100644 --- a/docs/01-app/01-getting-started/01-installation.mdx +++ b/docs/01-app/01-getting-started/01-installation.mdx @@ -124,7 +124,7 @@ Both `layout.tsx` and `page.tsx` will be rendered when the user visits the root > **Good to know**: > > - If you forget to create the root layout, Next.js will automatically create this file when running the development server with `next dev`. -> - You can optionally use a [`src` directory](/docs/app/building-your-application/configuring/src-directory) in the root of your project to separate your application's code from configuration files. </AppOnly> diff --git a/docs/01-app/01-getting-started/02-project-structure.mdx b/docs/01-app/01-getting-started/02-project-structure.mdx index 8ce4d11e1ecfd..085745f2137d4 100644 --- a/docs/01-app/01-getting-started/02-project-structure.mdx +++ b/docs/01-app/01-getting-started/02-project-structure.mdx @@ -25,7 +25,7 @@ Top-level folders are used to organize your application's code and static assets | [`app`](/docs/app/building-your-application/routing) | App Router | | [`pages`](/docs/pages/building-your-application/routing) | Pages Router | | [`public`](/docs/app/building-your-application/optimizing/static-assets) | Static assets to be served | -| [`src`](/docs/app/building-your-application/configuring/src-directory) | Optional application source folder | +| [`src`](/docs/app/api-reference/file-conventions/src-folder) | Optional application source folder | ### Top-level files @@ -285,12 +285,12 @@ Route groups are useful for: - [Creating multiple nested layouts in the same segment, including multiple root layouts](#creating-multiple-root-layouts) - [Adding a layout to a subset of routes in a common segment](#opting-specific-segments-into-a-layout) +### `src` folder -Next.js supports storing application code (including `app`) inside an optional [`src` directory](/docs/app/building-your-application/configuring/src-directory). This separates application code from project configuration files which mostly live in the root of a project. diff --git a/docs/01-app/02-guides/environment-variables.mdx b/docs/01-app/02-guides/environment-variables.mdx index 5a92b19e1013c..e6bd12e2f1943 100644 --- a/docs/01-app/02-guides/environment-variables.mdx +++ b/docs/01-app/02-guides/environment-variables.mdx @@ -282,7 +282,7 @@ For example, if `NODE_ENV` is `development` and you define a variable in both `. ## Good to know -- If you are using a [`/src` directory](/docs/app/building-your-application/configuring/src-directory), `.env.*` files should remain in the root of your project. +- If you are using a [`/src` directory](/docs/app/api-reference/file-conventions/src-folder), `.env.*` files should remain in the root of your project. - If the environment variable `NODE_ENV` is unassigned, Next.js automatically assigns `development` when running the `next dev` command, or `production` for all other commands. ## Version History diff --git a/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/docs/01-app/02-guides/migrating/from-create-react-app.mdx index 1782c3b8fb370..e7cf97f761a1c 100644 --- a/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/docs/01-app/02-guides/migrating/from-create-react-app.mdx @@ -82,7 +82,7 @@ A Next.js [App Router](/docs/app) application must include a [root layout](/docs The closest equivalent of the root layout file in a CRA application is `public/index.html`, which includes your `<html>`, `<head>`, and `<body>` tags. -1. Create a new `app` directory inside your `src` directory (or at your project root if you prefer `app` at the root). 2. Inside the `app` directory, create a `layout.tsx` (or `layout.js`) file: diff --git a/docs/01-app/02-guides/migrating/from-vite.mdx b/docs/01-app/02-guides/migrating/from-vite.mdx index e31b54519c7d9..7cf79078a8f34 100644 --- a/docs/01-app/02-guides/migrating/from-vite.mdx +++ b/docs/01-app/02-guides/migrating/from-vite.mdx @@ -140,7 +140,7 @@ The closest equivalent to the root layout file in a Vite application is the In this step, you'll convert your `index.html` file into a root layout file: -1. Create a new `app` directory in your `src` directory. +1. Create a new `app` directory in your `src` folder. 2. Create a new `layout.tsx` file inside that `app` directory: diff --git a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx b/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx index f4113ac6bfa0a..d4bc45bffbf2b 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/09-instrumentation.mdx @@ -13,7 +13,7 @@ Instrumentation is the process of using code to integrate monitoring and logging ## Convention -To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/building-your-application/configuring/src-directory) folder if using one). +To set up instrumentation, create `instrumentation.ts|js` file in the **root directory** of your project (or inside the [`src`](/docs/app/api-reference/file-conventions/src-folder) folder if using one). Then, export a `register` function in the file. This function will be called **once** when a new Next.js server instance is initiated. diff --git a/docs/01-app/05-api-reference/03-file-conventions/index.mdx b/docs/01-app/05-api-reference/03-file-conventions/index.mdx index d98cc138c5c3f..a69df3feeee97 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/index.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/index.mdx @@ -1,4 +1,4 @@ -title: File Conventions -description: API Reference for Next.js File Conventions. diff --git a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx index 1ed59e2a32524..be35961615758 100644 --- a/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/instrumentation.mdx @@ -9,7 +9,7 @@ related: The `instrumentation.js|ts` file is used to integrate observability tools into your application, allowing you to track the performance and behavior, and to debug issues in production. -To use it, place the file in the **root** of your application or inside a [`src` folder](/docs/app/building-your-application/configuring/src-directory) if using one. +To use it, place the file in the **root** of your application or inside a [`src` folder](/docs/app/api-reference/file-conventions/src-folder) if using one. ## Exports diff --git a/docs/01-app/03-building-your-application/07-configuring/06-src-directory.mdx b/docs/01-app/05-api-reference/03-file-conventions/src-folder.mdx similarity index 80% rename from docs/01-app/03-building-your-application/07-configuring/06-src-directory.mdx rename to docs/01-app/05-api-reference/03-file-conventions/src-folder.mdx index 1a7353c7e5c35..3350189966115 100644 --- a/docs/01-app/03-building-your-application/07-configuring/06-src-directory.mdx +++ b/docs/01-app/05-api-reference/03-file-conventions/src-folder.mdx @@ -1,6 +1,7 @@ -title: src Directory +title: src Folder +nav_title: src related: links: - app/getting-started/project-structure @@ -8,14 +9,14 @@ related: {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -As an alternative to having the special Next.js `app` or `pages` directories in the root of your project, Next.js also supports the common pattern of placing application code under the `src` directory. This separates application code from project configuration files which mostly live in the root of a project, which is preferred by some individuals and teams. -To use the `src` directory, move the `app` Router folder or `pages` Router folder to `src/app` or `src/pages` respectively. +To use the `src` folder, move the `app` Router folder or `pages` Router folder to `src/app` or `src/pages` respectively. @@ -29,6 +30,6 @@ To use the `src` directory, move the `app` Router folder or `pages` Router folde > - `.env.*` files should remain in the root of your project. > - `src/app` or `src/pages` will be ignored if `app` or `pages` are present in the root directory. > - If you're using `src`, you'll probably also move other application folders such as `/components` or `/lib`. -> - If you're using Middleware, ensure it is placed inside the `src` directory. +> - If you're using Middleware, ensure it is placed inside the `src` folder. > - If you're using Tailwind CSS, you'll need to add the `/src` prefix to the `tailwind.config.js` file in the [content section](https://tailwindcss.com/docs/content-configuration). > - If you are using TypeScript paths for imports such as `@/*`, you should update the `paths` object in `tsconfig.json` to include `src/`. diff --git a/docs/02-pages/04-api-reference/02-file-conventions/index.mdx b/docs/02-pages/04-api-reference/02-file-conventions/index.mdx new file mode 100644 index 0000000000000..a69df3feeee97 --- /dev/null +++ b/docs/02-pages/04-api-reference/02-file-conventions/index.mdx @@ -0,0 +1,4 @@ diff --git a/docs/02-pages/03-building-your-application/06-configuring/05-src-directory.mdx b/docs/02-pages/04-api-reference/02-file-conventions/src-folder.mdx similarity index 68% rename from docs/02-pages/03-building-your-application/06-configuring/05-src-directory.mdx rename to docs/02-pages/04-api-reference/02-file-conventions/src-folder.mdx index fd8ea6a7c8a72..bd76fcaa385ef 100644 --- a/docs/02-pages/03-building-your-application/06-configuring/05-src-directory.mdx +++ b/docs/02-pages/04-api-reference/02-file-conventions/src-folder.mdx @@ -1,7 +1,7 @@ title: src Directory -source: app/building-your-application/configuring/src-directory +source: app/api-reference/file-conventions/src-folder {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
[ "+> - You can optionally use a [`src` folder](/docs/app/api-reference/file-conventions/src-folder) in the root of your project to separate your application's code from configuration files.", "-### `src` directory", "+Next.js supports storing application code (including `app`) inside an optional [`src` folder](/docs/app/api-reference/file-conventions/src-folder). This separates application code from project configuration files which mostly live in the root of a project.", "+1. Create a new `app` directory inside your `src` folder (or at your project root if you prefer `app` at the root).", "+As an alternative to having the special Next.js `app` or `pages` directories in the root of your project, Next.js also supports the common pattern of placing application code under the `src` folder." ]
[ 9, 30, 34, 64, 140 ]
{ "additions": 25, "author": "delbaoliveira", "deletions": 20, "html_url": "https://github.com/vercel/next.js/pull/78499", "issue_id": 78499, "merged_at": "2025-04-24T13:34:05Z", "omission_probability": 0.1, "pr_number": 78499, "repo": "vercel/next.js", "title": "Docs IA 2.0: Move `src` folder page to API reference", "total_changes": 45 }
328
diff --git a/crates/next-core/src/next_import_map.rs b/crates/next-core/src/next_import_map.rs index cf9bc88bcaadb..937dc1cd58cdc 100644 --- a/crates/next-core/src/next_import_map.rs +++ b/crates/next-core/src/next_import_map.rs @@ -196,19 +196,23 @@ pub async fn get_next_client_import_map( &format!("next/dist/compiled/react-server-dom-turbopack{react_flavor}/*"), ), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/head", request_to_import_mapping(project_path, "next/dist/client/components/noop-head"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/dynamic", request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/link", request_to_import_mapping(project_path, "next/dist/client/app-dir/link"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/form", request_to_import_mapping(project_path, "next/dist/client/app-dir/form"), ); @@ -337,19 +341,23 @@ pub async fn get_next_server_import_map( ServerContextType::AppSSR { .. } | ServerContextType::AppRSC { .. } | ServerContextType::AppRoute { .. } => { - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/head", request_to_import_mapping(project_path, "next/dist/client/components/noop-head"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/dynamic", request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/link", request_to_import_mapping(project_path, "next/dist/client/app-dir/link"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/form", request_to_import_mapping(project_path, "next/dist/client/app-dir/form"), ); @@ -450,18 +458,21 @@ pub async fn get_next_edge_import_map( ServerContextType::AppSSR { .. } | ServerContextType::AppRSC { .. } | ServerContextType::AppRoute { .. } => { - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/head", request_to_import_mapping(project_path, "next/dist/client/components/noop-head"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/dynamic", request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"), ); - import_map.insert_exact_alias( + insert_exact_alias_or_js( + &mut import_map, "next/link", request_to_import_mapping(project_path, "next/dist/client/app-dir/link"), - ) + ); } } @@ -1124,6 +1135,16 @@ async fn insert_instrumentation_client_alias( Ok(()) } +// To alias e.g. both `import "next/link"` and `import "next/link.js"` +fn insert_exact_alias_or_js( + import_map: &mut ImportMap, + pattern: &str, + mapping: ResolvedVc<ImportMapping>, +) { + import_map.insert_exact_alias(pattern, mapping); + import_map.insert_exact_alias(format!("{pattern}.js"), mapping); +} + /// Creates a direct import mapping to the result of resolving a request /// in a context. fn request_to_import_mapping(
diff --git a/crates/next-core/src/next_import_map.rs b/crates/next-core/src/next_import_map.rs index cf9bc88bcaadb..937dc1cd58cdc 100644 --- a/crates/next-core/src/next_import_map.rs +++ b/crates/next-core/src/next_import_map.rs @@ -196,19 +196,23 @@ pub async fn get_next_client_import_map( &format!("next/dist/compiled/react-server-dom-turbopack{react_flavor}/*"), ), @@ -337,19 +341,23 @@ pub async fn get_next_server_import_map( @@ -450,18 +458,21 @@ pub async fn get_next_edge_import_map( - ) + ); } } @@ -1124,6 +1135,16 @@ async fn insert_instrumentation_client_alias( Ok(()) } +// To alias e.g. both `import "next/link"` and `import "next/link.js"` +fn insert_exact_alias_or_js( + import_map: &mut ImportMap, + pattern: &str, + mapping: ResolvedVc<ImportMapping>, +) { + import_map.insert_exact_alias(pattern, mapping); + import_map.insert_exact_alias(format!("{pattern}.js"), mapping); +} + /// Creates a direct import mapping to the result of resolving a request /// in a context. fn request_to_import_mapping(
[]
[]
{ "additions": 33, "author": "mischnic", "deletions": 12, "html_url": "https://github.com/vercel/next.js/pull/78447", "issue_id": 78447, "merged_at": "2025-04-24T12:16:22Z", "omission_probability": 0.1, "pr_number": 78447, "repo": "vercel/next.js", "title": "Turbopack: add app-dir alias for `next/*` subpackages", "total_changes": 45 }
329
diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index 99c7634905c23..d7e3a210b9423 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -1544,6 +1544,18 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/css-modules-data-urls/css-modules-data-urls.test.ts": { + "passed": [ + "css-modules-data-urls should apply client class name from data url correctly", + "css-modules-data-urls should apply client styles from data url correctly", + "css-modules-data-urls should apply rsc class name from data url correctly", + "css-modules-data-urls should apply rsc styles from data url correctly" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/css-modules-pure-no-check/css-modules-pure-no-check.test.ts": { "passed": [ "css-modules-pure-no-check should apply styles correctly", @@ -5246,7 +5258,10 @@ "segment cache (incremental opt in) multiple prefetches to same link are deduped page with PPR disabled, and has a loading boundary", "segment cache (incremental opt in) multiple prefetches to same link are deduped page with PPR enabled", "segment cache (incremental opt in) multiple prefetches to same link are deduped page with PPR enabled, and has a dynamic param", + "segment cache (incremental opt in) prefetches a dynamic route when PPR is disabled if it has a loading.tsx boundary", "segment cache (incremental opt in) prefetches a shared layout on a PPR-enabled route that was previously omitted from a non-PPR-enabled route", + "segment cache (incremental opt in) skips prefetching a dynamic route when PPR is disabled if everything up to its loading.tsx boundary is already cached", + "segment cache (incremental opt in) skips prefetching a dynamic route when PPR is disabled if it has no loading.tsx boundary", "segment cache (incremental opt in) when a link is prefetched with <Link prefetch=true>, no dynamic request is made on navigation", "segment cache (incremental opt in) when prefetching with prefetch=true, refetches cache entries that only contain partial data", "segment cache (incremental opt in) when prefetching with prefetch=true, refetches partial cache entries even if there's already a pending PPR request" @@ -6096,6 +6111,17 @@ "flakey": [], "runtimeError": false }, + "test/e2e/config-turbopack/index.test.ts": { + "passed": [ + "config-turbopack when webpack is configured and config.experimental.turbo is set does not warn", + "config-turbopack when webpack is configured and config.turbopack is set does not warn", + "config-turbopack when webpack is configured but Turbopack is not warns" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/conflicting-app-page-error/index.test.ts": { "passed": [ "Conflict between app file and pages file should print error for conflicting app/page" @@ -18737,14 +18763,14 @@ "test/production/graceful-shutdown/index.test.ts": { "passed": [ "Graceful Shutdown development (next dev) should shut down child immediately", - "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup when there is no activity", - "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup when there is no activity" + "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup should finish pending requests but refuse new ones", + "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup should stop accepting new requests when shutting down", + "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup should finish pending requests but refuse new ones", + "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup should stop accepting new requests when shutting down" ], "failed": [], "pending": [ - "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup when request is made before shutdown", "Graceful Shutdown production (next start) should wait for requests to complete before exiting", - "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup when request is made before shutdown", "Graceful Shutdown production (standalone mode) should wait for requests to complete before exiting" ], "flakey": [],
diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index 99c7634905c23..d7e3a210b9423 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -1544,6 +1544,18 @@ + "test/e2e/app-dir/css-modules-data-urls/css-modules-data-urls.test.ts": { + "css-modules-data-urls should apply client class name from data url correctly", + "css-modules-data-urls should apply client styles from data url correctly", + "css-modules-data-urls should apply rsc class name from data url correctly", + "css-modules-data-urls should apply rsc styles from data url correctly" "test/e2e/app-dir/css-modules-pure-no-check/css-modules-pure-no-check.test.ts": { "css-modules-pure-no-check should apply styles correctly", @@ -5246,7 +5258,10 @@ "segment cache (incremental opt in) multiple prefetches to same link are deduped page with PPR disabled, and has a loading boundary", "segment cache (incremental opt in) multiple prefetches to same link are deduped page with PPR enabled", "segment cache (incremental opt in) multiple prefetches to same link are deduped page with PPR enabled, and has a dynamic param", + "segment cache (incremental opt in) prefetches a dynamic route when PPR is disabled if it has a loading.tsx boundary", "segment cache (incremental opt in) prefetches a shared layout on a PPR-enabled route that was previously omitted from a non-PPR-enabled route", + "segment cache (incremental opt in) skips prefetching a dynamic route when PPR is disabled if everything up to its loading.tsx boundary is already cached", + "segment cache (incremental opt in) skips prefetching a dynamic route when PPR is disabled if it has no loading.tsx boundary", "segment cache (incremental opt in) when a link is prefetched with <Link prefetch=true>, no dynamic request is made on navigation", "segment cache (incremental opt in) when prefetching with prefetch=true, refetches cache entries that only contain partial data", "segment cache (incremental opt in) when prefetching with prefetch=true, refetches partial cache entries even if there's already a pending PPR request" @@ -6096,6 +6111,17 @@ + "test/e2e/config-turbopack/index.test.ts": { + "config-turbopack when webpack is configured and config.experimental.turbo is set does not warn", + "config-turbopack when webpack is configured and config.turbopack is set does not warn", + "config-turbopack when webpack is configured but Turbopack is not warns" "test/e2e/conflicting-app-page-error/index.test.ts": { "Conflict between app file and pages file should print error for conflicting app/page" @@ -18737,14 +18763,14 @@ "test/production/graceful-shutdown/index.test.ts": { "Graceful Shutdown development (next dev) should shut down child immediately", - "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup when there is no activity", - "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup when there is no activity" + "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup should finish pending requests but refuse new ones", + "Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup should stop accepting new requests when shutting down", + "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup should finish pending requests but refuse new ones", + "Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup should stop accepting new requests when shutting down" "failed": [], "pending": [ "Graceful Shutdown production (next start) should wait for requests to complete before exiting", "Graceful Shutdown production (standalone mode) should wait for requests to complete before exiting"
[ "- \"Graceful Shutdown production (next start) should not accept new requests during shutdown cleanup when request is made before shutdown\",", "- \"Graceful Shutdown production (standalone mode) should not accept new requests during shutdown cleanup when request is made before shutdown\"," ]
[ 65, 67 ]
{ "additions": 30, "author": "vercel-release-bot", "deletions": 4, "html_url": "https://github.com/vercel/next.js/pull/78491", "issue_id": 78491, "merged_at": "2025-04-24T12:14:38Z", "omission_probability": 0.1, "pr_number": 78491, "repo": "vercel/next.js", "title": "Update Turbopack production test manifest", "total_changes": 34 }
330
diff --git a/packages/create-next-app/templates/app-tw/js/app/page.js b/packages/create-next-app/templates/app-tw/js/app/page.js index 560d8bf8ad870..8d04cec62e71e 100644 --- a/packages/create-next-app/templates/app-tw/js/app/page.js +++ b/packages/create-next-app/templates/app-tw/js/app/page.js @@ -2,7 +2,7 @@ import Image from "next/image"; export default function Home() { return ( - <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> + <div className="font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20"> <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start"> <Image className="dark:invert" @@ -12,10 +12,10 @@ export default function Home() { height={38} priority /> - <ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]"> + <ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left"> <li className="mb-2 tracking-[-.01em]"> Get started by editing{" "} - <code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold"> + <code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded"> app/page.js </code> . diff --git a/packages/create-next-app/templates/app-tw/ts/app/page.tsx b/packages/create-next-app/templates/app-tw/ts/app/page.tsx index 88f0cc9b5a22e..21b686d98132a 100644 --- a/packages/create-next-app/templates/app-tw/ts/app/page.tsx +++ b/packages/create-next-app/templates/app-tw/ts/app/page.tsx @@ -2,7 +2,7 @@ import Image from "next/image"; export default function Home() { return ( - <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> + <div className="font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20"> <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start"> <Image className="dark:invert" @@ -12,10 +12,10 @@ export default function Home() { height={38} priority /> - <ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]"> + <ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left"> <li className="mb-2 tracking-[-.01em]"> Get started by editing{" "} - <code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold"> + <code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded"> app/page.tsx </code> . diff --git a/packages/create-next-app/templates/default-tw/js/pages/index.js b/packages/create-next-app/templates/default-tw/js/pages/index.js index b97696e1ff3cd..11e369a8bab0b 100644 --- a/packages/create-next-app/templates/default-tw/js/pages/index.js +++ b/packages/create-next-app/templates/default-tw/js/pages/index.js @@ -14,7 +14,7 @@ const geistMono = Geist_Mono({ export default function Home() { return ( <div - className={`${geistSans.className} ${geistMono.className} grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]`} + className={`${geistSans.className} ${geistMono.className} font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20`} > <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start"> <Image @@ -25,10 +25,10 @@ export default function Home() { height={38} priority /> - <ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]"> + <ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left"> <li className="mb-2 tracking-[-.01em]"> Get started by editing{" "} - <code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold"> + <code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded"> pages/index.js </code> . diff --git a/packages/create-next-app/templates/default-tw/ts/pages/index.tsx b/packages/create-next-app/templates/default-tw/ts/pages/index.tsx index cb1ff37cee3ff..0fa922b6f1d9b 100644 --- a/packages/create-next-app/templates/default-tw/ts/pages/index.tsx +++ b/packages/create-next-app/templates/default-tw/ts/pages/index.tsx @@ -14,7 +14,7 @@ const geistMono = Geist_Mono({ export default function Home() { return ( <div - className={`${geistSans.className} ${geistMono.className} grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]`} + className={`${geistSans.className} ${geistMono.className} font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20`} > <main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start"> <Image @@ -25,10 +25,10 @@ export default function Home() { height={38} priority /> - <ol className="list-inside list-decimal text-sm/6 text-center sm:text-left font-[family-name:var(--font-geist-mono)]"> + <ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left"> <li className="mb-2 tracking-[-.01em]"> Get started by editing{" "} - <code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-[family-name:var(--font-geist-mono)] font-semibold"> + <code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded"> pages/index.tsx </code> .
diff --git a/packages/create-next-app/templates/app-tw/js/app/page.js b/packages/create-next-app/templates/app-tw/js/app/page.js index 560d8bf8ad870..8d04cec62e71e 100644 --- a/packages/create-next-app/templates/app-tw/js/app/page.js +++ b/packages/create-next-app/templates/app-tw/js/app/page.js app/page.js diff --git a/packages/create-next-app/templates/app-tw/ts/app/page.tsx b/packages/create-next-app/templates/app-tw/ts/app/page.tsx index 88f0cc9b5a22e..21b686d98132a 100644 --- a/packages/create-next-app/templates/app-tw/ts/app/page.tsx +++ b/packages/create-next-app/templates/app-tw/ts/app/page.tsx app/page.tsx diff --git a/packages/create-next-app/templates/default-tw/js/pages/index.js b/packages/create-next-app/templates/default-tw/js/pages/index.js index b97696e1ff3cd..11e369a8bab0b 100644 --- a/packages/create-next-app/templates/default-tw/js/pages/index.js +++ b/packages/create-next-app/templates/default-tw/js/pages/index.js pages/index.js diff --git a/packages/create-next-app/templates/default-tw/ts/pages/index.tsx b/packages/create-next-app/templates/default-tw/ts/pages/index.tsx index cb1ff37cee3ff..0fa922b6f1d9b 100644 --- a/packages/create-next-app/templates/default-tw/ts/pages/index.tsx +++ b/packages/create-next-app/templates/default-tw/ts/pages/index.tsx pages/index.tsx
[]
[]
{ "additions": 12, "author": "Marukome0743", "deletions": 12, "html_url": "https://github.com/vercel/next.js/pull/77271", "issue_id": 77271, "merged_at": "2025-04-09T23:46:50Z", "omission_probability": 0.1, "pr_number": 77271, "repo": "vercel/next.js", "title": "chore(cna): use short tailwind classname of font-family", "total_changes": 24 }
331
diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs index ebd28f41a63ef..b43c0c7e9405f 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs @@ -455,11 +455,11 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { Some(Ok(Err(listen_to_done_event(this, reader, done_event)))) } Some(InProgressState::InProgress(box InProgressStateInner { - marked_as_completed, + done, done_event, .. })) => { - if !*marked_as_completed { + if !*done { Some(Ok(Err(listen_to_done_event(this, reader, done_event)))) } else { None @@ -606,6 +606,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { // Output doesn't exist. We need to schedule the task to compute it. let (item, listener) = CachedDataItem::new_scheduled_with_listener(self.get_task_desc_fn(task_id), note); + // It's not possible that the task is InProgress at this point. If it is InProgress { + // done: true } it must have Output and would early return. task.add_new(item); turbo_tasks.schedule(task_id); @@ -1135,6 +1137,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { done_event, session_dependent: false, marked_as_completed: false, + done: false, new_children: Default::default(), })), }); @@ -1277,7 +1280,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { }; let &mut InProgressState::InProgress(box InProgressStateInner { stale, - ref mut marked_as_completed, + ref mut done, ref done_event, ref mut new_children, .. @@ -1318,10 +1321,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { } // mark the task as completed, so dependent tasks can continue working - if !*marked_as_completed { - *marked_as_completed = true; - done_event.notify(usize::MAX); - } + *done = true; + done_event.notify(usize::MAX); // take the children from the task to process them let mut new_children = take(new_children); @@ -1502,6 +1503,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { once_task: _, stale, session_dependent, + done: _, marked_as_completed: _, new_children, }) = in_progress @@ -1886,12 +1888,10 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { let mut task = ctx.task(task, TaskDataCategory::Data); if let Some(InProgressState::InProgress(box InProgressStateInner { marked_as_completed, - done_event, .. })) = get_mut!(task, InProgress) { *marked_as_completed = true; - done_event.notify(usize::MAX); // TODO this should remove the dirty state (also check session_dependent) // but this would break some assumptions for strongly consistent reads. // Client tasks are not connected yet, so we wouldn't wait for them. diff --git a/turbopack/crates/turbo-tasks-backend/src/data.rs b/turbopack/crates/turbo-tasks-backend/src/data.rs index d0c6e8c66da69..da4dab0a775ba 100644 --- a/turbopack/crates/turbo-tasks-backend/src/data.rs +++ b/turbopack/crates/turbo-tasks-backend/src/data.rs @@ -309,7 +309,13 @@ pub struct InProgressStateInner { #[allow(dead_code)] pub once_task: bool, pub session_dependent: bool, + /// Early marking as completed. This is set before the output is available and will ignore full + /// task completion of the task for strongly consistent reads. pub marked_as_completed: bool, + /// Task execution has completed and the output is available. + pub done: bool, + /// Event that is triggered when the task output is available (completed flag set). + /// This is used to wait for completion when reading the task output before it's available. pub done_event: Event, /// Children that should be connected to the task and have their active_count decremented /// once the task completes.
diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs index ebd28f41a63ef..b43c0c7e9405f 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs @@ -455,11 +455,11 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { Some(Ok(Err(listen_to_done_event(this, reader, done_event)))) } Some(InProgressState::InProgress(box InProgressStateInner { - marked_as_completed, + done, .. })) => { - if !*marked_as_completed { + if !*done { Some(Ok(Err(listen_to_done_event(this, reader, done_event)))) } else { None @@ -606,6 +606,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { // Output doesn't exist. We need to schedule the task to compute it. let (item, listener) = CachedDataItem::new_scheduled_with_listener(self.get_task_desc_fn(task_id), note); + // It's not possible that the task is InProgress at this point. If it is InProgress { + // done: true } it must have Output and would early return. task.add_new(item); turbo_tasks.schedule(task_id); @@ -1135,6 +1137,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { session_dependent: false, marked_as_completed: false, new_children: Default::default(), })), }); @@ -1277,7 +1280,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { }; let &mut InProgressState::InProgress(box InProgressStateInner { - ref mut marked_as_completed, + ref mut done, ref done_event, ref mut new_children, @@ -1318,10 +1321,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { } // mark the task as completed, so dependent tasks can continue working - if !*marked_as_completed { - *marked_as_completed = true; - } + done_event.notify(usize::MAX); // take the children from the task to process them let mut new_children = take(new_children); @@ -1502,6 +1503,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { once_task: _, session_dependent, + done: _, marked_as_completed: _, new_children, }) = in_progress @@ -1886,12 +1888,10 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> { let mut task = ctx.task(task, TaskDataCategory::Data); if let Some(InProgressState::InProgress(box InProgressStateInner { marked_as_completed, })) = get_mut!(task, InProgress) { *marked_as_completed = true; // TODO this should remove the dirty state (also check session_dependent) // but this would break some assumptions for strongly consistent reads. // Client tasks are not connected yet, so we wouldn't wait for them. diff --git a/turbopack/crates/turbo-tasks-backend/src/data.rs b/turbopack/crates/turbo-tasks-backend/src/data.rs index d0c6e8c66da69..da4dab0a775ba 100644 --- a/turbopack/crates/turbo-tasks-backend/src/data.rs +++ b/turbopack/crates/turbo-tasks-backend/src/data.rs @@ -309,7 +309,13 @@ pub struct InProgressStateInner { #[allow(dead_code)] pub once_task: bool, pub session_dependent: bool, + /// Early marking as completed. This is set before the output is available and will ignore full + /// task completion of the task for strongly consistent reads. pub marked_as_completed: bool, + /// Task execution has completed and the output is available. + pub done: bool, + /// Event that is triggered when the task output is available (completed flag set). + /// This is used to wait for completion when reading the task output before it's available. pub done_event: Event, /// Children that should be connected to the task and have their active_count decremented /// once the task completes.
[ "+ done: false,", "+ *done = true;", "- done_event," ]
[ 31, 52, 69 ]
{ "additions": 15, "author": "sokra", "deletions": 9, "html_url": "https://github.com/vercel/next.js/pull/77922", "issue_id": 77922, "merged_at": "2025-04-10T06:22:07Z", "omission_probability": 0.1, "pr_number": 77922, "repo": "vercel/next.js", "title": "Turbopack: fix a bug where marking a task a completed causes a panic when reading the output", "total_changes": 24 }
332
diff --git a/test/integration/css/test/css-modules.test.js b/test/integration/css/test/css-modules.test.js index 66ce50ceb8440..45a7fb99fe5d6 100644 --- a/test/integration/css/test/css-modules.test.js +++ b/test/integration/css/test/css-modules.test.js @@ -1,6 +1,6 @@ /* eslint-env jest */ import cheerio from 'cheerio' -import { readdir, readFile, remove } from 'fs-extra' +import { readFile, remove } from 'fs-extra' import { check, File, @@ -14,6 +14,7 @@ import { } from 'next-test-utils' import webdriver from 'next-webdriver' import { join } from 'path' +import nodeFs from 'fs' const fixturesDir = join(__dirname, '../..', 'css-fixtures') @@ -145,16 +146,18 @@ describe('should handle unresolved files gracefully', () => { }) it('should have correct file references in CSS output', async () => { - const cssFiles = await readdir(join(workDir, '.next/static/css')) + const cssFolder = join(workDir, '.next', 'static') + const cssFiles = nodeFs + .readdirSync(cssFolder, { + recursive: true, + encoding: 'utf8', + }) + .filter((f) => f.endsWith('.css')) - for (const file of cssFiles) { - if (file.endsWith('.css.map')) continue + expect(cssFiles).not.toBeEmpty() - const content = await readFile( - join(workDir, '.next/static/css', file), - 'utf8' - ) - console.log(file, content) + for (const file of cssFiles) { + const content = await readFile(join(cssFolder, file), 'utf8') // if it is the combined global CSS file there are double the expected // results @@ -162,7 +165,6 @@ describe('should handle unresolved files gracefully', () => { content.includes('p{') || content.includes('p,') ? 2 : 1 expect(content.match(/\(\/vercel\.svg/g).length).toBe(howMany) - // expect(content.match(/\(vercel\.svg/g).length).toBe(howMany) expect(content.match(/\(\/_next\/static\/media/g).length).toBe(1) expect(content.match(/\(https:\/\//g).length).toBe(howMany) } @@ -184,14 +186,18 @@ describe('Data URLs', () => { }) it('should have emitted expected files', async () => { - const cssFolder = join(workDir, '.next/static/css') - const files = await readdir(cssFolder) - const cssFiles = files.filter((f) => /\.css$/.test(f)) + const cssFolder = join(workDir, '.next', 'static') + const cssFiles = nodeFs + .readdirSync(cssFolder, { + recursive: true, + encoding: 'utf8', + }) + .filter((f) => f.endsWith('.css')) expect(cssFiles.length).toBe(1) const cssContent = await readFile(join(cssFolder, cssFiles[0]), 'utf8') - expect(cssContent.replace(/\/\*.*?\*\//g, '').trim()).toMatch( - /background:url\("data:[^"]+"\)/ + expect(cssContent.replace(/\/\*.*?\*\/n/g, '').trim()).toMatch( + /background:url\("?data:[^"]+"?\)/ ) }) } diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index 79d9cee396432..bc7f934ebe8a4 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -9713,6 +9713,7 @@ "test/integration/css/test/css-modules.test.js": { "passed": [ "Data URLs production mode should compile successfully", + "Data URLs production mode should have emitted expected files", "Ordering with Global CSS and Modules (dev) useLightnincsss(false) should have the correct color (css ordering)", "Ordering with Global CSS and Modules (dev) useLightnincsss(false) should have the correct color (css ordering) during hot reloads", "Ordering with Global CSS and Modules (dev) useLightnincsss(false) should not execute scripts in any order", @@ -9726,7 +9727,6 @@ "should handle unresolved files gracefully production mode should build correctly" ], "failed": [ - "Data URLs production mode should have emitted expected files", "should handle unresolved files gracefully production mode should have correct file references in CSS output" ], "pending": [
diff --git a/test/integration/css/test/css-modules.test.js b/test/integration/css/test/css-modules.test.js index 66ce50ceb8440..45a7fb99fe5d6 100644 --- a/test/integration/css/test/css-modules.test.js +++ b/test/integration/css/test/css-modules.test.js @@ -1,6 +1,6 @@ /* eslint-env jest */ import cheerio from 'cheerio' +import { readFile, remove } from 'fs-extra' import { check, File, @@ -14,6 +14,7 @@ import { } from 'next-test-utils' import webdriver from 'next-webdriver' import { join } from 'path' +import nodeFs from 'fs' const fixturesDir = join(__dirname, '../..', 'css-fixtures') @@ -145,16 +146,18 @@ describe('should handle unresolved files gracefully', () => { it('should have correct file references in CSS output', async () => { - const cssFiles = await readdir(join(workDir, '.next/static/css')) - for (const file of cssFiles) { - if (file.endsWith('.css.map')) continue + expect(cssFiles).not.toBeEmpty() - const content = await readFile( - join(workDir, '.next/static/css', file), - 'utf8' - ) - console.log(file, content) + for (const file of cssFiles) { + const content = await readFile(join(cssFolder, file), 'utf8') // if it is the combined global CSS file there are double the expected // results @@ -162,7 +165,6 @@ describe('should handle unresolved files gracefully', () => { content.includes('p{') || content.includes('p,') ? 2 : 1 expect(content.match(/\(\/vercel\.svg/g).length).toBe(howMany) - // expect(content.match(/\(vercel\.svg/g).length).toBe(howMany) expect(content.match(/\(\/_next\/static\/media/g).length).toBe(1) expect(content.match(/\(https:\/\//g).length).toBe(howMany) } @@ -184,14 +186,18 @@ describe('Data URLs', () => { it('should have emitted expected files', async () => { - const cssFolder = join(workDir, '.next/static/css') - const files = await readdir(cssFolder) - const cssFiles = files.filter((f) => /\.css$/.test(f)) expect(cssFiles.length).toBe(1) const cssContent = await readFile(join(cssFolder, cssFiles[0]), 'utf8') - expect(cssContent.replace(/\/\*.*?\*\//g, '').trim()).toMatch( - /background:url\("data:[^"]+"\)/ + expect(cssContent.replace(/\/\*.*?\*\/n/g, '').trim()).toMatch( + /background:url\("?data:[^"]+"?\)/ ) } diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index 79d9cee396432..bc7f934ebe8a4 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -9713,6 +9713,7 @@ "test/integration/css/test/css-modules.test.js": { "passed": [ "Data URLs production mode should compile successfully", + "Data URLs production mode should have emitted expected files", "Ordering with Global CSS and Modules (dev) useLightnincsss(false) should have the correct color (css ordering)", "Ordering with Global CSS and Modules (dev) useLightnincsss(false) should have the correct color (css ordering) during hot reloads", "Ordering with Global CSS and Modules (dev) useLightnincsss(false) should not execute scripts in any order", @@ -9726,7 +9727,6 @@ "should handle unresolved files gracefully production mode should build correctly" "failed": [ - "Data URLs production mode should have emitted expected files", "should handle unresolved files gracefully production mode should have correct file references in CSS output" "pending": [
[ "-import { readdir, readFile, remove } from 'fs-extra'" ]
[ 7 ]
{ "additions": 22, "author": "mischnic", "deletions": 16, "html_url": "https://github.com/vercel/next.js/pull/77970", "issue_id": 77970, "merged_at": "2025-04-10T06:29:55Z", "omission_probability": 0.1, "pr_number": 77970, "repo": "vercel/next.js", "title": "Fix CSS Data URL test on Turbopack", "total_changes": 38 }
333
diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index bc7f934ebe8a4..17f1cbc1524bd 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -1438,6 +1438,15 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts": { + "passed": [ + "back/forward cache Activity component is renderable when the routerBFCache flag is on" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/binary/rsc-binary.test.ts": { "passed": [ "RSC binary serialization should correctly encode/decode binaries and hydrate" @@ -4499,6 +4508,15 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/rewrite-with-search-params/rewrite-with-search-params.test.ts": { + "passed": [ + "rewrite-with-search-params should not contain params in search params after rewrite" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/rewrites-redirects/rewrites-redirects.test.ts": { "passed": [ "redirects and rewrites navigation using button should redirect from middleware correctly", @@ -4643,6 +4661,16 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/rsc-query-routing/rsc-query-routing.test.ts": { + "passed": [ + "rsc-query-routing should contain rsc query in rsc request when redirect the page", + "rsc-query-routing should contain rsc query in rsc request when rewrite the page" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/rsc-webpack-loader/rsc-webpack-loader.test.ts": { "passed": [], "failed": [], @@ -8122,6 +8150,16 @@ "flakey": [], "runtimeError": false }, + "test/e2e/turbopack-turbo-config-compatibility/index.test.ts": { + "passed": [ + "turbopack-turbo-config-compatibility including both turbopack and deprecated experimental turbo config prefers turbopack config over deprecated experimental turbo config", + "turbopack-turbo-config-compatibility only including deprecated experimental turbo config still uses the deprecated experimental turbo config" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/type-module-interop/index.test.ts": { "passed": [ "Type module interop should render client-side", @@ -14971,7 +15009,7 @@ "flakey": [], "runtimeError": false }, - "test/integration/module-id-strategies/test/index.test.js": { + "test/integration/module-ids/test/index.test.js": { "passed": [ "minified module ids production mode should have no long module id for the next client runtime module", "minified module ids production mode should have no long module ids for async loader modules",
diff --git a/test/turbopack-build-tests-manifest.json b/test/turbopack-build-tests-manifest.json index bc7f934ebe8a4..17f1cbc1524bd 100644 --- a/test/turbopack-build-tests-manifest.json +++ b/test/turbopack-build-tests-manifest.json @@ -1438,6 +1438,15 @@ + "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts": { + "back/forward cache Activity component is renderable when the routerBFCache flag is on" "test/e2e/app-dir/binary/rsc-binary.test.ts": { "RSC binary serialization should correctly encode/decode binaries and hydrate" @@ -4499,6 +4508,15 @@ + "test/e2e/app-dir/rewrite-with-search-params/rewrite-with-search-params.test.ts": { + "rewrite-with-search-params should not contain params in search params after rewrite" "test/e2e/app-dir/rewrites-redirects/rewrites-redirects.test.ts": { "redirects and rewrites navigation using button should redirect from middleware correctly", @@ -4643,6 +4661,16 @@ + "test/e2e/app-dir/rsc-query-routing/rsc-query-routing.test.ts": { + "rsc-query-routing should contain rsc query in rsc request when redirect the page", + "rsc-query-routing should contain rsc query in rsc request when rewrite the page" "test/e2e/app-dir/rsc-webpack-loader/rsc-webpack-loader.test.ts": { "passed": [], "failed": [], @@ -8122,6 +8150,16 @@ + "turbopack-turbo-config-compatibility including both turbopack and deprecated experimental turbo config prefers turbopack config over deprecated experimental turbo config", + "turbopack-turbo-config-compatibility only including deprecated experimental turbo config still uses the deprecated experimental turbo config" "test/e2e/type-module-interop/index.test.ts": { "Type module interop should render client-side", @@ -14971,7 +15009,7 @@ - "test/integration/module-id-strategies/test/index.test.js": { + "test/integration/module-ids/test/index.test.js": { "minified module ids production mode should have no long module id for the next client runtime module", "minified module ids production mode should have no long module ids for async loader modules",
[ "+ \"test/e2e/turbopack-turbo-config-compatibility/index.test.ts\": {" ]
[ 57 ]
{ "additions": 39, "author": "vercel-release-bot", "deletions": 1, "html_url": "https://github.com/vercel/next.js/pull/78007", "issue_id": 78007, "merged_at": "2025-04-10T07:36:32Z", "omission_probability": 0.1, "pr_number": 78007, "repo": "vercel/next.js", "title": "Update Turbopack production test manifest", "total_changes": 40 }
334
diff --git a/test/turbopack-dev-tests-manifest.json b/test/turbopack-dev-tests-manifest.json index 6136b0f17a0e9..7f19d7cfdc182 100644 --- a/test/turbopack-dev-tests-manifest.json +++ b/test/turbopack-dev-tests-manifest.json @@ -2009,6 +2009,7 @@ "Error Overlay for server components Class component used in Server Component should show error when Class Component is used", "Error Overlay for server components Class component used in Server Component should show error when Component is rendered in external package", "Error Overlay for server components Class component used in Server Component should show error when React.PureComponent is rendered in external package", + "Error Overlay for server components Next.js link client hooks called in Server Component should show error when useLinkStatus is called", "Error Overlay for server components Next.js navigation client hooks called in Server Component should show error when useParams is called", "Error Overlay for server components Next.js navigation client hooks called in Server Component should show error when usePathname is called", "Error Overlay for server components Next.js navigation client hooks called in Server Component should show error when useRouter is called", @@ -4901,6 +4902,15 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts": { + "passed": [ + "back/forward cache Activity component is renderable when the routerBFCache flag is on" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/binary/rsc-binary.test.ts": { "passed": [ "RSC binary serialization should correctly encode/decode binaries and hydrate" @@ -7753,6 +7763,15 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/rewrite-with-search-params/rewrite-with-search-params.test.ts": { + "passed": [ + "rewrite-with-search-params should not contain params in search params after rewrite" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/rewrites-redirects/rewrites-redirects.test.ts": { "passed": [ "redirects and rewrites navigation using button should redirect from middleware correctly", @@ -7899,6 +7918,16 @@ "flakey": [], "runtimeError": false }, + "test/e2e/app-dir/rsc-query-routing/rsc-query-routing.test.ts": { + "passed": [ + "rsc-query-routing should contain rsc query in rsc request when redirect the page", + "rsc-query-routing should contain rsc query in rsc request when rewrite the page" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/app-dir/rsc-webpack-loader/rsc-webpack-loader.test.ts": { "passed": [], "failed": [], @@ -11306,6 +11335,16 @@ "flakey": [], "runtimeError": false }, + "test/e2e/turbopack-turbo-config-compatibility/index.test.ts": { + "passed": [ + "turbopack-turbo-config-compatibility including both turbopack and deprecated experimental turbo config prefers turbopack config over deprecated experimental turbo config", + "turbopack-turbo-config-compatibility only including deprecated experimental turbo config still uses the deprecated experimental turbo config" + ], + "failed": [], + "pending": [], + "flakey": [], + "runtimeError": false + }, "test/e2e/type-module-interop/index.test.ts": { "passed": [ "Type module interop should render client-side", @@ -18147,7 +18186,7 @@ "flakey": [], "runtimeError": false }, - "test/integration/module-id-strategies/test/index.test.js": { + "test/integration/module-ids/test/index.test.js": { "passed": [ "minified module ids development mode should have long module id for the next client runtime module", "minified module ids development mode should have long module ids for async loader modules",
diff --git a/test/turbopack-dev-tests-manifest.json b/test/turbopack-dev-tests-manifest.json index 6136b0f17a0e9..7f19d7cfdc182 100644 --- a/test/turbopack-dev-tests-manifest.json +++ b/test/turbopack-dev-tests-manifest.json @@ -2009,6 +2009,7 @@ "Error Overlay for server components Class component used in Server Component should show error when Class Component is used", "Error Overlay for server components Class component used in Server Component should show error when Component is rendered in external package", "Error Overlay for server components Class component used in Server Component should show error when React.PureComponent is rendered in external package", + "Error Overlay for server components Next.js link client hooks called in Server Component should show error when useLinkStatus is called", "Error Overlay for server components Next.js navigation client hooks called in Server Component should show error when useParams is called", "Error Overlay for server components Next.js navigation client hooks called in Server Component should show error when usePathname is called", "Error Overlay for server components Next.js navigation client hooks called in Server Component should show error when useRouter is called", @@ -4901,6 +4902,15 @@ + "test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts": { + "back/forward cache Activity component is renderable when the routerBFCache flag is on" "test/e2e/app-dir/binary/rsc-binary.test.ts": { "RSC binary serialization should correctly encode/decode binaries and hydrate" @@ -7753,6 +7763,15 @@ + "test/e2e/app-dir/rewrite-with-search-params/rewrite-with-search-params.test.ts": { + "rewrite-with-search-params should not contain params in search params after rewrite" "test/e2e/app-dir/rewrites-redirects/rewrites-redirects.test.ts": { "redirects and rewrites navigation using button should redirect from middleware correctly", @@ -7899,6 +7918,16 @@ + "test/e2e/app-dir/rsc-query-routing/rsc-query-routing.test.ts": { + "rsc-query-routing should contain rsc query in rsc request when redirect the page", "test/e2e/app-dir/rsc-webpack-loader/rsc-webpack-loader.test.ts": { "passed": [], "failed": [], @@ -11306,6 +11335,16 @@ + "test/e2e/turbopack-turbo-config-compatibility/index.test.ts": { + "turbopack-turbo-config-compatibility including both turbopack and deprecated experimental turbo config prefers turbopack config over deprecated experimental turbo config", + "turbopack-turbo-config-compatibility only including deprecated experimental turbo config still uses the deprecated experimental turbo config" "test/e2e/type-module-interop/index.test.ts": { "Type module interop should render client-side", @@ -18147,7 +18186,7 @@ - "test/integration/module-id-strategies/test/index.test.js": { + "test/integration/module-ids/test/index.test.js": { "minified module ids development mode should have long module id for the next client runtime module", "minified module ids development mode should have long module ids for async loader modules",
[ "+ \"rsc-query-routing should contain rsc query in rsc request when rewrite the page\"" ]
[ 51 ]
{ "additions": 40, "author": "vercel-release-bot", "deletions": 1, "html_url": "https://github.com/vercel/next.js/pull/78008", "issue_id": 78008, "merged_at": "2025-04-10T07:46:35Z", "omission_probability": 0.1, "pr_number": 78008, "repo": "vercel/next.js", "title": "Update Turbopack development test manifest", "total_changes": 41 }
335
diff --git a/packages/next/src/build/utils.ts b/packages/next/src/build/utils.ts index 43c04c9fc9269..5d321d1eb7129 100644 --- a/packages/next/src/build/utils.ts +++ b/packages/next/src/build/utils.ts @@ -1544,8 +1544,19 @@ export async function copyTracedFiles( } try { const packageJsonPath = path.join(distDir, '../package.json') - const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8')) + const packageJsonContent = await fs.readFile(packageJsonPath, 'utf8') + const packageJson = JSON.parse(packageJsonContent) moduleType = packageJson.type === 'module' + + // we always copy the package.json to the standalone + // folder to ensure any resolving logic is maintained + const packageJsonOutputPath = path.join( + outputPath, + path.relative(tracingRoot, dir), + 'package.json' + ) + await fs.mkdir(path.dirname(packageJsonOutputPath), { recursive: true }) + await fs.writeFile(packageJsonOutputPath, packageJsonContent) } catch {} const copiedFiles = new Set() await fs.rm(outputPath, { recursive: true, force: true }) @@ -1676,7 +1687,7 @@ export async function copyTracedFiles( const serverOutputPath = path.join( outputPath, path.relative(tracingRoot, dir), - 'server.js' + moduleType ? 'server.mjs' : 'server.js' ) await fs.mkdir(path.dirname(serverOutputPath), { recursive: true }) diff --git a/test/production/standalone-mode/type-module/index.test.ts b/test/production/standalone-mode/type-module/index.test.ts index cc88eec6cf97a..464bb4ecec3d9 100644 --- a/test/production/standalone-mode/type-module/index.test.ts +++ b/test/production/standalone-mode/type-module/index.test.ts @@ -39,7 +39,9 @@ describe('type-module', () => { await fs.move(staticSrc, staticDest) - const serverFile = join(standalonePath, 'server.js') + expect(fs.existsSync(join(standalonePath, 'package.json'))).toBe(true) + + const serverFile = join(standalonePath, 'server.mjs') const appPort = await findPort() const server = await initNextServerScript( serverFile,
diff --git a/packages/next/src/build/utils.ts b/packages/next/src/build/utils.ts index 43c04c9fc9269..5d321d1eb7129 100644 --- a/packages/next/src/build/utils.ts +++ b/packages/next/src/build/utils.ts @@ -1544,8 +1544,19 @@ export async function copyTracedFiles( } try { const packageJsonPath = path.join(distDir, '../package.json') - const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8')) + const packageJsonContent = await fs.readFile(packageJsonPath, 'utf8') + const packageJson = JSON.parse(packageJsonContent) moduleType = packageJson.type === 'module' + // we always copy the package.json to the standalone + // folder to ensure any resolving logic is maintained + const packageJsonOutputPath = path.join( + outputPath, + path.relative(tracingRoot, dir), + ) + await fs.mkdir(path.dirname(packageJsonOutputPath), { recursive: true }) + await fs.writeFile(packageJsonOutputPath, packageJsonContent) } catch {} const copiedFiles = new Set() await fs.rm(outputPath, { recursive: true, force: true }) @@ -1676,7 +1687,7 @@ export async function copyTracedFiles( const serverOutputPath = path.join( outputPath, path.relative(tracingRoot, dir), - 'server.js' + moduleType ? 'server.mjs' : 'server.js' ) await fs.mkdir(path.dirname(serverOutputPath), { recursive: true }) diff --git a/test/production/standalone-mode/type-module/index.test.ts b/test/production/standalone-mode/type-module/index.test.ts index cc88eec6cf97a..464bb4ecec3d9 100644 --- a/test/production/standalone-mode/type-module/index.test.ts +++ b/test/production/standalone-mode/type-module/index.test.ts @@ -39,7 +39,9 @@ describe('type-module', () => { await fs.move(staticSrc, staticDest) - const serverFile = join(standalonePath, 'server.js') + expect(fs.existsSync(join(standalonePath, 'package.json'))).toBe(true) + const serverFile = join(standalonePath, 'server.mjs') const appPort = await findPort() const server = await initNextServerScript( serverFile,
[ "+ 'package.json'" ]
[ 18 ]
{ "additions": 16, "author": "ijjk", "deletions": 3, "html_url": "https://github.com/vercel/next.js/pull/77944", "issue_id": 77944, "merged_at": "2025-04-08T18:57:05Z", "omission_probability": 0.1, "pr_number": 77944, "repo": "vercel/next.js", "title": "Output server.mjs for standalone with type: module", "total_changes": 19 }
336
diff --git a/packages/next/src/client/components/errors/attach-hydration-error-state.ts b/packages/next/src/client/components/errors/attach-hydration-error-state.ts index 7624ffb8295b0..8292fde4c8e09 100644 --- a/packages/next/src/client/components/errors/attach-hydration-error-state.ts +++ b/packages/next/src/client/components/errors/attach-hydration-error-state.ts @@ -1,11 +1,11 @@ import { getDefaultHydrationErrorMessage, + getHydrationErrorStackInfo, isHydrationError, testReactHydrationWarning, } from '../is-hydration-error' import { hydrationErrorState, - getReactHydrationDiffSegments, type HydrationErrorState, } from './hydration-error-info' @@ -19,14 +19,8 @@ export function attachHydrationErrorState(error: Error) { return } - const reactHydrationDiffSegments = getReactHydrationDiffSegments( - error.message - ) - // If the reactHydrationDiffSegments exists - // and the diff (reactHydrationDiffSegments[1]) exists - // e.g. the hydration diff log error. - if (reactHydrationDiffSegments) { - const diff = reactHydrationDiffSegments[1] + const { message, diff } = getHydrationErrorStackInfo(error.message) + if (message) { parsedHydrationErrorState = { ...((error as any).details as HydrationErrorState), ...hydrationErrorState, @@ -43,7 +37,7 @@ export function attachHydrationErrorState(error: Error) { ], // When it's hydration diff log, do not show notes section. // This condition is only for the 1st squashed error. - notes: isHydrationWarning ? '' : reactHydrationDiffSegments[0], + notes: isHydrationWarning ? '' : message, reactOutputComponentDiff: diff, } // Cache the `reactOutputComponentDiff` into hydrationErrorState. diff --git a/packages/next/src/client/components/errors/hydration-error-info.ts b/packages/next/src/client/components/errors/hydration-error-info.ts index 939e0a8f5048a..8faa37e881fdf 100644 --- a/packages/next/src/client/components/errors/hydration-error-info.ts +++ b/packages/next/src/client/components/errors/hydration-error-info.ts @@ -1,7 +1,4 @@ -import { - getHydrationErrorStackInfo, - testReactHydrationWarning, -} from '../is-hydration-error' +import { testReactHydrationWarning } from '../is-hydration-error' export type HydrationErrorState = { // Hydration warning template format: <message> <serverContent> <clientContent> @@ -55,14 +52,6 @@ const isHtmlTagsWarning = (message: string) => htmlTagsWarnings.has(message) const isTextInTagsMismatchWarning = (msg: string) => textAndTagsMismatchWarnings.has(msg) -export const getReactHydrationDiffSegments = (msg: NullableText) => { - if (msg) { - const { message, diff } = getHydrationErrorStackInfo(msg) - if (message) return [message, diff] - } - return undefined -} - /** * Patch console.error to capture hydration errors. * If any of the knownHydrationWarnings are logged, store the message and component stack. diff --git a/packages/next/src/client/components/is-hydration-error.ts b/packages/next/src/client/components/is-hydration-error.ts index 366567e931940..acb6850f56423 100644 --- a/packages/next/src/client/components/is-hydration-error.ts +++ b/packages/next/src/client/components/is-hydration-error.ts @@ -52,7 +52,6 @@ export function testReactHydrationWarning(msg: string): boolean { export function getHydrationErrorStackInfo(rawMessage: string): { message: string | null - stack?: string diff?: string } { rawMessage = rawMessage.replace(/^Error: /, '') @@ -62,7 +61,6 @@ export function getHydrationErrorStackInfo(rawMessage: string): { if (!isReactHydrationErrorMessage(rawMessage) && !isReactHydrationWarning) { return { message: null, - stack: rawMessage, diff: '', } } @@ -71,7 +69,6 @@ export function getHydrationErrorStackInfo(rawMessage: string): { const [message, diffLog] = rawMessage.split('\n\n') return { message: message.trim(), - stack: '', diff: (diffLog || '').trim(), } } @@ -83,13 +80,10 @@ export function getHydrationErrorStackInfo(rawMessage: string): { const trimmedMessage = message.trim() // React built-in hydration diff starts with a newline, checking if length is > 1 if (trailing && trailing.length > 1) { - const stacks: string[] = [] const diffs: string[] = [] trailing.split('\n').forEach((line) => { if (line.trim() === '') return - if (line.trim().startsWith('at ')) { - stacks.push(line) - } else { + if (!line.trim().startsWith('at ')) { diffs.push(line) } }) @@ -97,12 +91,10 @@ export function getHydrationErrorStackInfo(rawMessage: string): { return { message: trimmedMessage, diff: diffs.join('\n'), - stack: stacks.join('\n'), } } else { return { message: trimmedMessage, - stack: trailing, // without hydration diff } } } diff --git a/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx b/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx index fa329e7965003..9a67c3bb493c3 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx @@ -4,7 +4,6 @@ import { useMeasureHeight } from '../../hooks/use-measure-height' export type DialogProps = { children?: React.ReactNode - type: 'error' | 'warning' 'aria-labelledby': string 'aria-describedby': string className?: string @@ -22,7 +21,6 @@ const CSS_SELECTORS_TO_EXCLUDE_ON_CLICK_OUTSIDE = [ const Dialog: React.FC<DialogProps> = function Dialog({ children, - type, className, onClose, 'aria-labelledby': ariaLabelledBy, diff --git a/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx b/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx index a2f6868dcbf19..9fc6bc39869c3 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx @@ -16,7 +16,6 @@ export function ErrorOverlayDialog({ return ( <div className="error-overlay-dialog-container"> <Dialog - type="error" aria-labelledby="nextjs__container_errors_label" aria-describedby="nextjs__container_errors_desc" className="error-overlay-dialog-scroll" diff --git a/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx b/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx index b4d1a59721ef6..b807664b92747 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx @@ -49,16 +49,10 @@ import { CollapseIcon } from '../../icons/collapse-icon' * */ export function PseudoHtmlDiff({ - firstContent, - secondContent, - hydrationMismatchType, reactOutputComponentDiff, ...props }: { - firstContent: string - secondContent: string reactOutputComponentDiff: string - hydrationMismatchType: 'tag' | 'text' | 'text-in-tag' } & React.HTMLAttributes<HTMLPreElement>) { const [isDiffCollapsed, toggleCollapseHtml] = useState(true) diff --git a/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx b/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx index 2c7928d881ff2..fc5cf9f7d3eef 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx @@ -5,10 +5,7 @@ import { RuntimeError } from './runtime-error' import { getErrorSource } from '../../../../../shared/lib/error-source' import { HotlinkedText } from '../components/hot-linked-text' import { PseudoHtmlDiff } from './runtime-error/component-stack-pseudo-html' -import { - type HydrationErrorState, - getHydrationWarningType, -} from '../../../errors/hydration-error-info' +import type { HydrationErrorState } from '../../../errors/hydration-error-info' import { isConsoleError, getConsoleErrorType, @@ -131,7 +128,6 @@ export function Errors({ const [warningTemplate, serverContent, clientContent] = errorDetails.warning || [null, '', ''] - const hydrationErrorType = getHydrationWarningType(warningTemplate) const hydrationWarning = warningTemplate ? warningTemplate .replace('%s', serverContent) @@ -193,9 +189,6 @@ export function Errors({ !!errorDetails.reactOutputComponentDiff) ? ( <PseudoHtmlDiff className="nextjs__container_errors__component-stack" - hydrationMismatchType={hydrationErrorType} - firstContent={serverContent} - secondContent={clientContent} reactOutputComponentDiff={errorDetails.reactOutputComponentDiff || ''} /> ) : null} diff --git a/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx b/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx index 610c7809cfe2d..820359e76affe 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx @@ -15,25 +15,18 @@ type Story = StoryObj<typeof PseudoHtmlDiff> export const TextMismatch: Story = { args: { - firstContent: 'Server rendered content', - secondContent: 'Client rendered content', - hydrationMismatchType: 'text', reactOutputComponentDiff: undefined, }, } export const TextInTagMismatch: Story = { args: { - firstContent: 'Mismatched content', - secondContent: 'p', - hydrationMismatchType: 'text-in-tag', reactOutputComponentDiff: undefined, }, } export const ReactUnifiedMismatch: Story = { args: { - hydrationMismatchType: 'tag', reactOutputComponentDiff: `<Page> <Layout> <div> diff --git a/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts b/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts index 8ed88f8650b1c..e4882eadea3b9 100644 --- a/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts +++ b/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts @@ -1,21 +1,10 @@ import { parse } from 'next/dist/compiled/stacktrace-parser' import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' -import { - getHydrationErrorStackInfo, - isReactHydrationErrorMessage, -} from '../../is-hydration-error' const regexNextStatic = /\/_next(\/static\/.+)/ export function parseStack(stack: string | undefined): StackFrame[] { if (!stack) return [] - const messageAndStack = stack.replace(/^Error: /, '') - if (isReactHydrationErrorMessage(messageAndStack)) { - const { stack: parsedStack } = getHydrationErrorStackInfo(messageAndStack) - if (parsedStack) { - stack = parsedStack - } - } // throw away eval information that stacktrace-parser doesn't support // adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62
diff --git a/packages/next/src/client/components/errors/attach-hydration-error-state.ts b/packages/next/src/client/components/errors/attach-hydration-error-state.ts index 7624ffb8295b0..8292fde4c8e09 100644 --- a/packages/next/src/client/components/errors/attach-hydration-error-state.ts +++ b/packages/next/src/client/components/errors/attach-hydration-error-state.ts @@ -1,11 +1,11 @@ getDefaultHydrationErrorMessage, + getHydrationErrorStackInfo, isHydrationError, testReactHydrationWarning, } from '../is-hydration-error' hydrationErrorState, - getReactHydrationDiffSegments, type HydrationErrorState, } from './hydration-error-info' @@ -19,14 +19,8 @@ export function attachHydrationErrorState(error: Error) { return - const reactHydrationDiffSegments = getReactHydrationDiffSegments( - error.message - ) - // and the diff (reactHydrationDiffSegments[1]) exists - // e.g. the hydration diff log error. - if (reactHydrationDiffSegments) { - const diff = reactHydrationDiffSegments[1] + const { message, diff } = getHydrationErrorStackInfo(error.message) + if (message) { parsedHydrationErrorState = { ...((error as any).details as HydrationErrorState), ...hydrationErrorState, @@ -43,7 +37,7 @@ export function attachHydrationErrorState(error: Error) { ], // When it's hydration diff log, do not show notes section. // This condition is only for the 1st squashed error. - notes: isHydrationWarning ? '' : reactHydrationDiffSegments[0], + notes: isHydrationWarning ? '' : message, reactOutputComponentDiff: diff, // Cache the `reactOutputComponentDiff` into hydrationErrorState. diff --git a/packages/next/src/client/components/errors/hydration-error-info.ts b/packages/next/src/client/components/errors/hydration-error-info.ts index 939e0a8f5048a..8faa37e881fdf 100644 --- a/packages/next/src/client/components/errors/hydration-error-info.ts +++ b/packages/next/src/client/components/errors/hydration-error-info.ts @@ -1,7 +1,4 @@ - testReactHydrationWarning, -} from '../is-hydration-error' +import { testReactHydrationWarning } from '../is-hydration-error' export type HydrationErrorState = { // Hydration warning template format: <message> <serverContent> <clientContent> @@ -55,14 +52,6 @@ const isHtmlTagsWarning = (message: string) => htmlTagsWarnings.has(message) const isTextInTagsMismatchWarning = (msg: string) => textAndTagsMismatchWarnings.has(msg) -export const getReactHydrationDiffSegments = (msg: NullableText) => { - if (msg) { - const { message, diff } = getHydrationErrorStackInfo(msg) - if (message) return [message, diff] - return undefined - /** * Patch console.error to capture hydration errors. * If any of the knownHydrationWarnings are logged, store the message and component stack. diff --git a/packages/next/src/client/components/is-hydration-error.ts b/packages/next/src/client/components/is-hydration-error.ts index 366567e931940..acb6850f56423 100644 --- a/packages/next/src/client/components/is-hydration-error.ts +++ b/packages/next/src/client/components/is-hydration-error.ts @@ -52,7 +52,6 @@ export function testReactHydrationWarning(msg: string): boolean { export function getHydrationErrorStackInfo(rawMessage: string): { message: string | null - stack?: string diff?: string } { rawMessage = rawMessage.replace(/^Error: /, '') @@ -62,7 +61,6 @@ export function getHydrationErrorStackInfo(rawMessage: string): { if (!isReactHydrationErrorMessage(rawMessage) && !isReactHydrationWarning) { message: null, - stack: rawMessage, diff: '', @@ -71,7 +69,6 @@ export function getHydrationErrorStackInfo(rawMessage: string): { const [message, diffLog] = rawMessage.split('\n\n') message: message.trim(), - stack: '', diff: (diffLog || '').trim(), @@ -83,13 +80,10 @@ export function getHydrationErrorStackInfo(rawMessage: string): { const trimmedMessage = message.trim() // React built-in hydration diff starts with a newline, checking if length is > 1 if (trailing && trailing.length > 1) { - const stacks: string[] = [] const diffs: string[] = [] trailing.split('\n').forEach((line) => { if (line.trim() === '') return - if (line.trim().startsWith('at ')) { - stacks.push(line) - } else { + if (!line.trim().startsWith('at ')) { diffs.push(line) } }) @@ -97,12 +91,10 @@ export function getHydrationErrorStackInfo(rawMessage: string): { diff: diffs.join('\n'), - stack: stacks.join('\n'), } else { - stack: trailing, // without hydration diff diff --git a/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx b/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx index fa329e7965003..9a67c3bb493c3 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/components/dialog/dialog.tsx @@ -4,7 +4,6 @@ import { useMeasureHeight } from '../../hooks/use-measure-height' export type DialogProps = { children?: React.ReactNode - type: 'error' | 'warning' 'aria-labelledby': string 'aria-describedby': string className?: string @@ -22,7 +21,6 @@ const CSS_SELECTORS_TO_EXCLUDE_ON_CLICK_OUTSIDE = [ const Dialog: React.FC<DialogProps> = function Dialog({ children, - type, className, onClose, 'aria-labelledby': ariaLabelledBy, diff --git a/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx b/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx index a2f6868dcbf19..9fc6bc39869c3 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/components/errors/dialog/dialog.tsx @@ -16,7 +16,6 @@ export function ErrorOverlayDialog({ return ( <div className="error-overlay-dialog-container"> <Dialog - type="error" aria-labelledby="nextjs__container_errors_label" aria-describedby="nextjs__container_errors_desc" className="error-overlay-dialog-scroll" diff --git a/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx b/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx index b4d1a59721ef6..b807664b92747 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/components/hydration-diff/diff-view.tsx @@ -49,16 +49,10 @@ import { CollapseIcon } from '../../icons/collapse-icon' * */ export function PseudoHtmlDiff({ - firstContent, - secondContent, - hydrationMismatchType, reactOutputComponentDiff, ...props }: { - firstContent: string - secondContent: string reactOutputComponentDiff: string } & React.HTMLAttributes<HTMLPreElement>) { const [isDiffCollapsed, toggleCollapseHtml] = useState(true) diff --git a/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx b/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx index 2c7928d881ff2..fc5cf9f7d3eef 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/container/errors.tsx @@ -5,10 +5,7 @@ import { RuntimeError } from './runtime-error' import { getErrorSource } from '../../../../../shared/lib/error-source' import { HotlinkedText } from '../components/hot-linked-text' import { PseudoHtmlDiff } from './runtime-error/component-stack-pseudo-html' - type HydrationErrorState, - getHydrationWarningType, -} from '../../../errors/hydration-error-info' +import type { HydrationErrorState } from '../../../errors/hydration-error-info' isConsoleError, getConsoleErrorType, @@ -131,7 +128,6 @@ export function Errors({ const [warningTemplate, serverContent, clientContent] = errorDetails.warning || [null, '', ''] - const hydrationErrorType = getHydrationWarningType(warningTemplate) const hydrationWarning = warningTemplate ? warningTemplate .replace('%s', serverContent) @@ -193,9 +189,6 @@ export function Errors({ !!errorDetails.reactOutputComponentDiff) ? ( <PseudoHtmlDiff className="nextjs__container_errors__component-stack" - hydrationMismatchType={hydrationErrorType} - firstContent={serverContent} - secondContent={clientContent} reactOutputComponentDiff={errorDetails.reactOutputComponentDiff || ''} /> ) : null} diff --git a/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx b/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx index 610c7809cfe2d..820359e76affe 100644 --- a/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx +++ b/packages/next/src/client/components/react-dev-overlay/ui/container/runtime-error/component-stack-pseudo-html.stories.tsx @@ -15,25 +15,18 @@ type Story = StoryObj<typeof PseudoHtmlDiff> export const TextMismatch: Story = { - firstContent: 'Server rendered content', - secondContent: 'Client rendered content', - hydrationMismatchType: 'text', export const TextInTagMismatch: Story = { - firstContent: 'Mismatched content', - secondContent: 'p', - hydrationMismatchType: 'text-in-tag', export const ReactUnifiedMismatch: Story = { - hydrationMismatchType: 'tag', reactOutputComponentDiff: `<Page> <Layout> <div> diff --git a/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts b/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts index 8ed88f8650b1c..e4882eadea3b9 100644 --- a/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts +++ b/packages/next/src/client/components/react-dev-overlay/utils/parse-stack.ts @@ -1,21 +1,10 @@ import { parse } from 'next/dist/compiled/stacktrace-parser' import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' - isReactHydrationErrorMessage, -} from '../../is-hydration-error' const regexNextStatic = /\/_next(\/static\/.+)/ export function parseStack(stack: string | undefined): StackFrame[] { if (!stack) return [] - const messageAndStack = stack.replace(/^Error: /, '') - if (isReactHydrationErrorMessage(messageAndStack)) { - const { stack: parsedStack } = getHydrationErrorStackInfo(messageAndStack) - if (parsedStack) { - stack = parsedStack - } // throw away eval information that stacktrace-parser doesn't support // adapted from https://github.com/stacktracejs/error-stack-parser/blob/9f33c224b5d7b607755eb277f9d51fcdb7287e24/error-stack-parser.js#L59C33-L59C62
[ "- // If the reactHydrationDiffSegments exists", "-}", "- hydrationMismatchType: 'tag' | 'text' | 'text-in-tag'" ]
[ 24, 66, 176 ]
{ "additions": 7, "author": "eps1lon", "deletions": 66, "html_url": "https://github.com/vercel/next.js/pull/77929", "issue_id": 77929, "merged_at": "2025-04-10T08:43:30Z", "omission_probability": 0.1, "pr_number": 77929, "repo": "vercel/next.js", "title": "[dev-overlay] Remove unused hydration error related code", "total_changes": 73 }
337
diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx new file mode 100644 index 0000000000000..8ed2439d837c4 --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx @@ -0,0 +1,17 @@ +import { type Params, expectedParams } from '../../../expected' + +export default async function CatchAll({ + params, +}: { + params: Promise<Params> +}) { + const received = await params + + return <p>{JSON.stringify(received)}</p> +} + +export async function generateStaticParams(): Promise<Params[]> { + return [expectedParams] +} + +export const dynamic = 'force-dynamic' diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx new file mode 100644 index 0000000000000..33d03756335ee --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx @@ -0,0 +1,5 @@ +import Link from 'next/link' + +export default function Home() { + return <Link href="/1/2">Go to /1/2</Link> +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx new file mode 100644 index 0000000000000..888614deda3ba --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx @@ -0,0 +1,8 @@ +import { ReactNode } from 'react' +export default function Root({ children }: { children: ReactNode }) { + return ( + <html> + <body>{children}</body> + </html> + ) +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts new file mode 100644 index 0000000000000..37ae1d80cd3d1 --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts @@ -0,0 +1,9 @@ +export type Params = { + locale: string + rest: string[] +} + +export const expectedParams: Params = { + locale: 'en', + rest: ['1', '2'], +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts new file mode 100644 index 0000000000000..d6cac831af0fb --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts @@ -0,0 +1,21 @@ +import type { NextRequest } from 'next/server' +import { NextResponse } from 'next/server' + +export function middleware(request: NextRequest) { + return NextResponse.rewrite( + new URL('/en' + request.nextUrl.pathname, request.url) + ) +} + +export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - api (API routes) + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)', + ], +} diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js new file mode 100644 index 0000000000000..016ac8833b57f --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + experimental: { + ppr: true, + }, +} + +module.exports = nextConfig diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts new file mode 100644 index 0000000000000..4c583bbdf32c6 --- /dev/null +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts @@ -0,0 +1,26 @@ +import { nextTestSetup } from 'e2e-utils' +import { expectedParams as expected } from './expected' + +describe('ppr-middleware-rewrite-force-dynamic-generate-static-params', () => { + const { next } = nextTestSetup({ + files: __dirname, + }) + + const expectedParams = JSON.stringify(expected) + + it('should have correct dynamic params', async () => { + // should be rewritten with /en + const browser = await next.browser('/') + expect(await browser.elementByCss('a').text()).toBe('Go to /1/2') + + // navigate to /1/2 + await browser.elementByCss('a').click() + + // should be rewritten with /en/1/2 with correct params + expect(await browser.elementByCss('p').text()).toBe(expectedParams) + + // reloading the page should have the same params + await browser.refresh() + expect(await browser.elementByCss('p').text()).toBe(expectedParams) + }) +})
diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx index 0000000000000..8ed2439d837c4 +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/[...rest]/page.tsx @@ -0,0 +1,17 @@ +import { type Params, expectedParams } from '../../../expected' + params, +}: { + params: Promise<Params> +}) { + const received = await params +export async function generateStaticParams(): Promise<Params[]> { + return [expectedParams] +export const dynamic = 'force-dynamic' diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx index 0000000000000..33d03756335ee +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/[locale]/page.tsx @@ -0,0 +1,5 @@ +import Link from 'next/link' +export default function Home() { + return <Link href="/1/2">Go to /1/2</Link> diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx index 0000000000000..888614deda3ba +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/app/layout.tsx @@ -0,0 +1,8 @@ +import { ReactNode } from 'react' +export default function Root({ children }: { children: ReactNode }) { + return ( + <html> + <body>{children}</body> + </html> diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts index 0000000000000..37ae1d80cd3d1 +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/expected.ts @@ -0,0 +1,9 @@ +export type Params = { + locale: string + rest: string[] +export const expectedParams: Params = { + locale: 'en', + rest: ['1', '2'], diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts index 0000000000000..d6cac831af0fb +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/middleware.ts @@ -0,0 +1,21 @@ +import type { NextRequest } from 'next/server' +import { NextResponse } from 'next/server' +export function middleware(request: NextRequest) { + return NextResponse.rewrite( + new URL('/en' + request.nextUrl.pathname, request.url) +export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - api (API routes) + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)', + ], diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js index 0000000000000..016ac8833b57f +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/next.config.js @@ -0,0 +1,10 @@ +/** + */ +const nextConfig = { + experimental: { + ppr: true, + }, +module.exports = nextConfig diff --git a/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts index 0000000000000..4c583bbdf32c6 +++ b/test/e2e/app-dir/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params/ppr-middleware-rewrite-force-dynamic-ssg-dynamic-params.test.ts @@ -0,0 +1,26 @@ +import { nextTestSetup } from 'e2e-utils' +import { expectedParams as expected } from './expected' + const { next } = nextTestSetup({ + files: __dirname, + const expectedParams = JSON.stringify(expected) + it('should have correct dynamic params', async () => { + // should be rewritten with /en + const browser = await next.browser('/') + expect(await browser.elementByCss('a').text()).toBe('Go to /1/2') + // navigate to /1/2 + await browser.elementByCss('a').click() + // should be rewritten with /en/1/2 with correct params + // reloading the page should have the same params + await browser.refresh() +})
[ "+export default async function CatchAll({", "+ return <p>{JSON.stringify(received)}</p>", "+ * @type {import('next').NextConfig}", "+describe('ppr-middleware-rewrite-force-dynamic-generate-static-params', () => {" ]
[ 8, 15, 97, 115 ]
{ "additions": 96, "author": "devjiwonchoi", "deletions": 0, "html_url": "https://github.com/vercel/next.js/pull/78012", "issue_id": 78012, "merged_at": "2025-04-10T09:31:35Z", "omission_probability": 0.1, "pr_number": 78012, "repo": "vercel/next.js", "title": "(DO NOT MERGE) test: page to have correct dynamic params after middle…", "total_changes": 96 }
338
diff --git a/test/e2e/app-dir/css-order/app/nav.tsx b/test/e2e/app-dir/css-order/app/nav.tsx index f8a129a6ea94c..11b90a82fefb5 100644 --- a/test/e2e/app-dir/css-order/app/nav.tsx +++ b/test/e2e/app-dir/css-order/app/nav.tsx @@ -159,6 +159,7 @@ export default function Nav() { <Link href={'/pages/partial-reversed/a'} id="pages-partial-reversed-a" + prefetch={false} > Partial Reversed A </Link> @@ -167,6 +168,7 @@ export default function Nav() { <Link href={'/pages/partial-reversed/b'} id="pages-partial-reversed-b" + prefetch={false} > Partial Reversed B </Link> diff --git a/test/e2e/app-dir/css-order/css-order.test.ts b/test/e2e/app-dir/css-order/css-order.test.ts index 113f288de6882..c10f589242f7e 100644 --- a/test/e2e/app-dir/css-order/css-order.test.ts +++ b/test/e2e/app-dir/css-order/css-order.test.ts @@ -28,6 +28,8 @@ const PAGES: Record< conflictTurbo?: boolean brokenLoading?: boolean brokenLoadingDev?: boolean + requests?: number + requestsLoose?: number } > = { first: { @@ -35,42 +37,49 @@ const PAGES: Record< url: '/first', selector: '#hello1', color: 'rgb(0, 0, 255)', + requests: 1, }, second: { group: 'basic', url: '/second', selector: '#hello2', color: 'rgb(0, 128, 0)', + requests: 1, }, third: { group: 'basic', url: '/third', selector: '#hello3', color: 'rgb(0, 128, 128)', + requests: 1, }, 'first-client': { group: 'basic', url: '/first-client', selector: '#hello1c', color: 'rgb(255, 0, 255)', + requests: 1, }, 'second-client': { group: 'basic', url: '/second-client', selector: '#hello2c', color: 'rgb(255, 128, 0)', + requests: 1, }, 'interleaved-a': { group: 'interleaved', url: '/interleaved/a', selector: '#helloia', color: 'rgb(0, 255, 0)', + requests: 1, }, 'interleaved-b': { group: 'interleaved', url: '/interleaved/b', selector: '#helloib', color: 'rgb(255, 0, 255)', + requests: 1, }, 'big-interleaved-a': { group: 'big-interleaved', @@ -79,6 +88,7 @@ const PAGES: Record< url: '/big-interleaved/a', selector: '#hellobia', color: 'rgb(166, 255, 0)', + requests: 4, }, 'big-interleaved-b': { group: 'big-interleaved', @@ -87,6 +97,7 @@ const PAGES: Record< url: '/big-interleaved/b', selector: '#hellobib', color: 'rgb(166, 0, 255)', + requests: 4, }, 'reversed-a': { group: 'reversed', @@ -94,6 +105,7 @@ const PAGES: Record< url: '/reversed/a', selector: '#hellora', color: 'rgb(0, 166, 255)', + requests: 3, }, 'reversed-b': { group: 'reversed', @@ -101,6 +113,7 @@ const PAGES: Record< url: '/reversed/b', selector: '#hellorb', color: 'rgb(0, 89, 255)', + requests: 3, }, 'partial-reversed-a': { group: 'partial-reversed', @@ -109,6 +122,7 @@ const PAGES: Record< selector: '#hellopra', color: 'rgb(255, 166, 255)', background: 'rgba(0, 0, 0, 0)', + requests: 4, }, 'partial-reversed-b': { group: 'partial-reversed', @@ -117,24 +131,28 @@ const PAGES: Record< selector: '#helloprb', color: 'rgb(255, 55, 255)', background: 'rgba(0, 0, 0, 0)', + requests: 4, }, 'pages-first': { group: 'pages-basic', url: '/pages/first', selector: '#hello1', color: 'rgb(0, 0, 255)', + requests: 1, }, 'pages-second': { group: 'pages-basic', url: '/pages/second', selector: '#hello2', color: 'rgb(0, 128, 0)', + requests: 1, }, 'pages-third': { group: 'pages-basic', url: '/pages/third', selector: '#hello3', color: 'rgb(0, 128, 128)', + requests: 1, }, 'pages-interleaved-a': { @@ -143,6 +161,7 @@ const PAGES: Record< url: '/pages/interleaved/a', selector: '#helloia', color: 'rgb(0, 255, 0)', + requests: 1, }, 'pages-interleaved-b': { group: 'pages-interleaved', @@ -150,6 +169,7 @@ const PAGES: Record< url: '/pages/interleaved/b', selector: '#helloib', color: 'rgb(255, 0, 255)', + requests: 1, }, 'pages-reversed-a': { group: 'pages-reversed', @@ -159,6 +179,7 @@ const PAGES: Record< url: '/pages/reversed/a', selector: '#hellora', color: 'rgb(0, 166, 255)', + requests: 1, }, 'pages-reversed-b': { group: 'pages-reversed', @@ -168,6 +189,7 @@ const PAGES: Record< url: '/pages/reversed/b', selector: '#hellorb', color: 'rgb(0, 89, 255)', + requests: 1, }, 'pages-partial-reversed-a': { group: 'pages-partial-reversed', @@ -178,6 +200,7 @@ const PAGES: Record< selector: '#hellopra', color: 'rgb(255, 166, 255)', background: 'rgba(0, 0, 0, 0)', + requests: 1, }, 'pages-partial-reversed-b': { group: 'pages-partial-reversed', @@ -188,6 +211,7 @@ const PAGES: Record< selector: '#helloprb', color: 'rgb(255, 55, 255)', background: 'rgba(0, 0, 0, 0)', + requests: 1, }, 'global-first': { group: 'global', @@ -195,6 +219,7 @@ const PAGES: Record< url: '/global-first', selector: '#hello1', color: 'rgb(0, 255, 0)', + requests: 2, }, 'global-second': { group: 'global', @@ -202,12 +227,14 @@ const PAGES: Record< url: '/global-second', selector: '#hello2', color: 'rgb(0, 0, 255)', + requests: 2, }, vendor: { group: 'vendor', url: '/vendor', selector: '#vendor1', color: 'rgb(0, 255, 0)', + requests: 1, }, } @@ -350,7 +377,7 @@ describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])( describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])( 'css-order %s', (mode: string) => { - const { next } = nextTestSetup(options(mode)) + const { next, isNextDev } = nextTestSetup(options(mode)) for (const [page, pageInfo] of Object.entries(PAGES)) { const name = `should load correct styles on ${page}` if ( @@ -367,6 +394,19 @@ describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])( .waitForElementByCss(pageInfo.selector) .getComputedCss('color') ).toBe(pageInfo.color) + if (!isNextDev) { + const stylesheets = await browser.elementsByCss( + "link[rel='stylesheet']" + ) + const files = await Promise.all( + Array.from(stylesheets).map((e) => e.getAttribute('href')) + ) + expect(files).toHaveLength( + mode === 'turbo' || mode === 'loose' + ? pageInfo.requestsLoose || pageInfo.requests + : pageInfo.requests + ) + } await browser.close() }) }
diff --git a/test/e2e/app-dir/css-order/app/nav.tsx b/test/e2e/app-dir/css-order/app/nav.tsx index f8a129a6ea94c..11b90a82fefb5 100644 --- a/test/e2e/app-dir/css-order/app/nav.tsx +++ b/test/e2e/app-dir/css-order/app/nav.tsx @@ -159,6 +159,7 @@ export default function Nav() { href={'/pages/partial-reversed/a'} id="pages-partial-reversed-a" Partial Reversed A @@ -167,6 +168,7 @@ export default function Nav() { href={'/pages/partial-reversed/b'} id="pages-partial-reversed-b" Partial Reversed B diff --git a/test/e2e/app-dir/css-order/css-order.test.ts b/test/e2e/app-dir/css-order/css-order.test.ts index 113f288de6882..c10f589242f7e 100644 --- a/test/e2e/app-dir/css-order/css-order.test.ts +++ b/test/e2e/app-dir/css-order/css-order.test.ts @@ -28,6 +28,8 @@ const PAGES: Record< conflictTurbo?: boolean brokenLoading?: boolean brokenLoadingDev?: boolean + requests?: number + requestsLoose?: number } > = { first: { @@ -35,42 +37,49 @@ const PAGES: Record< url: '/first', second: { url: '/second', third: { url: '/third', 'first-client': { url: '/first-client', selector: '#hello1c', 'second-client': { url: '/second-client', selector: '#hello2c', color: 'rgb(255, 128, 0)', 'interleaved-a': { url: '/interleaved/a', 'interleaved-b': { url: '/interleaved/b', 'big-interleaved-a': { @@ -79,6 +88,7 @@ const PAGES: Record< url: '/big-interleaved/a', selector: '#hellobia', color: 'rgb(166, 255, 0)', 'big-interleaved-b': { @@ -87,6 +97,7 @@ const PAGES: Record< url: '/big-interleaved/b', selector: '#hellobib', color: 'rgb(166, 0, 255)', 'reversed-a': { @@ -94,6 +105,7 @@ const PAGES: Record< url: '/reversed/a', 'reversed-b': { @@ -101,6 +113,7 @@ const PAGES: Record< url: '/reversed/b', 'partial-reversed-a': { @@ -109,6 +122,7 @@ const PAGES: Record< 'partial-reversed-b': { @@ -117,24 +131,28 @@ const PAGES: Record< 'pages-first': { url: '/pages/first', 'pages-second': { url: '/pages/second', 'pages-third': { url: '/pages/third', 'pages-interleaved-a': { @@ -143,6 +161,7 @@ const PAGES: Record< url: '/pages/interleaved/a', 'pages-interleaved-b': { group: 'pages-interleaved', @@ -150,6 +169,7 @@ const PAGES: Record< url: '/pages/interleaved/b', 'pages-reversed-a': { @@ -159,6 +179,7 @@ const PAGES: Record< url: '/pages/reversed/a', 'pages-reversed-b': { @@ -168,6 +189,7 @@ const PAGES: Record< url: '/pages/reversed/b', 'pages-partial-reversed-a': { @@ -178,6 +200,7 @@ const PAGES: Record< 'pages-partial-reversed-b': { @@ -188,6 +211,7 @@ const PAGES: Record< 'global-first': { @@ -195,6 +219,7 @@ const PAGES: Record< url: '/global-first', 'global-second': { @@ -202,12 +227,14 @@ const PAGES: Record< url: '/global-second', vendor: { group: 'vendor', url: '/vendor', selector: '#vendor1', } @@ -350,7 +377,7 @@ describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])( describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])( 'css-order %s', (mode: string) => { - const { next } = nextTestSetup(options(mode)) + const { next, isNextDev } = nextTestSetup(options(mode)) for (const [page, pageInfo] of Object.entries(PAGES)) { const name = `should load correct styles on ${page}` if ( @@ -367,6 +394,19 @@ describe.each(process.env.IS_TURBOPACK_TEST ? ['turbo'] : ['strict', 'loose'])( .waitForElementByCss(pageInfo.selector) .getComputedCss('color') ).toBe(pageInfo.color) + const stylesheets = await browser.elementsByCss( + "link[rel='stylesheet']" + const files = await Promise.all( + Array.from(stylesheets).map((e) => e.getAttribute('href')) + expect(files).toHaveLength( + mode === 'turbo' || mode === 'loose' + ? pageInfo.requestsLoose || pageInfo.requests + } await browser.close() }) }
[ "+ if (!isNextDev) {", "+ : pageInfo.requests" ]
[ 236, 246 ]
{ "additions": 43, "author": "sokra", "deletions": 1, "html_url": "https://github.com/vercel/next.js/pull/77285", "issue_id": 77285, "merged_at": "2025-04-10T10:14:01Z", "omission_probability": 0.1, "pr_number": 77285, "repo": "vercel/next.js", "title": "Turbopack: check css requests in test", "total_changes": 44 }
339
diff --git a/docs/01-app/05-api-reference/08-turbopack.mdx b/docs/01-app/05-api-reference/08-turbopack.mdx index ac072f7702fc2..5a5743b58d10b 100644 --- a/docs/01-app/05-api-reference/08-turbopack.mdx +++ b/docs/01-app/05-api-reference/08-turbopack.mdx @@ -18,19 +18,19 @@ We built Turbopack to push the performance of Next.js, including: ## Getting started -To enable Turbopack in your Next.js project, use the `--turbopack` flag when running the development server: +To enable Turbopack in your Next.js project, add the `--turbopack` flag to the `dev`, `build`, and `start` scripts in your `package.json` file: ```json filename="package.json" highlight={3} { "scripts": { "dev": "next dev --turbopack", - "build": "next build", - "start": "next start" + "build": "next build --turbopack", + "start": "next start --turbopack" } } ``` -Currently, Turbopack only supports `next dev`. Build (`next build`) is **not yet** supported. We are actively working on production support as Turbopack moves closer to stability. +Currently, Turbopack for `dev` is stable, while `build` is in alpha. We are actively working on production support as Turbopack moves closer to stability. ## Supported features @@ -95,8 +95,6 @@ Turbopack in Next.js has **zero-configuration** for the common use cases. Below Some features are not yet implemented or not planned: -- **Production Builds** (`next build`) - Turbopack currently only supports `next dev`. Support for production builds is in active development. - **Legacy CSS Modules features** - Standalone `:local` and `:global` pseudo-classes (only the function variant `:global(...)` is supported). - The `@value` rule (superseded by CSS variables). @@ -166,3 +164,10 @@ This will produce a `.next/trace-turbopack` file. Include that file when creatin Turbopack is a **Rust-based**, **incremental** bundler designed to make local development and builds fast—especially for large applications. It is integrated into Next.js, offering zero-config CSS, React, and TypeScript support. Stay tuned for more updates as we continue to improve Turbopack and add production build support. In the meantime, give it a try with `next dev --turbopack` and let us know your feedback. + +## Version Changes + +| Version | Changes | +| --------- | -------------------------------- | +| `v15.3.0` | Experimental support for `build` | +| `v15.0.0` | Turbopack for `dev` stable |
diff --git a/docs/01-app/05-api-reference/08-turbopack.mdx b/docs/01-app/05-api-reference/08-turbopack.mdx index ac072f7702fc2..5a5743b58d10b 100644 --- a/docs/01-app/05-api-reference/08-turbopack.mdx +++ b/docs/01-app/05-api-reference/08-turbopack.mdx @@ -18,19 +18,19 @@ We built Turbopack to push the performance of Next.js, including: ## Getting started +To enable Turbopack in your Next.js project, add the `--turbopack` flag to the `dev`, `build`, and `start` scripts in your `package.json` file: ```json filename="package.json" highlight={3} { "scripts": { "dev": "next dev --turbopack", - "build": "next build", - "start": "next start" + "build": "next build --turbopack", + "start": "next start --turbopack" } } ``` -Currently, Turbopack only supports `next dev`. Build (`next build`) is **not yet** supported. We are actively working on production support as Turbopack moves closer to stability. +Currently, Turbopack for `dev` is stable, while `build` is in alpha. We are actively working on production support as Turbopack moves closer to stability. ## Supported features @@ -95,8 +95,6 @@ Turbopack in Next.js has **zero-configuration** for the common use cases. Below Some features are not yet implemented or not planned: -- **Production Builds** (`next build`) - Turbopack currently only supports `next dev`. Support for production builds is in active development. - **Legacy CSS Modules features** - Standalone `:local` and `:global` pseudo-classes (only the function variant `:global(...)` is supported). - The `@value` rule (superseded by CSS variables). @@ -166,3 +164,10 @@ This will produce a `.next/trace-turbopack` file. Include that file when creatin Turbopack is a **Rust-based**, **incremental** bundler designed to make local development and builds fast—especially for large applications. It is integrated into Next.js, offering zero-config CSS, React, and TypeScript support. Stay tuned for more updates as we continue to improve Turbopack and add production build support. In the meantime, give it a try with `next dev --turbopack` and let us know your feedback. +## Version Changes +| Version | Changes | +| --------- | -------------------------------- | +| `v15.3.0` | Experimental support for `build` | +| `v15.0.0` | Turbopack for `dev` stable |
[ "-To enable Turbopack in your Next.js project, use the `--turbopack` flag when running the development server:" ]
[ 8 ]
{ "additions": 11, "author": "delbaoliveira", "deletions": 6, "html_url": "https://github.com/vercel/next.js/pull/77730", "issue_id": 77730, "merged_at": "2025-04-10T10:17:41Z", "omission_probability": 0.1, "pr_number": 77730, "repo": "vercel/next.js", "title": "15.3 Docs: Turbopack for `build`", "total_changes": 17 }
340
diff --git a/docs/01-app/02-guides/index.mdx b/docs/01-app/02-guides/index.mdx index 51be2796e7408..820b02619340c 100644 --- a/docs/01-app/02-guides/index.mdx +++ b/docs/01-app/02-guides/index.mdx @@ -50,10 +50,10 @@ description: Learn how to implement common UI patterns and use cases using Next. ### Testing -- [Vitest](/docs/app/building-your-application/testing/vitest) -- [Jest](/docs/app/building-your-application/testing/jest) -- [Playwright](/docs/app/building-your-application/testing/playwright) -- [Cypress](/docs/app/building-your-application/testing/cypress) +- [Vitest](/docs/app/guides/testing/vitest) +- [Jest](/docs/app/guides/testing/jest) +- [Playwright](/docs/app/guides/testing/playwright) +- [Cypress](/docs/app/guides/testing/cypress) ### Deployment diff --git a/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/docs/01-app/02-guides/migrating/from-create-react-app.mdx index 90a510cf53fe0..f4586958cfd3d 100644 --- a/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/docs/01-app/02-guides/migrating/from-create-react-app.mdx @@ -145,7 +145,7 @@ export default function RootLayout({ children }) { } ``` -> **Good to know**: Next.js ignores CRA’s `public/manifest.json`, additional iconography, and [testing configuration](/docs/app/building-your-application/testing) by default. If you need these, Next.js has support with its [Metadata API](/docs/app/building-your-application/optimizing/metadata) and [Testing](/docs/app/building-your-application/testing) setup. +> **Good to know**: Next.js ignores CRA’s `public/manifest.json`, additional iconography, and [testing configuration](/docs/app/guides/testing) by default. If you need these, Next.js has support with its [Metadata API](/docs/app/building-your-application/optimizing/metadata) and [Testing](/docs/app/guides/testing) setup. ### Step 4: Metadata diff --git a/docs/01-app/03-building-your-application/08-testing/04-cypress.mdx b/docs/01-app/02-guides/testing/cypress.mdx similarity index 99% rename from docs/01-app/03-building-your-application/08-testing/04-cypress.mdx rename to docs/01-app/02-guides/testing/cypress.mdx index 9d705dd97a925..11897d8ee7093 100644 --- a/docs/01-app/03-building-your-application/08-testing/04-cypress.mdx +++ b/docs/01-app/02-guides/testing/cypress.mdx @@ -1,5 +1,5 @@ --- -title: Setting up Cypress with Next.js +title: How to set up Cypress with Next.js nav_title: Cypress description: Learn how to set up Cypress with Next.js for End-to-End (E2E) and Component Testing. --- diff --git a/docs/01-app/03-building-your-application/08-testing/index.mdx b/docs/01-app/02-guides/testing/index.mdx similarity index 100% rename from docs/01-app/03-building-your-application/08-testing/index.mdx rename to docs/01-app/02-guides/testing/index.mdx diff --git a/docs/01-app/03-building-your-application/08-testing/02-jest.mdx b/docs/01-app/02-guides/testing/jest.mdx similarity index 99% rename from docs/01-app/03-building-your-application/08-testing/02-jest.mdx rename to docs/01-app/02-guides/testing/jest.mdx index 38390a3e418c1..4d6a166842e37 100644 --- a/docs/01-app/03-building-your-application/08-testing/02-jest.mdx +++ b/docs/01-app/02-guides/testing/jest.mdx @@ -1,5 +1,5 @@ --- -title: Setting up Jest with Next.js +title: How to set up Jest with Next.js nav_title: Jest description: Learn how to set up Jest with Next.js for Unit Testing and Snapshot Testing. --- diff --git a/docs/01-app/03-building-your-application/08-testing/03-playwright.mdx b/docs/01-app/02-guides/testing/playwright.mdx similarity index 98% rename from docs/01-app/03-building-your-application/08-testing/03-playwright.mdx rename to docs/01-app/02-guides/testing/playwright.mdx index f8238bd5c3fbe..05c1b04625568 100644 --- a/docs/01-app/03-building-your-application/08-testing/03-playwright.mdx +++ b/docs/01-app/02-guides/testing/playwright.mdx @@ -1,5 +1,5 @@ --- -title: Setting up Playwright with Next.js +title: How to set up Playwright with Next.js nav_title: Playwright description: Learn how to set up Playwright with Next.js for End-to-End (E2E) Testing. --- diff --git a/docs/01-app/03-building-your-application/08-testing/01-vitest.mdx b/docs/01-app/02-guides/testing/vitest.mdx similarity index 99% rename from docs/01-app/03-building-your-application/08-testing/01-vitest.mdx rename to docs/01-app/02-guides/testing/vitest.mdx index 5b8608d4c7eef..f64f0a2a07710 100644 --- a/docs/01-app/03-building-your-application/08-testing/01-vitest.mdx +++ b/docs/01-app/02-guides/testing/vitest.mdx @@ -1,5 +1,5 @@ --- -title: Setting up Vitest with Next.js +title: How to set up Vitest with Next.js nav_title: Vitest description: Learn how to set up Vitest with Next.js for Unit Testing. --- diff --git a/docs/02-pages/03-building-your-application/07-testing/04-cypress.mdx b/docs/02-pages/02-guides/testing/cypress.mdx similarity index 82% rename from docs/02-pages/03-building-your-application/07-testing/04-cypress.mdx rename to docs/02-pages/02-guides/testing/cypress.mdx index e8530c9ff3bf6..85873fc3dabe5 100644 --- a/docs/02-pages/03-building-your-application/07-testing/04-cypress.mdx +++ b/docs/02-pages/02-guides/testing/cypress.mdx @@ -1,8 +1,8 @@ --- -title: Setting up Cypress with Next.js +title: How to set up Cypress with Next.js nav_title: Cypress description: Learn how to set up Next.js with Cypress for End-to-End (E2E) and Component Testing. -source: app/building-your-application/testing/cypress +source: app/guides/testing/cypress --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/07-testing/index.mdx b/docs/02-pages/02-guides/testing/index.mdx similarity index 91% rename from docs/02-pages/03-building-your-application/07-testing/index.mdx rename to docs/02-pages/02-guides/testing/index.mdx index ac033a4bb07c8..7c014535cd4e4 100644 --- a/docs/02-pages/03-building-your-application/07-testing/index.mdx +++ b/docs/02-pages/02-guides/testing/index.mdx @@ -1,7 +1,7 @@ --- title: Testing description: Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Vitest, and Jest. -source: app/building-your-application/testing +source: app/guides/testing --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/07-testing/02-jest.mdx b/docs/02-pages/02-guides/testing/jest.mdx similarity index 82% rename from docs/02-pages/03-building-your-application/07-testing/02-jest.mdx rename to docs/02-pages/02-guides/testing/jest.mdx index 993ccdc09f3c4..b6495096fc57d 100644 --- a/docs/02-pages/03-building-your-application/07-testing/02-jest.mdx +++ b/docs/02-pages/02-guides/testing/jest.mdx @@ -1,8 +1,8 @@ --- -title: Setting up Jest with Next.js +title: How to set up Jest with Next.js nav_title: Jest description: Learn how to set up Next.js with Jest for Unit Testing. -source: app/building-your-application/testing/jest +source: app/guides/testing/jest --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/07-testing/03-playwright.mdx b/docs/02-pages/02-guides/testing/playwright.mdx similarity index 82% rename from docs/02-pages/03-building-your-application/07-testing/03-playwright.mdx rename to docs/02-pages/02-guides/testing/playwright.mdx index 77fab146905a9..2424861c35f3b 100644 --- a/docs/02-pages/03-building-your-application/07-testing/03-playwright.mdx +++ b/docs/02-pages/02-guides/testing/playwright.mdx @@ -1,8 +1,8 @@ --- -title: Setting up Playwright with Next.js +title: How to set up Playwright with Next.js nav_title: Playwright description: Learn how to set up Next.js with Playwright for End-to-End (E2E) and Integration testing. -source: app/building-your-application/testing/playwright +source: app/guides/testing/playwright --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} diff --git a/docs/02-pages/03-building-your-application/07-testing/01-vitest.mdx b/docs/02-pages/02-guides/testing/vitest.mdx similarity index 83% rename from docs/02-pages/03-building-your-application/07-testing/01-vitest.mdx rename to docs/02-pages/02-guides/testing/vitest.mdx index 9b7d0067bde1c..d29d90a64a2f6 100644 --- a/docs/02-pages/03-building-your-application/07-testing/01-vitest.mdx +++ b/docs/02-pages/02-guides/testing/vitest.mdx @@ -1,8 +1,8 @@ --- -title: Setting up Vitest with Next.js +title: How to set up Vitest with Next.js nav_title: Vitest description: Learn how to set up Next.js with Vitest and React Testing Library - two popular unit testing libraries. -source: app/building-your-application/testing/vitest +source: app/guides/testing/vitest --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
diff --git a/docs/01-app/02-guides/index.mdx b/docs/01-app/02-guides/index.mdx index 51be2796e7408..820b02619340c 100644 --- a/docs/01-app/02-guides/index.mdx +++ b/docs/01-app/02-guides/index.mdx @@ -50,10 +50,10 @@ description: Learn how to implement common UI patterns and use cases using Next. ### Testing -- [Vitest](/docs/app/building-your-application/testing/vitest) -- [Jest](/docs/app/building-your-application/testing/jest) -- [Playwright](/docs/app/building-your-application/testing/playwright) -- [Cypress](/docs/app/building-your-application/testing/cypress) +- [Vitest](/docs/app/guides/testing/vitest) +- [Playwright](/docs/app/guides/testing/playwright) +- [Cypress](/docs/app/guides/testing/cypress) ### Deployment diff --git a/docs/01-app/02-guides/migrating/from-create-react-app.mdx b/docs/01-app/02-guides/migrating/from-create-react-app.mdx index 90a510cf53fe0..f4586958cfd3d 100644 --- a/docs/01-app/02-guides/migrating/from-create-react-app.mdx +++ b/docs/01-app/02-guides/migrating/from-create-react-app.mdx @@ -145,7 +145,7 @@ export default function RootLayout({ children }) { } ``` -> **Good to know**: Next.js ignores CRA’s `public/manifest.json`, additional iconography, and [testing configuration](/docs/app/building-your-application/testing) by default. If you need these, Next.js has support with its [Metadata API](/docs/app/building-your-application/optimizing/metadata) and [Testing](/docs/app/building-your-application/testing) setup. ### Step 4: Metadata diff --git a/docs/01-app/03-building-your-application/08-testing/04-cypress.mdx b/docs/01-app/02-guides/testing/cypress.mdx rename from docs/01-app/03-building-your-application/08-testing/04-cypress.mdx rename to docs/01-app/02-guides/testing/cypress.mdx index 9d705dd97a925..11897d8ee7093 100644 --- a/docs/01-app/03-building-your-application/08-testing/04-cypress.mdx +++ b/docs/01-app/02-guides/testing/cypress.mdx description: Learn how to set up Cypress with Next.js for End-to-End (E2E) and Component Testing. diff --git a/docs/01-app/03-building-your-application/08-testing/index.mdx b/docs/01-app/02-guides/testing/index.mdx similarity index 100% rename from docs/01-app/03-building-your-application/08-testing/index.mdx rename to docs/01-app/02-guides/testing/index.mdx diff --git a/docs/01-app/03-building-your-application/08-testing/02-jest.mdx b/docs/01-app/02-guides/testing/jest.mdx rename from docs/01-app/03-building-your-application/08-testing/02-jest.mdx rename to docs/01-app/02-guides/testing/jest.mdx index 38390a3e418c1..4d6a166842e37 100644 --- a/docs/01-app/03-building-your-application/08-testing/02-jest.mdx +++ b/docs/01-app/02-guides/testing/jest.mdx description: Learn how to set up Jest with Next.js for Unit Testing and Snapshot Testing. diff --git a/docs/01-app/03-building-your-application/08-testing/03-playwright.mdx b/docs/01-app/02-guides/testing/playwright.mdx similarity index 98% rename from docs/01-app/03-building-your-application/08-testing/03-playwright.mdx rename to docs/01-app/02-guides/testing/playwright.mdx index f8238bd5c3fbe..05c1b04625568 100644 --- a/docs/01-app/03-building-your-application/08-testing/03-playwright.mdx +++ b/docs/01-app/02-guides/testing/playwright.mdx description: Learn how to set up Playwright with Next.js for End-to-End (E2E) Testing. diff --git a/docs/01-app/03-building-your-application/08-testing/01-vitest.mdx b/docs/01-app/02-guides/testing/vitest.mdx rename from docs/01-app/03-building-your-application/08-testing/01-vitest.mdx rename to docs/01-app/02-guides/testing/vitest.mdx index 5b8608d4c7eef..f64f0a2a07710 100644 --- a/docs/01-app/03-building-your-application/08-testing/01-vitest.mdx +++ b/docs/01-app/02-guides/testing/vitest.mdx description: Learn how to set up Vitest with Next.js for Unit Testing. diff --git a/docs/02-pages/03-building-your-application/07-testing/04-cypress.mdx b/docs/02-pages/02-guides/testing/cypress.mdx rename from docs/02-pages/03-building-your-application/07-testing/04-cypress.mdx rename to docs/02-pages/02-guides/testing/cypress.mdx index e8530c9ff3bf6..85873fc3dabe5 100644 --- a/docs/02-pages/03-building-your-application/07-testing/04-cypress.mdx +++ b/docs/02-pages/02-guides/testing/cypress.mdx description: Learn how to set up Next.js with Cypress for End-to-End (E2E) and Component Testing. -source: app/building-your-application/testing/cypress +source: app/guides/testing/cypress diff --git a/docs/02-pages/03-building-your-application/07-testing/index.mdx b/docs/02-pages/02-guides/testing/index.mdx similarity index 91% rename from docs/02-pages/03-building-your-application/07-testing/index.mdx rename to docs/02-pages/02-guides/testing/index.mdx index ac033a4bb07c8..7c014535cd4e4 100644 --- a/docs/02-pages/03-building-your-application/07-testing/index.mdx +++ b/docs/02-pages/02-guides/testing/index.mdx @@ -1,7 +1,7 @@ title: Testing description: Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Vitest, and Jest. -source: app/building-your-application/testing +source: app/guides/testing diff --git a/docs/02-pages/03-building-your-application/07-testing/02-jest.mdx b/docs/02-pages/02-guides/testing/jest.mdx rename from docs/02-pages/03-building-your-application/07-testing/02-jest.mdx rename to docs/02-pages/02-guides/testing/jest.mdx index 993ccdc09f3c4..b6495096fc57d 100644 --- a/docs/02-pages/03-building-your-application/07-testing/02-jest.mdx +++ b/docs/02-pages/02-guides/testing/jest.mdx description: Learn how to set up Next.js with Jest for Unit Testing. -source: app/building-your-application/testing/jest +source: app/guides/testing/jest diff --git a/docs/02-pages/03-building-your-application/07-testing/03-playwright.mdx b/docs/02-pages/02-guides/testing/playwright.mdx rename from docs/02-pages/03-building-your-application/07-testing/03-playwright.mdx rename to docs/02-pages/02-guides/testing/playwright.mdx index 77fab146905a9..2424861c35f3b 100644 --- a/docs/02-pages/03-building-your-application/07-testing/03-playwright.mdx +++ b/docs/02-pages/02-guides/testing/playwright.mdx description: Learn how to set up Next.js with Playwright for End-to-End (E2E) and Integration testing. -source: app/building-your-application/testing/playwright +source: app/guides/testing/playwright diff --git a/docs/02-pages/03-building-your-application/07-testing/01-vitest.mdx b/docs/02-pages/02-guides/testing/vitest.mdx similarity index 83% rename from docs/02-pages/03-building-your-application/07-testing/01-vitest.mdx rename to docs/02-pages/02-guides/testing/vitest.mdx index 9b7d0067bde1c..d29d90a64a2f6 100644 --- a/docs/02-pages/03-building-your-application/07-testing/01-vitest.mdx +++ b/docs/02-pages/02-guides/testing/vitest.mdx description: Learn how to set up Next.js with Vitest and React Testing Library - two popular unit testing libraries. -source: app/building-your-application/testing/vitest +source: app/guides/testing/vitest
[ "+- [Jest](/docs/app/guides/testing/jest)", "+> **Good to know**: Next.js ignores CRA’s `public/manifest.json`, additional iconography, and [testing configuration](/docs/app/guides/testing) by default. If you need these, Next.js has support with its [Metadata API](/docs/app/building-your-application/optimizing/metadata) and [Testing](/docs/app/guides/testing) setup." ]
[ 13, 28 ]
{ "additions": 18, "author": "delbaoliveira", "deletions": 18, "html_url": "https://github.com/vercel/next.js/pull/78418", "issue_id": 78418, "merged_at": "2025-04-24T08:25:55Z", "omission_probability": 0.1, "pr_number": 78418, "repo": "vercel/next.js", "title": "Docs IA 2.0: Move testing guides", "total_changes": 36 }
341
diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs index 2d4ddd31547f0..aa6edae48152e 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs @@ -13,6 +13,7 @@ use turbopack_core::{ ChunkableModuleReference, ChunkingContext, ChunkingType, ChunkingTypeOption, ModuleChunkItemIdExt, }, + context::AssetContext, issue::{ Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, OptionIssueSource, OptionStyledString, StyledString, @@ -23,7 +24,7 @@ use turbopack_core::{ resolve::{ origin::{ResolveOrigin, ResolveOriginExt}, parse::Request, - ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem, + ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem, RequestKey, }, }; use turbopack_resolve::ecmascript::esm_resolve; @@ -38,6 +39,7 @@ use crate::{ runtime_functions::{TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE, TURBOPACK_IMPORT}, tree_shake::{asset::EcmascriptModulePartAsset, TURBOPACK_PART_IMPORT_SOURCE}, utils::module_id_to_lit, + TreeShakingMode, }; #[turbo_tasks::value] @@ -168,6 +170,32 @@ impl ModuleReference for EsmAssetReference { EcmaScriptModulesReferenceSubType::Import }; + if let Some(ModulePart::Evaluation) = &self.export_name { + let module: ResolvedVc<crate::EcmascriptModuleAsset> = + ResolvedVc::try_downcast_type(self.origin) + .expect("EsmAssetReference origin should be a EcmascriptModuleAsset"); + + let tree_shaking_mode = module.options().await?.tree_shaking_mode; + + if let Some(TreeShakingMode::ModuleFragments) = tree_shaking_mode { + let side_effect_free_packages = module.asset_context().side_effect_free_packages(); + + if *module + .is_marked_as_side_effect_free(side_effect_free_packages) + .await? + { + return Ok(ModuleResolveResult { + primary: Box::new([( + RequestKey::default(), + ModuleResolveResultItem::Ignore, + )]), + affecting_sources: Default::default(), + } + .cell()); + } + } + } + if let Request::Module { module, .. } = &*self.request.await? { if module == TURBOPACK_PART_IMPORT_SOURCE { if let Some(part) = &self.export_name { @@ -175,11 +203,11 @@ impl ModuleReference for EsmAssetReference { ResolvedVc::try_downcast_type(self.origin) .expect("EsmAssetReference origin should be a EcmascriptModuleAsset"); - return Ok(*ModuleResolveResult::module( + return Ok(*ModuleResolveResult::module(ResolvedVc::upcast( EcmascriptModulePartAsset::select_part(*module, part.clone()) .to_resolved() .await?, - )); + ))); } bail!("export_name is required for part import") diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs index b8bf69ff6b8d8..4af63d3d54a70 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs @@ -24,6 +24,7 @@ use turbopack_core::{ module::Module, module_graph::ModuleGraph, reference::ModuleReference, + resolve::ModulePart, }; use super::base::ReferencedAsset; @@ -33,6 +34,8 @@ use crate::{ magic_identifier, parse::ParseResult, runtime_functions::{TURBOPACK_DYNAMIC, TURBOPACK_ESM}, + tree_shake::asset::EcmascriptModulePartAsset, + EcmascriptModuleAsset, }; #[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue)] @@ -177,9 +180,9 @@ pub async fn follow_reexports( // Try to find the export in the star exports if !exports_ref.star_exports.is_empty() && &*export_name != "default" { - let result = get_all_export_names(*module).await?; - if let Some(m) = result.esm_exports.get(&export_name) { - module = *m; + let result = find_export_from_reexports(*module, export_name.clone()).await?; + if let Some(m) = result.esm_export { + module = m; continue; } return match &result.dynamic_exporting_modules[..] { @@ -269,6 +272,48 @@ async fn handle_declared_export( })) } +#[turbo_tasks::value] +struct FindExportFromReexportsResult { + esm_export: Option<ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, + dynamic_exporting_modules: Vec<ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, +} + +#[turbo_tasks::function] +async fn find_export_from_reexports( + module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, + export_name: RcStr, +) -> Result<Vc<FindExportFromReexportsResult>> { + if let Some(module) = + Vc::try_resolve_downcast_type::<EcmascriptModulePartAsset>(*module).await? + { + if matches!(module.await?.part, ModulePart::Exports) { + let module_part = EcmascriptModulePartAsset::select_part( + *module.await?.full_module, + ModulePart::export(export_name.clone()), + ); + + // If we apply this logic to EcmascriptModuleAsset, we will resolve everything in the + // target module. + if (Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module_part).await?) + .is_none() + { + return Ok(find_export_from_reexports( + Vc::upcast(module_part), + export_name, + )); + } + } + } + + let all_export_names = get_all_export_names(*module).await?; + let esm_export = all_export_names.esm_exports.get(&export_name).copied(); + Ok(FindExportFromReexportsResult { + esm_export, + dynamic_exporting_modules: all_export_names.dynamic_exporting_modules.clone(), + } + .cell()) +} + #[turbo_tasks::value] struct AllExportNamesResult { esm_exports: FxIndexMap<RcStr, ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, diff --git a/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs b/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs index b2e604aa67b6c..5b58d808047a7 100644 --- a/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs +++ b/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs @@ -122,7 +122,7 @@ impl EcmascriptModulePartAsset { pub async fn select_part( module: Vc<EcmascriptModuleAsset>, part: ModulePart, - ) -> Result<Vc<Box<dyn Module>>> { + ) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> { let SplitResult::Ok { entrypoints, .. } = &*split_module(module).await? else { return Ok(Vc::upcast(module)); }; diff --git a/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs b/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs index 646ff45569330..d68ab3a7e96d3 100644 --- a/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs +++ b/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs @@ -717,6 +717,19 @@ impl DepGraph { }, ))); + if !star_reexports.is_empty() { + let mut module = Module::dummy(); + outputs.insert(Key::StarExports, modules.len() as u32); + + for star in &star_reexports { + module + .body + .push(ModuleItem::ModuleDecl(ModuleDecl::ExportAll(star.clone()))); + } + + modules.push(module); + } + SplitModuleResult { entrypoints: outputs, part_deps, diff --git a/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs b/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs index c3b52006e64de..b55eba6349e3f 100644 --- a/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs @@ -374,6 +374,7 @@ pub(crate) enum Key { ModuleEvaluation, Export(RcStr), Exports, + StarExports, } /// Converts [ModulePart] to the index. @@ -407,7 +408,10 @@ async fn get_part_id(result: &SplitResult, part: &ModulePart) -> Result<u32> { // This is required to handle `export * from 'foo'` if let ModulePart::Export(..) = part { - if let Some(&v) = entrypoints.get(&Key::Exports) { + if let Some(&v) = entrypoints + .get(&Key::StarExports) + .or_else(|| entrypoints.get(&Key::Exports)) + { return Ok(v); } } diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/input/index.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/input/index.js similarity index 100% rename from turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/input/index.js rename to turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/input/index.js diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/options.json b/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/options.json similarity index 100% rename from turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/options.json rename to turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/options.json
diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs index 2d4ddd31547f0..aa6edae48152e 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs @@ -13,6 +13,7 @@ use turbopack_core::{ ChunkableModuleReference, ChunkingContext, ChunkingType, ChunkingTypeOption, ModuleChunkItemIdExt, + context::AssetContext, issue::{ Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, OptionIssueSource, OptionStyledString, StyledString, @@ -23,7 +24,7 @@ use turbopack_core::{ resolve::{ origin::{ResolveOrigin, ResolveOriginExt}, parse::Request, - ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem, + ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem, RequestKey, use turbopack_resolve::ecmascript::esm_resolve; @@ -38,6 +39,7 @@ use crate::{ runtime_functions::{TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE, TURBOPACK_IMPORT}, tree_shake::{asset::EcmascriptModulePartAsset, TURBOPACK_PART_IMPORT_SOURCE}, utils::module_id_to_lit, + TreeShakingMode, @@ -168,6 +170,32 @@ impl ModuleReference for EsmAssetReference { EcmaScriptModulesReferenceSubType::Import + if let Some(ModulePart::Evaluation) = &self.export_name { + let module: ResolvedVc<crate::EcmascriptModuleAsset> = + ResolvedVc::try_downcast_type(self.origin) + .expect("EsmAssetReference origin should be a EcmascriptModuleAsset"); + let tree_shaking_mode = module.options().await?.tree_shaking_mode; + if let Some(TreeShakingMode::ModuleFragments) = tree_shaking_mode { + let side_effect_free_packages = module.asset_context().side_effect_free_packages(); + if *module + .is_marked_as_side_effect_free(side_effect_free_packages) + .await? + { + return Ok(ModuleResolveResult { + primary: Box::new([( + RequestKey::default(), + ModuleResolveResultItem::Ignore, + )]), + affecting_sources: Default::default(), + } + .cell()); + } if let Request::Module { module, .. } = &*self.request.await? { if module == TURBOPACK_PART_IMPORT_SOURCE { if let Some(part) = &self.export_name { @@ -175,11 +203,11 @@ impl ModuleReference for EsmAssetReference { ResolvedVc::try_downcast_type(self.origin) .expect("EsmAssetReference origin should be a EcmascriptModuleAsset"); - return Ok(*ModuleResolveResult::module( + return Ok(*ModuleResolveResult::module(ResolvedVc::upcast( EcmascriptModulePartAsset::select_part(*module, part.clone()) .to_resolved() .await?, - )); + ))); } bail!("export_name is required for part import") diff --git a/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs b/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs index b8bf69ff6b8d8..4af63d3d54a70 100644 --- a/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs +++ b/turbopack/crates/turbopack-ecmascript/src/references/esm/export.rs @@ -24,6 +24,7 @@ use turbopack_core::{ module::Module, module_graph::ModuleGraph, reference::ModuleReference, + resolve::ModulePart, use super::base::ReferencedAsset; @@ -33,6 +34,8 @@ use crate::{ magic_identifier, parse::ParseResult, runtime_functions::{TURBOPACK_DYNAMIC, TURBOPACK_ESM}, + tree_shake::asset::EcmascriptModulePartAsset, + EcmascriptModuleAsset, #[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue)] @@ -177,9 +180,9 @@ pub async fn follow_reexports( // Try to find the export in the star exports if !exports_ref.star_exports.is_empty() && &*export_name != "default" { - let result = get_all_export_names(*module).await?; - if let Some(m) = result.esm_exports.get(&export_name) { + let result = find_export_from_reexports(*module, export_name.clone()).await?; + if let Some(m) = result.esm_export { + module = m; continue; } return match &result.dynamic_exporting_modules[..] { @@ -269,6 +272,48 @@ async fn handle_declared_export( })) +#[turbo_tasks::value] +struct FindExportFromReexportsResult { + dynamic_exporting_modules: Vec<ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, +#[turbo_tasks::function] + module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, + export_name: RcStr, +) -> Result<Vc<FindExportFromReexportsResult>> { + if let Some(module) = + Vc::try_resolve_downcast_type::<EcmascriptModulePartAsset>(*module).await? + if matches!(module.await?.part, ModulePart::Exports) { + let module_part = EcmascriptModulePartAsset::select_part( + *module.await?.full_module, + ModulePart::export(export_name.clone()), + // target module. + if (Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module_part).await?) + { + return Ok(find_export_from_reexports( + Vc::upcast(module_part), + export_name, + )); + Ok(FindExportFromReexportsResult { + esm_export, + .cell()) struct AllExportNamesResult { esm_exports: FxIndexMap<RcStr, ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, diff --git a/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs b/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs index b2e604aa67b6c..5b58d808047a7 100644 --- a/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs +++ b/turbopack/crates/turbopack-ecmascript/src/tree_shake/asset.rs @@ -122,7 +122,7 @@ impl EcmascriptModulePartAsset { pub async fn select_part( module: Vc<EcmascriptModuleAsset>, part: ModulePart, - ) -> Result<Vc<Box<dyn Module>>> { + ) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> { let SplitResult::Ok { entrypoints, .. } = &*split_module(module).await? else { return Ok(Vc::upcast(module)); diff --git a/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs b/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs index 646ff45569330..d68ab3a7e96d3 100644 --- a/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs +++ b/turbopack/crates/turbopack-ecmascript/src/tree_shake/graph.rs @@ -717,6 +717,19 @@ impl DepGraph { }, ))); + if !star_reexports.is_empty() { + let mut module = Module::dummy(); + outputs.insert(Key::StarExports, modules.len() as u32); + module + .body + .push(ModuleItem::ModuleDecl(ModuleDecl::ExportAll(star.clone()))); + modules.push(module); SplitModuleResult { entrypoints: outputs, part_deps, diff --git a/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs b/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs index c3b52006e64de..b55eba6349e3f 100644 --- a/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/tree_shake/mod.rs @@ -374,6 +374,7 @@ pub(crate) enum Key { ModuleEvaluation, Export(RcStr), Exports, + StarExports, /// Converts [ModulePart] to the index. @@ -407,7 +408,10 @@ async fn get_part_id(result: &SplitResult, part: &ModulePart) -> Result<u32> { // This is required to handle `export * from 'foo'` if let ModulePart::Export(..) = part { - if let Some(&v) = entrypoints.get(&Key::Exports) { + if let Some(&v) = entrypoints + .get(&Key::StarExports) + .or_else(|| entrypoints.get(&Key::Exports)) + { return Ok(v); } } diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/input/index.js b/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/input/index.js rename from turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/input/index.js rename to turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/input/index.js diff --git a/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/options.json b/turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/options.json rename from turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/.basic/options.json rename to turbopack/crates/turbopack-tests/tests/execution/turbopack/tree-shaking/basic/options.json
[ "- module = *m;", "+ esm_export: Option<ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>,", "+async fn find_export_from_reexports(", "+ {", "+ );", "+ // If we apply this logic to EcmascriptModuleAsset, we will resolve everything in the", "+ .is_none()", "+ let all_export_names = get_all_export_names(*module).await?;", "+ let esm_export = all_export_names.esm_exports.get(&export_name).copied();", "+ dynamic_exporting_modules: all_export_names.dynamic_exporting_modules.clone(),", "+ for star in &star_reexports {" ]
[ 103, 116, 121, 127, 132, 134, 137, 147, 148, 151, 184 ]
{ "additions": 98, "author": "kdy1", "deletions": 8, "html_url": "https://github.com/vercel/next.js/pull/78047", "issue_id": 78047, "merged_at": "2025-04-24T01:03:43Z", "omission_probability": 0.1, "pr_number": 78047, "repo": "vercel/next.js", "title": "feat(turbopack): Implement side-effect optimization", "total_changes": 106 }
342
diff --git a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx b/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx index 545e86581dae9..074dbbc38fec4 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx @@ -114,7 +114,7 @@ Tailwind CSS version 3.4.8 or newer will warn you about settings that might slow If you've added custom webpack settings, they might be slowing down compilation. -Consider if you really need them for local development. You can optionally only include certain tools for production builds, or explore moving to Turbopack and using [loaders](/docs/app/api-reference/config/next-config-js/turbo#supported-loaders). +Consider if you really need them for local development. You can optionally only include certain tools for production builds, or explore moving to Turbopack and using [loaders](/docs/app/api-reference/config/next-config-js/turbopack#supported-loaders). ### 6. Optimize memory usage diff --git a/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx b/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx index 73db3aede0c88..b6e22017595ea 100644 --- a/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx +++ b/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx @@ -557,7 +557,7 @@ Next.js automatically sets up TypeScript if you have a `tsconfig.json`. Make sur ## Bundler Compatibility -Both Create React App and Next.js default to webpack for bundling. Next.js also offers [Turbopack](/docs/app/api-reference/config/next-config-js/turbo) for faster local development with: +Both Create React App and Next.js default to webpack for bundling. Next.js also offers [Turbopack](/docs/app/api-reference/config/next-config-js/turbopack) for faster local development with: ```bash next dev --turbopack diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/turbo.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/turbopack.mdx similarity index 74% rename from docs/01-app/05-api-reference/05-config/01-next-config-js/turbo.mdx rename to docs/01-app/05-api-reference/05-config/01-next-config-js/turbopack.mdx index a5bc7801825ff..4d98fadc9ffc4 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/turbo.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/turbopack.mdx @@ -1,21 +1,18 @@ --- -title: turbo +title: turbopack description: Configure Next.js with Turbopack-specific options -version: experimental --- {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -The `turbo` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved. +The `turbopack` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved. ```ts filename="next.config.ts" switcher import type { NextConfig } from 'next' const nextConfig: NextConfig = { - experimental: { - turbo: { - // ... - }, + turbopack: { + // ... }, } @@ -25,10 +22,8 @@ export default nextConfig ```js filename="next.config.js" switcher /** @type {import('next').NextConfig} */ const nextConfig = { - experimental: { - turbo: { - // ... - }, + turbopack: { + // ... }, } @@ -47,12 +42,10 @@ The following options are available for the `turbo` configuration: | Option | Description | | ------------------- | ----------------------------------------------------------------------- | +| `root` | Sets the application root directory. Should be an absolute path. | | `rules` | List of supported webpack loaders to apply when running with Turbopack. | | `resolveAlias` | Map aliased imports to modules to load in their place. | | `resolveExtensions` | List of extensions to resolve when importing files. | -| `moduleIds` | Assign module IDs | -| `treeShaking` | Enable tree shaking for the turbopack dev server and build. | -| `memoryLimit` | A target memory limit for turbo, in bytes. | ### Supported loaders @@ -68,6 +61,29 @@ The following loaders have been tested to work with Turbopack's webpack loader i ## Examples +### Root directory + +Turbopack uses the root directory to resolve modules. Files outside of the project root are not resolved. + +Next.js automatically detects the root directory of your project. It does so by looking for one of these files: + +- `pnpm-lock.yaml` +- `package-lock.json` +- `yarn.lock` +- `bun.lock` +- `bun.lockb` + +If you have a different project structure, for example if you don't use workspaces, you can manually set the `root` option: + +```js filename="next.config.js" +const path = require('path') +module.exports = { + turbopack: { + root: path.join(__dirname, '..'), + }, +} +``` + ### Configuring webpack loaders If you need loader support beyond what's built in, many webpack loaders already work with Turbopack. There are currently some limitations: @@ -82,13 +98,11 @@ Here is an example below using the [`@svgr/webpack`](https://www.npmjs.com/packa ```js filename="next.config.js" module.exports = { - experimental: { - turbo: { - rules: { - '*.svg': { - loaders: ['@svgr/webpack'], - as: '*.js', - }, + turbopack: { + rules: { + '*.svg': { + loaders: ['@svgr/webpack'], + as: '*.js', }, }, }, @@ -105,12 +119,10 @@ To configure resolve aliases, map imported patterns to their new destination in ```js filename="next.config.js" module.exports = { - experimental: { - turbo: { - resolveAlias: { - underscore: 'lodash', - mocha: { browser: 'mocha/browser-entry.js' }, - }, + turbopack: { + resolveAlias: { + underscore: 'lodash', + mocha: { browser: 'mocha/browser-entry.js' }, }, }, } @@ -128,18 +140,8 @@ To configure resolve extensions, use the `resolveExtensions` field in `next.conf ```js filename="next.config.js" module.exports = { - experimental: { - turbo: { - resolveExtensions: [ - '.mdx', - '.tsx', - '.ts', - '.jsx', - '.js', - '.mjs', - '.json', - ], - }, + turbopack: { + resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.mjs', '.json'], }, } ``` @@ -148,27 +150,9 @@ This overwrites the original resolve extensions with the provided list. Make sur For more information and guidance for how to migrate your app to Turbopack from webpack, see [Turbopack's documentation on webpack compatibility](https://turbo.build/pack/docs/migrating-from-webpack). -### Assigning module IDs - -Turbopack currently supports two strategies for assigning module IDs: - -- `'named'` assigns readable module IDs based on the module's path and functionality. -- `'deterministic'` assigns small hashed numeric module IDs, which are mostly consistent between builds and therefore help with long-term caching. - -If not set, Turbopack will use `'named'` for development builds and `'deterministic'` for production builds. - -To configure the module IDs strategy, use the `moduleIds` field in `next.config.js`: - -```js filename="next.config.js" -module.exports = { - turbo: { - moduleIds: 'deterministic', - }, -} -``` - ## Version History -| Version | Changes | -| -------- | -------------------------------- | -| `13.0.0` | `experimental.turbo` introduced. | +| Version | Changes | +| -------- | ----------------------------------------------- | +| `15.3.0` | `experimental.turbo` is changed to `turbopack`. | +| `13.0.0` | `experimental.turbo` introduced. | diff --git a/docs/01-app/05-api-reference/08-turbopack.mdx b/docs/01-app/05-api-reference/08-turbopack.mdx index 9f26346e65b21..ac072f7702fc2 100644 --- a/docs/01-app/05-api-reference/08-turbopack.mdx +++ b/docs/01-app/05-api-reference/08-turbopack.mdx @@ -38,13 +38,13 @@ Turbopack in Next.js has **zero-configuration** for the common use cases. Below ### Language features -| Feature | Status | Notes | -| --------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **JavaScript & TypeScript** | **Supported** | Uses SWC under the hood. Type-checking is not done by Turbopack (run `tsc --watch` or rely on your IDE for type checks). | -| **ECMAScript (ESNext)** | **Supported** | Turbopack supports the latest ECMAScript features, matching SWC’s coverage. | -| **CommonJS** | **Supported** | `require()` syntax is handled out of the box. | -| **ESM** | **Supported** | Static and dynamic `import` are fully supported. | -| **Babel** | Partially Unsupported | Turbopack does not include Babel by default. However, you can [configure `babel-loader` via the Turbopack config](/docs/app/api-reference/config/next-config-js/turbo#configuring-webpack-loaders). | +| Feature | Status | Notes | +| --------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **JavaScript & TypeScript** | **Supported** | Uses SWC under the hood. Type-checking is not done by Turbopack (run `tsc --watch` or rely on your IDE for type checks). | +| **ECMAScript (ESNext)** | **Supported** | Turbopack supports the latest ECMAScript features, matching SWC’s coverage. | +| **CommonJS** | **Supported** | `require()` syntax is handled out of the box. | +| **ESM** | **Supported** | Static and dynamic `import` are fully supported. | +| **Babel** | Partially Unsupported | Turbopack does not include Babel by default. However, you can [configure `babel-loader` via the Turbopack config](/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders). | ### Framework and React features @@ -77,12 +77,12 @@ Turbopack in Next.js has **zero-configuration** for the common use cases. Below ### Module resolution -| Feature | Status | Notes | -| --------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Path Aliases** | **Supported** | Reads `tsconfig.json`'s `paths` and `baseUrl`, matching Next.js behavior. | -| **Manual Aliases** | **Supported** | [Configure `resolveAlias` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbo#resolving-aliases) (similar to `webpack.resolve.alias`). | -| **Custom Extensions** | **Supported** | [Configure `resolveExtensions` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbo#resolving-custom-extensions). | -| **AMD** | Partially Supported | Basic transforms work; advanced AMD usage is limited. | +| Feature | Status | Notes | +| --------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Path Aliases** | **Supported** | Reads `tsconfig.json`'s `paths` and `baseUrl`, matching Next.js behavior. | +| **Manual Aliases** | **Supported** | [Configure `resolveAlias` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbopack#resolving-aliases) (similar to `webpack.resolve.alias`). | +| **Custom Extensions** | **Supported** | [Configure `resolveExtensions` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbopack#resolving-custom-extensions). | +| **AMD** | Partially Supported | Basic transforms work; advanced AMD usage is limited. | ### Performance and Fast Refresh @@ -102,7 +102,7 @@ Some features are not yet implemented or not planned: - The `@value` rule (superseded by CSS variables). - `:import` and `:export` ICSS rules. - **`webpack()` configuration** in `next.config.js` - Turbopack replaces webpack, so `webpack()` configs are not recognized. Use the [`experimental.turbo` config](/docs/app/api-reference/config/next-config-js/turbo) instead. + Turbopack replaces webpack, so `webpack()` configs are not recognized. Use the [`experimental.turbo` config](/docs/app/api-reference/config/next-config-js/turbopack) instead. - **AMP** Not planned for Turbopack support in Next.js. - **Yarn PnP** @@ -118,14 +118,14 @@ Some features are not yet implemented or not planned: - `experimental.fallbackNodePolyfills` We plan to implement these in the future. -For a full, detailed breakdown of each feature flag and its status, see the [Turbopack API Reference](/docs/app/api-reference/config/next-config-js/turbo). +For a full, detailed breakdown of each feature flag and its status, see the [Turbopack API Reference](/docs/app/api-reference/config/next-config-js/turbopack). ## Configuration -Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the `experimental.turbo` key. Configuration options include: +Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the `turbopack` key. Configuration options include: - **`rules`** - Define additional [webpack loaders](/docs/app/api-reference/config/next-config-js/turbo#configuring-webpack-loaders) for file transformations. + Define additional [webpack loaders](/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders) for file transformations. - **`resolveAlias`** Create manual aliases (like `resolve.alias` in webpack). - **`resolveExtensions`** @@ -139,19 +139,17 @@ Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the ```js filename="next.config.js" module.exports = { - experimental: { - turbo: { - // Example: adding an alias and custom file extension - resolveAlias: { - underscore: 'lodash', - }, - resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.json'], + turbopack: { + // Example: adding an alias and custom file extension + resolveAlias: { + underscore: 'lodash', }, + resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.json'], }, } ``` -For more in-depth configuration examples, see the [Turbopack config documentation](/docs/app/api-reference/config/next-config-js/turbo). +For more in-depth configuration examples, see the [Turbopack config documentation](/docs/app/api-reference/config/next-config-js/turbopack). ## Generating trace files for performance debugging diff --git a/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx b/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx index 1be780969309f..6b55ded59ee31 100644 --- a/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx +++ b/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx @@ -2,7 +2,7 @@ title: turbo description: Configure Next.js with Turbopack-specific options version: experimental -source: app/api-reference/config/next-config-js/turbo +source: app/api-reference/config/next-config-js/turbopack --- {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
diff --git a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx b/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx index 545e86581dae9..074dbbc38fec4 100644 --- a/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx +++ b/docs/01-app/03-building-your-application/06-optimizing/14-local-development.mdx @@ -114,7 +114,7 @@ Tailwind CSS version 3.4.8 or newer will warn you about settings that might slow If you've added custom webpack settings, they might be slowing down compilation. -Consider if you really need them for local development. You can optionally only include certain tools for production builds, or explore moving to Turbopack and using [loaders](/docs/app/api-reference/config/next-config-js/turbo#supported-loaders). +Consider if you really need them for local development. You can optionally only include certain tools for production builds, or explore moving to Turbopack and using [loaders](/docs/app/api-reference/config/next-config-js/turbopack#supported-loaders). ### 6. Optimize memory usage diff --git a/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx b/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx index 73db3aede0c88..b6e22017595ea 100644 --- a/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx +++ b/docs/01-app/03-building-your-application/11-upgrading/06-from-create-react-app.mdx @@ -557,7 +557,7 @@ Next.js automatically sets up TypeScript if you have a `tsconfig.json`. Make sur ## Bundler Compatibility -Both Create React App and Next.js default to webpack for bundling. Next.js also offers [Turbopack](/docs/app/api-reference/config/next-config-js/turbo) for faster local development with: ```bash next dev --turbopack diff --git a/docs/01-app/05-api-reference/05-config/01-next-config-js/turbo.mdx b/docs/01-app/05-api-reference/05-config/01-next-config-js/turbopack.mdx similarity index 74% rename from docs/01-app/05-api-reference/05-config/01-next-config-js/turbo.mdx rename to docs/01-app/05-api-reference/05-config/01-next-config-js/turbopack.mdx index a5bc7801825ff..4d98fadc9ffc4 100644 --- a/docs/01-app/05-api-reference/05-config/01-next-config-js/turbo.mdx +++ b/docs/01-app/05-api-reference/05-config/01-next-config-js/turbopack.mdx @@ -1,21 +1,18 @@ -title: turbo +title: turbopack {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} -The `turbo` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved. +The `turbopack` option lets you customize [Turbopack](/docs/app/api-reference/turbopack) to transform different files and change how modules are resolved. ```ts filename="next.config.ts" switcher import type { NextConfig } from 'next' const nextConfig: NextConfig = { @@ -25,10 +22,8 @@ export default nextConfig ```js filename="next.config.js" switcher /** @type {import('next').NextConfig} */ const nextConfig = { @@ -47,12 +42,10 @@ The following options are available for the `turbo` configuration: | Option | Description | | ------------------- | ----------------------------------------------------------------------- | +| `root` | Sets the application root directory. Should be an absolute path. | | `rules` | List of supported webpack loaders to apply when running with Turbopack. | | `resolveAlias` | Map aliased imports to modules to load in their place. | | `resolveExtensions` | List of extensions to resolve when importing files. | -| `treeShaking` | Enable tree shaking for the turbopack dev server and build. | -| `memoryLimit` | A target memory limit for turbo, in bytes. | ### Supported loaders @@ -68,6 +61,29 @@ The following loaders have been tested to work with Turbopack's webpack loader i ## Examples +Turbopack uses the root directory to resolve modules. Files outside of the project root are not resolved. +Next.js automatically detects the root directory of your project. It does so by looking for one of these files: +- `pnpm-lock.yaml` +- `package-lock.json` +- `yarn.lock` +- `bun.lock` +- `bun.lockb` +If you have a different project structure, for example if you don't use workspaces, you can manually set the `root` option: +```js filename="next.config.js" +const path = require('path') +module.exports = { + root: path.join(__dirname, '..'), + }, +} +``` ### Configuring webpack loaders If you need loader support beyond what's built in, many webpack loaders already work with Turbopack. There are currently some limitations: @@ -82,13 +98,11 @@ Here is an example below using the [`@svgr/webpack`](https://www.npmjs.com/packa - rules: { - '*.svg': { - loaders: ['@svgr/webpack'], - as: '*.js', - }, + rules: { + '*.svg': { + loaders: ['@svgr/webpack'], }, @@ -105,12 +119,10 @@ To configure resolve aliases, map imported patterns to their new destination in - mocha: { browser: 'mocha/browser-entry.js' }, + mocha: { browser: 'mocha/browser-entry.js' }, @@ -128,18 +140,8 @@ To configure resolve extensions, use the `resolveExtensions` field in `next.conf - resolveExtensions: [ - '.mdx', - '.tsx', - '.ts', - '.jsx', - '.js', - '.mjs', - '.json', - ], + resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.mjs', '.json'], @@ -148,27 +150,9 @@ This overwrites the original resolve extensions with the provided list. Make sur For more information and guidance for how to migrate your app to Turbopack from webpack, see [Turbopack's documentation on webpack compatibility](https://turbo.build/pack/docs/migrating-from-webpack). -### Assigning module IDs -Turbopack currently supports two strategies for assigning module IDs: -- `'named'` assigns readable module IDs based on the module's path and functionality. -- `'deterministic'` assigns small hashed numeric module IDs, which are mostly consistent between builds and therefore help with long-term caching. -If not set, Turbopack will use `'named'` for development builds and `'deterministic'` for production builds. -To configure the module IDs strategy, use the `moduleIds` field in `next.config.js`: -```js filename="next.config.js" -module.exports = { - turbo: { - moduleIds: 'deterministic', - }, -} -``` ## Version History -| Version | Changes | -| `13.0.0` | `experimental.turbo` introduced. | +| Version | Changes | +| -------- | ----------------------------------------------- | +| `15.3.0` | `experimental.turbo` is changed to `turbopack`. | +| `13.0.0` | `experimental.turbo` introduced. | diff --git a/docs/01-app/05-api-reference/08-turbopack.mdx b/docs/01-app/05-api-reference/08-turbopack.mdx index 9f26346e65b21..ac072f7702fc2 100644 --- a/docs/01-app/05-api-reference/08-turbopack.mdx +++ b/docs/01-app/05-api-reference/08-turbopack.mdx @@ -38,13 +38,13 @@ Turbopack in Next.js has **zero-configuration** for the common use cases. Below ### Language features -| --------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **ECMAScript (ESNext)** | **Supported** | Turbopack supports the latest ECMAScript features, matching SWC’s coverage. | -| **CommonJS** | **Supported** | `require()` syntax is handled out of the box. | -| **Babel** | Partially Unsupported | Turbopack does not include Babel by default. However, you can [configure `babel-loader` via the Turbopack config](/docs/app/api-reference/config/next-config-js/turbo#configuring-webpack-loaders). | +| Feature | Status | Notes | +| --------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **JavaScript & TypeScript** | **Supported** | Uses SWC under the hood. Type-checking is not done by Turbopack (run `tsc --watch` or rely on your IDE for type checks). | +| **ECMAScript (ESNext)** | **Supported** | Turbopack supports the latest ECMAScript features, matching SWC’s coverage. | +| **CommonJS** | **Supported** | `require()` syntax is handled out of the box. | +| **ESM** | **Supported** | Static and dynamic `import` are fully supported. | +| **Babel** | Partially Unsupported | Turbopack does not include Babel by default. However, you can [configure `babel-loader` via the Turbopack config](/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders). | ### Framework and React features @@ -77,12 +77,12 @@ Turbopack in Next.js has **zero-configuration** for the common use cases. Below ### Module resolution -| Feature | Status | Notes | -| --------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Path Aliases** | **Supported** | Reads `tsconfig.json`'s `paths` and `baseUrl`, matching Next.js behavior. | -| **Manual Aliases** | **Supported** | [Configure `resolveAlias` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbo#resolving-aliases) (similar to `webpack.resolve.alias`). | -| **Custom Extensions** | **Supported** | [Configure `resolveExtensions` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbo#resolving-custom-extensions). | -| **AMD** | Partially Supported | Basic transforms work; advanced AMD usage is limited. | +| Feature | Status | Notes | +| --------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Path Aliases** | **Supported** | Reads `tsconfig.json`'s `paths` and `baseUrl`, matching Next.js behavior. | +| **Custom Extensions** | **Supported** | [Configure `resolveExtensions` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbopack#resolving-custom-extensions). | +| **AMD** | Partially Supported | Basic transforms work; advanced AMD usage is limited. | ### Performance and Fast Refresh @@ -102,7 +102,7 @@ Some features are not yet implemented or not planned: - The `@value` rule (superseded by CSS variables). - `:import` and `:export` ICSS rules. - **`webpack()` configuration** in `next.config.js` - Turbopack replaces webpack, so `webpack()` configs are not recognized. Use the [`experimental.turbo` config](/docs/app/api-reference/config/next-config-js/turbo) instead. + Turbopack replaces webpack, so `webpack()` configs are not recognized. Use the [`experimental.turbo` config](/docs/app/api-reference/config/next-config-js/turbopack) instead. - **AMP** Not planned for Turbopack support in Next.js. - **Yarn PnP** @@ -118,14 +118,14 @@ Some features are not yet implemented or not planned: - `experimental.fallbackNodePolyfills` We plan to implement these in the future. -For a full, detailed breakdown of each feature flag and its status, see the [Turbopack API Reference](/docs/app/api-reference/config/next-config-js/turbo). +For a full, detailed breakdown of each feature flag and its status, see the [Turbopack API Reference](/docs/app/api-reference/config/next-config-js/turbopack). ## Configuration -Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the `experimental.turbo` key. Configuration options include: +Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the `turbopack` key. Configuration options include: - **`rules`** - Define additional [webpack loaders](/docs/app/api-reference/config/next-config-js/turbo#configuring-webpack-loaders) for file transformations. + Define additional [webpack loaders](/docs/app/api-reference/config/next-config-js/turbopack#configuring-webpack-loaders) for file transformations. - **`resolveAlias`** Create manual aliases (like `resolve.alias` in webpack). - **`resolveExtensions`** @@ -139,19 +139,17 @@ Turbopack can be configured via `next.config.js` (or `next.config.ts`) under the - // Example: adding an alias and custom file extension - resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.json'], + // Example: adding an alias and custom file extension + resolveExtensions: ['.mdx', '.tsx', '.ts', '.jsx', '.js', '.json'], -For more in-depth configuration examples, see the [Turbopack config documentation](/docs/app/api-reference/config/next-config-js/turbo). +For more in-depth configuration examples, see the [Turbopack config documentation](/docs/app/api-reference/config/next-config-js/turbopack). ## Generating trace files for performance debugging diff --git a/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx b/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx index 1be780969309f..6b55ded59ee31 100644 --- a/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx +++ b/docs/02-pages/03-api-reference/04-config/01-next-config-js/turbo.mdx @@ -2,7 +2,7 @@ title: turbo version: experimental -source: app/api-reference/config/next-config-js/turbo +source: app/api-reference/config/next-config-js/turbopack {/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
[ "+Both Create React App and Next.js default to webpack for bundling. Next.js also offers [Turbopack](/docs/app/api-reference/config/next-config-js/turbopack) for faster local development with:", "-version: experimental", "-| `moduleIds` | Assign module IDs |", "+### Root directory", "+ as: '*.js',", "-| -------- | -------------------------------- |", "-| Feature | Status | Notes |", "-| **JavaScript & TypeScript** | **Supported** | Uses SWC under the hood. Type-checking is not done by Turbopack (run `tsc --watch` or rely on your IDE for type checks). |", "-| **ESM** | **Supported** | Static and dynamic `import` are fully supported. |", "+| **Manual Aliases** | **Supported** | [Configure `resolveAlias` in `next.config.js`](/docs/app/api-reference/config/next-config-js/turbopack#resolving-aliases) (similar to `webpack.resolve.alias`). |" ]
[ 22, 38, 80, 90, 131, 199, 213, 215, 218, 243 ]
{ "additions": 71, "author": "wbinnssmith", "deletions": 89, "html_url": "https://github.com/vercel/next.js/pull/77853", "issue_id": 77853, "merged_at": "2025-04-09T14:32:32Z", "omission_probability": 0.1, "pr_number": 77853, "repo": "vercel/next.js", "title": "Turbopack: update docs for `config.turbopack`", "total_changes": 160 }
343
diff --git a/crates/next-core/src/next_config.rs b/crates/next-core/src/next_config.rs index 07e4977451a9a..34c70a1e2445a 100644 --- a/crates/next-core/src/next_config.rs +++ b/crates/next-core/src/next_config.rs @@ -730,6 +730,8 @@ pub struct ExperimentalConfig { ppr: Option<ExperimentalPartialPrerendering>, taint: Option<bool>, react_owner_stack: Option<bool>, + #[serde(rename = "routerBFCache")] + router_bfcache: Option<bool>, proxy_timeout: Option<f64>, /// enables the minification of server code. server_minification: Option<bool>, @@ -1428,6 +1430,11 @@ impl NextConfig { Vc::cell(self.experimental.react_owner_stack.unwrap_or(false)) } + #[turbo_tasks::function] + pub fn enable_router_bfcache(&self) -> Vc<bool> { + Vc::cell(self.experimental.router_bfcache.unwrap_or(false)) + } + #[turbo_tasks::function] pub fn enable_view_transition(&self) -> Vc<bool> { Vc::cell(self.experimental.view_transition.unwrap_or(false)) diff --git a/crates/next-core/src/next_import_map.rs b/crates/next-core/src/next_import_map.rs index 0d9501e89496c..235e03b2ac7a9 100644 --- a/crates/next-core/src/next_import_map.rs +++ b/crates/next-core/src/next_import_map.rs @@ -122,6 +122,7 @@ pub async fn get_next_client_import_map( || *next_config.enable_taint().await? || *next_config.enable_react_owner_stack().await? || *next_config.enable_view_transition().await? + || *next_config.enable_router_bfcache().await? { "-experimental" } else { @@ -700,8 +701,9 @@ async fn rsc_aliases( let ppr = *next_config.enable_ppr().await?; let taint = *next_config.enable_taint().await?; let react_owner_stack = *next_config.enable_react_owner_stack().await?; + let router_bfcache = *next_config.enable_router_bfcache().await?; let view_transition = *next_config.enable_view_transition().await?; - let react_channel = if ppr || taint || react_owner_stack || view_transition { + let react_channel = if ppr || taint || react_owner_stack || view_transition || router_bfcache { "-experimental" } else { "" diff --git a/packages/next/src/build/webpack/plugins/define-env-plugin.ts b/packages/next/src/build/webpack/plugins/define-env-plugin.ts index 182adaed3761f..c555accac42ce 100644 --- a/packages/next/src/build/webpack/plugins/define-env-plugin.ts +++ b/packages/next/src/build/webpack/plugins/define-env-plugin.ts @@ -190,6 +190,9 @@ export function getDefineEnv({ 'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean( config.experimental.dynamicOnHover ), + 'process.env.__NEXT_ROUTER_BF_CACHE': Boolean( + config.experimental.routerBFCache + ), 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE': config.experimental.optimisticClientCache ?? true, 'process.env.__NEXT_MIDDLEWARE_PREFETCH': diff --git a/packages/next/src/lib/needs-experimental-react.ts b/packages/next/src/lib/needs-experimental-react.ts index faa3545db752b..26008128ecaa3 100644 --- a/packages/next/src/lib/needs-experimental-react.ts +++ b/packages/next/src/lib/needs-experimental-react.ts @@ -1,6 +1,7 @@ import type { NextConfig } from '../server/config-shared' export function needsExperimentalReact(config: NextConfig) { - const { ppr, taint, viewTransition } = config.experimental || {} - return Boolean(ppr || taint || viewTransition) + const { ppr, taint, viewTransition, routerBFCache } = + config.experimental || {} + return Boolean(ppr || taint || viewTransition || routerBFCache) } diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index 3424941a98364..544d149582b12 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -347,6 +347,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => taint: z.boolean().optional(), prerenderEarlyExit: z.boolean().optional(), proxyTimeout: z.number().gte(0).optional(), + routerBFCache: z.boolean().optional(), scrollRestoration: z.boolean().optional(), sri: z .object({ diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index f6a0f10c43c9b..a41b93601688c 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -471,6 +471,11 @@ export interface ExperimentalConfig { */ taint?: boolean + /** + * Enables the Back/Forward Cache for the router. + */ + routerBFCache?: boolean + serverActions?: { /** * Allows adjusting body parser size limit for server actions. @@ -1258,6 +1263,7 @@ export const defaultConfig: NextConfig = { optimizeServerReact: true, useEarlyImport: false, viewTransition: false, + routerBFCache: false, staleTimes: { dynamic: 0, static: 300, diff --git a/test/e2e/app-dir/back-forward-cache/app/layout.tsx b/test/e2e/app-dir/back-forward-cache/app/layout.tsx new file mode 100644 index 0000000000000..dbce4ea8e3aeb --- /dev/null +++ b/test/e2e/app-dir/back-forward-cache/app/layout.tsx @@ -0,0 +1,11 @@ +export default function RootLayout({ + children, +}: { + children: React.ReactNode +}) { + return ( + <html lang="en"> + <body>{children}</body> + </html> + ) +} diff --git a/test/e2e/app-dir/back-forward-cache/app/page.tsx b/test/e2e/app-dir/back-forward-cache/app/page.tsx new file mode 100644 index 0000000000000..3736ab466ec86 --- /dev/null +++ b/test/e2e/app-dir/back-forward-cache/app/page.tsx @@ -0,0 +1,15 @@ +'use client' + +// TODO: "use client" is required in this module because Activity is not +// exported from the server entrypoint of React + +// @ts-expect-error: Not yet part of the TypeScript types +import { unstable_Activity as Activity } from 'react' + +export default function Page() { + return ( + <Activity mode="hidden"> + <div id="activity-content">Hello</div> + </Activity> + ) +} diff --git a/test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts b/test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts new file mode 100644 index 0000000000000..0a5e12d0b8101 --- /dev/null +++ b/test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts @@ -0,0 +1,17 @@ +import { nextTestSetup } from 'e2e-utils' + +describe('back/forward cache', () => { + const { next } = nextTestSetup({ + files: __dirname, + }) + + it('Activity component is renderable when the routerBFCache flag is on', async () => { + // None of the back/forward behavior has been implemented yet; this just + // tests that when the flag is enabled, we're able to successfully render + // an Activity component. + const browser = await next.browser('/') + const activityContent = await browser.elementById('activity-content') + expect(await activityContent.innerHTML()).toBe('Hello') + expect(await activityContent.getComputedCss('display')).toBe('none') + }) +}) diff --git a/test/e2e/app-dir/back-forward-cache/next.config.js b/test/e2e/app-dir/back-forward-cache/next.config.js new file mode 100644 index 0000000000000..c64f7aa983d31 --- /dev/null +++ b/test/e2e/app-dir/back-forward-cache/next.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + experimental: { + routerBFCache: true, + }, +} + +module.exports = nextConfig
diff --git a/crates/next-core/src/next_config.rs b/crates/next-core/src/next_config.rs index 07e4977451a9a..34c70a1e2445a 100644 --- a/crates/next-core/src/next_config.rs +++ b/crates/next-core/src/next_config.rs @@ -730,6 +730,8 @@ pub struct ExperimentalConfig { ppr: Option<ExperimentalPartialPrerendering>, taint: Option<bool>, react_owner_stack: Option<bool>, + #[serde(rename = "routerBFCache")] + router_bfcache: Option<bool>, proxy_timeout: Option<f64>, /// enables the minification of server code. server_minification: Option<bool>, @@ -1428,6 +1430,11 @@ impl NextConfig { Vc::cell(self.experimental.react_owner_stack.unwrap_or(false)) } + #[turbo_tasks::function] + pub fn enable_router_bfcache(&self) -> Vc<bool> { + Vc::cell(self.experimental.router_bfcache.unwrap_or(false)) + } #[turbo_tasks::function] pub fn enable_view_transition(&self) -> Vc<bool> { Vc::cell(self.experimental.view_transition.unwrap_or(false)) diff --git a/crates/next-core/src/next_import_map.rs b/crates/next-core/src/next_import_map.rs index 0d9501e89496c..235e03b2ac7a9 100644 --- a/crates/next-core/src/next_import_map.rs +++ b/crates/next-core/src/next_import_map.rs @@ -122,6 +122,7 @@ pub async fn get_next_client_import_map( || *next_config.enable_taint().await? || *next_config.enable_react_owner_stack().await? || *next_config.enable_view_transition().await? + || *next_config.enable_router_bfcache().await? { "-experimental" } else { @@ -700,8 +701,9 @@ async fn rsc_aliases( let ppr = *next_config.enable_ppr().await?; let taint = *next_config.enable_taint().await?; let react_owner_stack = *next_config.enable_react_owner_stack().await?; + let router_bfcache = *next_config.enable_router_bfcache().await?; let view_transition = *next_config.enable_view_transition().await?; - let react_channel = if ppr || taint || react_owner_stack || view_transition { + let react_channel = if ppr || taint || react_owner_stack || view_transition || router_bfcache { "-experimental" } else { "" diff --git a/packages/next/src/build/webpack/plugins/define-env-plugin.ts b/packages/next/src/build/webpack/plugins/define-env-plugin.ts index 182adaed3761f..c555accac42ce 100644 --- a/packages/next/src/build/webpack/plugins/define-env-plugin.ts +++ b/packages/next/src/build/webpack/plugins/define-env-plugin.ts @@ -190,6 +190,9 @@ export function getDefineEnv({ 'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean( config.experimental.dynamicOnHover ), + 'process.env.__NEXT_ROUTER_BF_CACHE': Boolean( + config.experimental.routerBFCache + ), 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE': config.experimental.optimisticClientCache ?? true, 'process.env.__NEXT_MIDDLEWARE_PREFETCH': diff --git a/packages/next/src/lib/needs-experimental-react.ts b/packages/next/src/lib/needs-experimental-react.ts index faa3545db752b..26008128ecaa3 100644 --- a/packages/next/src/lib/needs-experimental-react.ts +++ b/packages/next/src/lib/needs-experimental-react.ts @@ -1,6 +1,7 @@ import type { NextConfig } from '../server/config-shared' export function needsExperimentalReact(config: NextConfig) { - return Boolean(ppr || taint || viewTransition) + const { ppr, taint, viewTransition, routerBFCache } = + config.experimental || {} + return Boolean(ppr || taint || viewTransition || routerBFCache) } diff --git a/packages/next/src/server/config-schema.ts b/packages/next/src/server/config-schema.ts index 3424941a98364..544d149582b12 100644 --- a/packages/next/src/server/config-schema.ts +++ b/packages/next/src/server/config-schema.ts @@ -347,6 +347,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => taint: z.boolean().optional(), prerenderEarlyExit: z.boolean().optional(), proxyTimeout: z.number().gte(0).optional(), + routerBFCache: z.boolean().optional(), scrollRestoration: z.boolean().optional(), sri: z .object({ diff --git a/packages/next/src/server/config-shared.ts b/packages/next/src/server/config-shared.ts index f6a0f10c43c9b..a41b93601688c 100644 --- a/packages/next/src/server/config-shared.ts +++ b/packages/next/src/server/config-shared.ts @@ -471,6 +471,11 @@ export interface ExperimentalConfig { */ taint?: boolean + /** + * Enables the Back/Forward Cache for the router. + */ + routerBFCache?: boolean serverActions?: { /** * Allows adjusting body parser size limit for server actions. @@ -1258,6 +1263,7 @@ export const defaultConfig: NextConfig = { optimizeServerReact: true, useEarlyImport: false, viewTransition: false, + routerBFCache: false, staleTimes: { dynamic: 0, static: 300, diff --git a/test/e2e/app-dir/back-forward-cache/app/layout.tsx b/test/e2e/app-dir/back-forward-cache/app/layout.tsx index 0000000000000..dbce4ea8e3aeb +++ b/test/e2e/app-dir/back-forward-cache/app/layout.tsx @@ -0,0 +1,11 @@ +export default function RootLayout({ + children, +}: { + children: React.ReactNode +}) { + <html lang="en"> + <body>{children}</body> + </html> diff --git a/test/e2e/app-dir/back-forward-cache/app/page.tsx b/test/e2e/app-dir/back-forward-cache/app/page.tsx index 0000000000000..3736ab466ec86 +++ b/test/e2e/app-dir/back-forward-cache/app/page.tsx @@ -0,0 +1,15 @@ +'use client' +// TODO: "use client" is required in this module because Activity is not +// exported from the server entrypoint of React +// @ts-expect-error: Not yet part of the TypeScript types +import { unstable_Activity as Activity } from 'react' +export default function Page() { + <Activity mode="hidden"> + <div id="activity-content">Hello</div> + </Activity> diff --git a/test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts b/test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts index 0000000000000..0a5e12d0b8101 +++ b/test/e2e/app-dir/back-forward-cache/back-forward-cache.test.ts @@ -0,0 +1,17 @@ +import { nextTestSetup } from 'e2e-utils' +describe('back/forward cache', () => { + files: __dirname, + it('Activity component is renderable when the routerBFCache flag is on', async () => { + // tests that when the flag is enabled, we're able to successfully render + // an Activity component. + const browser = await next.browser('/') + const activityContent = await browser.elementById('activity-content') + expect(await activityContent.innerHTML()).toBe('Hello') + expect(await activityContent.getComputedCss('display')).toBe('none') diff --git a/test/e2e/app-dir/back-forward-cache/next.config.js b/test/e2e/app-dir/back-forward-cache/next.config.js index 0000000000000..c64f7aa983d31 +++ b/test/e2e/app-dir/back-forward-cache/next.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('next').NextConfig} + */ +const nextConfig = { + experimental: { + routerBFCache: true, + }, +module.exports = nextConfig
[ "- const { ppr, taint, viewTransition } = config.experimental || {}", "+ const { next } = nextTestSetup({", "+ // None of the back/forward behavior has been implemented yet; this just", "+})" ]
[ 70, 159, 164, 172 ]
{ "additions": 76, "author": "acdlite", "deletions": 3, "html_url": "https://github.com/vercel/next.js/pull/77951", "issue_id": 77951, "merged_at": "2025-04-09T14:42:54Z", "omission_probability": 0.1, "pr_number": 77951, "repo": "vercel/next.js", "title": "Add experimental.routerBFCache to NextConfig", "total_changes": 79 }
344
diff --git a/errors/next-image-unconfigured-host.mdx b/errors/next-image-unconfigured-host.mdx index a20a9b6eaadd9..019b39516ec41 100644 --- a/errors/next-image-unconfigured-host.mdx +++ b/errors/next-image-unconfigured-host.mdx @@ -13,15 +13,7 @@ Add the protocol, hostname, port, and pathname to the `images.remotePatterns` co ```js filename="next.config.js" module.exports = { images: { - remotePatterns: [ - { - protocol: 'https', - hostname: 'assets.example.com', - port: '', - pathname: '/account123/**', - search: '', - }, - ], + remotePatterns: [new URL('https://assets.example.com/account123/**')], }, } ```
diff --git a/errors/next-image-unconfigured-host.mdx b/errors/next-image-unconfigured-host.mdx index a20a9b6eaadd9..019b39516ec41 100644 --- a/errors/next-image-unconfigured-host.mdx +++ b/errors/next-image-unconfigured-host.mdx @@ -13,15 +13,7 @@ Add the protocol, hostname, port, and pathname to the `images.remotePatterns` co ```js filename="next.config.js" module.exports = { images: { - remotePatterns: [ - { - protocol: 'https', - hostname: 'assets.example.com', - port: '', - pathname: '/account123/**', - search: '', - }, + remotePatterns: [new URL('https://assets.example.com/account123/**')], }, } ```
[ "- ]," ]
[ 16 ]
{ "additions": 1, "author": "styfle", "deletions": 9, "html_url": "https://github.com/vercel/next.js/pull/77977", "issue_id": 77977, "merged_at": "2025-04-09T15:32:37Z", "omission_probability": 0.1, "pr_number": 77977, "repo": "vercel/next.js", "title": "Revert \"docs: revert image 15.3 change until live\"", "total_changes": 10 }
345
diff --git a/test/rspack-build-tests-manifest.json b/test/rspack-build-tests-manifest.json index cf9a71f8d3349..9457238234eec 100644 --- a/test/rspack-build-tests-manifest.json +++ b/test/rspack-build-tests-manifest.json @@ -5732,10 +5732,11 @@ }, "test/e2e/app-dir/use-cache-unknown-cache-kind/use-cache-unknown-cache-kind.test.ts": { "passed": [ - "use-cache-unknown-cache-kind should fail the build with an error", "use-cache-unknown-cache-kind should not fail the build for default cache kinds" ], - "failed": [], + "failed": [ + "use-cache-unknown-cache-kind should fail the build with an error" + ], "pending": [], "flakey": [], "runtimeError": false @@ -18979,10 +18980,11 @@ }, "test/production/pnpm-support/index.test.ts": { "passed": [ - "pnpm support should build with dependencies installed via pnpm", + "pnpm support should build with dependencies installed via pnpm" + ], + "failed": [ "pnpm support should execute client-side JS on each page in output: \"standalone\"" ], - "failed": [], "pending": [], "flakey": [], "runtimeError": false
diff --git a/test/rspack-build-tests-manifest.json b/test/rspack-build-tests-manifest.json index cf9a71f8d3349..9457238234eec 100644 --- a/test/rspack-build-tests-manifest.json +++ b/test/rspack-build-tests-manifest.json @@ -5732,10 +5732,11 @@ "test/e2e/app-dir/use-cache-unknown-cache-kind/use-cache-unknown-cache-kind.test.ts": { - "use-cache-unknown-cache-kind should fail the build with an error", "use-cache-unknown-cache-kind should not fail the build for default cache kinds" + "use-cache-unknown-cache-kind should fail the build with an error" @@ -18979,10 +18980,11 @@ "test/production/pnpm-support/index.test.ts": { - "pnpm support should build with dependencies installed via pnpm", + "pnpm support should build with dependencies installed via pnpm" "pnpm support should execute client-side JS on each page in output: \"standalone\""
[]
[]
{ "additions": 6, "author": "vercel-release-bot", "deletions": 4, "html_url": "https://github.com/vercel/next.js/pull/77958", "issue_id": 77958, "merged_at": "2025-04-09T16:12:36Z", "omission_probability": 0.1, "pr_number": 77958, "repo": "vercel/next.js", "title": "Update bundler production test manifest", "total_changes": 10 }
346
diff --git a/test/rspack-dev-tests-manifest.json b/test/rspack-dev-tests-manifest.json index 4bf9e16ccaf63..797662f1acbbf 100644 --- a/test/rspack-dev-tests-manifest.json +++ b/test/rspack-dev-tests-manifest.json @@ -2213,12 +2213,13 @@ "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cacheTag is not allowed", "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expirePath is not allowed", "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expireTag is not allowed", - "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_noStore is allowed", + "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_noStore is allowed" + ], + "failed": [ "Error Overlay for server components compiler errors in pages importing 'next/headers' in pages", "Error Overlay for server components compiler errors in pages importing 'server-only' in pages", "Error Overlay for server components compiler errors in pages importing after from 'next/server' in pages" ], - "failed": [], "pending": [], "flakey": [], "runtimeError": false @@ -2270,8 +2271,8 @@ "runtimeError": false }, "test/development/app-dir/build-error-logs/build-error-logs.test.ts": { - "passed": ["build-error-logs should only log error a single time"], - "failed": [], + "passed": [], + "failed": ["build-error-logs should only log error a single time"], "pending": [], "flakey": [], "runtimeError": false @@ -2385,11 +2386,10 @@ }, "test/development/app-dir/edge-errors-hmr/index.test.ts": { "passed": [ + "develop - app-dir - edge errros hmr should recover from build errors when client component error", "develop - app-dir - edge errros hmr should recover from build errors when server component error" ], - "failed": [ - "develop - app-dir - edge errros hmr should recover from build errors when client component error" - ], + "failed": [], "pending": [], "flakey": [], "runtimeError": false @@ -3827,6 +3827,7 @@ "app-dir action handling Edge SSR should handle calls to redirect() with a relative URL in a single pass", "app-dir action handling Edge SSR should handle calls to redirect() with external URLs", "app-dir action handling Edge SSR should return error response for hoc auth wrappers in edge runtime", + "app-dir action handling HMR should support updating the action", "app-dir action handling caching disabled by default should not override force-cache in server action", "app-dir action handling caching disabled by default should not override revalidate in server action", "app-dir action handling caching disabled by default should use no-store as default for server action", @@ -3845,6 +3846,7 @@ "app-dir action handling fetch actions should revalidate when cookies.set is called", "app-dir action handling fetch actions should revalidate when cookies.set is called in a client action", "app-dir action handling fetch actions should store revalidation data in the prefetch cache", + "app-dir action handling redirects displays searchParams correctly when redirecting with SearchParams", "app-dir action handling redirects merges cookies correctly when redirecting", "app-dir action handling redirects redirects properly when server action handler redirects with a 307 status code", "app-dir action handling redirects redirects properly when server action handler redirects with a 308 status code", @@ -3858,6 +3860,8 @@ "app-dir action handling should be possible to catch network errors", "app-dir action handling should be possible to catch regular errors", "app-dir action handling should bundle external libraries if they are on the action layer", + "app-dir action handling should forward action request to a worker that contains the action handler (edge)", + "app-dir action handling should forward action request to a worker that contains the action handler (node)", "app-dir action handling should handle action correctly with middleware rewrite", "app-dir action handling should handle actions executed in quick succession", "app-dir action handling should handle basic actions correctly", @@ -3866,6 +3870,7 @@ "app-dir action handling should log a warning when a server action is not found but an id is provided", "app-dir action handling should not block navigation events while a server action is in flight", "app-dir action handling should not block router.back() while a server action is in flight", + "app-dir action handling should not error when a forwarded action triggers a redirect (edge)", "app-dir action handling should not error when a forwarded action triggers a redirect (node)", "app-dir action handling should not log errors for non-action form POSTs", "app-dir action handling should only submit action once when resubmitting an action after navigation", @@ -3897,12 +3902,7 @@ "app-dir action handling should work with interception routes" ], "failed": [ - "app-dir action handling Edge SSR should handle unicode search params", - "app-dir action handling HMR should support updating the action", - "app-dir action handling redirects displays searchParams correctly when redirecting with SearchParams", - "app-dir action handling should forward action request to a worker that contains the action handler (edge)", - "app-dir action handling should forward action request to a worker that contains the action handler (node)", - "app-dir action handling should not error when a forwarded action triggers a redirect (edge)" + "app-dir action handling Edge SSR should handle unicode search params" ], "pending": [ "app-dir action handling fetch actions should handle unstable_expireTag + redirect", @@ -4741,6 +4741,7 @@ "app dir - basic <Link /> should replace to external url", "app dir - basic <Link /> should soft push", "app dir - basic <Link /> should soft replace", + "app dir - basic HMR should HMR correctly for client component", "app dir - basic HMR should HMR correctly for server component", "app dir - basic bootstrap scripts should fail to bootstrap when using CSP in Dev due to eval", "app dir - basic bootstrap scripts should only bootstrap with one script, prinitializing the rest", @@ -4763,7 +4764,6 @@ "app dir - basic next/script should pass nonce when using next/font", "app dir - basic next/script should pass on extra props for beforeInteractive scripts with a src prop", "app dir - basic next/script should pass on extra props for beforeInteractive scripts without a src prop", - "app dir - basic next/script should support next/script and render in correct order", "app dir - basic rewrites should support rewrites on client-side navigation", "app dir - basic rewrites should support rewrites on client-side navigation from pages to app with existing pages path", "app dir - basic rewrites should support rewrites on initial load", @@ -4830,7 +4830,7 @@ ], "failed": [ "app dir - basic <Link /> should navigate to pages dynamic route from pages page if it overlaps with an app page", - "app dir - basic HMR should HMR correctly for client component", + "app dir - basic next/script should support next/script and render in correct order", "app dir - basic should serve polyfills for browsers that do not support modules" ], "pending": [ @@ -6681,8 +6681,10 @@ "app dir - navigation hash-with-scroll-offset should scroll to the specified hash", "app dir - navigation locale warnings should have no warnings in pages router", "app dir - navigation locale warnings should warn about using the `locale` prop with `next/link` in app router", + "app dir - navigation middleware redirect should change browser location when router.refresh() gets a redirect response", "app dir - navigation navigating to a page with async metadata shows a fallback when prefetch completed", "app dir - navigation navigating to a page with async metadata shows a fallback when prefetch was pending", + "app dir - navigation navigating to dynamic params & changing the casing should load the page correctly", "app dir - navigation navigation between pages and app should not contain _rsc query while navigating from app to pages", "app dir - navigation navigation between pages and app should not contain _rsc query while navigating from pages to app", "app dir - navigation navigation between pages and app should not omit the hash while navigating from app to pages", @@ -6721,10 +6723,7 @@ "app dir - navigation useRouter identity between navigations should preserve identity when navigating between different pages", "app dir - navigation useRouter identity between navigations should preserve identity when navigating to the same page" ], - "failed": [ - "app dir - navigation middleware redirect should change browser location when router.refresh() gets a redirect response", - "app dir - navigation navigating to dynamic params & changing the casing should load the page correctly" - ], + "failed": [], "pending": [], "flakey": [], "runtimeError": false @@ -7305,6 +7304,7 @@ "parallel-routes-and-interception parallel routes should support parallel route tab bars", "parallel-routes-and-interception parallel routes should support parallel routes with no page component", "parallel-routes-and-interception parallel routes should throw a 404 when no matching parallel route is found", + "parallel-routes-and-interception route intercepting should intercept on routes that contain hyphenated/special dynamic params", "parallel-routes-and-interception route intercepting should re-render the layout on the server when it had a default child route", "parallel-routes-and-interception route intercepting should render an intercepted route at the top level from a nested path", "parallel-routes-and-interception route intercepting should render an intercepted route from a slot", @@ -7318,9 +7318,7 @@ "parallel-routes-and-interception route intercepting with dynamic routes should render intercepted route", "parallel-routes-and-interception-conflicting-pages should gracefully handle when two page segments match the `children` parallel slot" ], - "failed": [ - "parallel-routes-and-interception route intercepting should intercept on routes that contain hyphenated/special dynamic params" - ], + "failed": [], "pending": [], "flakey": [], "runtimeError": false @@ -8010,6 +8008,7 @@ "app dir - rsc basics next internal shared context should not error if just load next/router module in app page", "app dir - rsc basics react@experimental should opt into the react@experimental when enabling ppr", "app dir - rsc basics react@experimental should opt into the react@experimental when enabling taint", + "app dir - rsc basics should be able to navigate between rsc routes", "app dir - rsc basics should correctly render component returning null", "app dir - rsc basics should correctly render component returning undefined", "app dir - rsc basics should correctly render layout returning null", @@ -8042,8 +8041,7 @@ "app dir - rsc basics should use canary react for app" ], "failed": [ - "app dir - rsc basics should be able to call legacy react-dom/server APIs in client components", - "app dir - rsc basics should be able to navigate between rsc routes" + "app dir - rsc basics should be able to call legacy react-dom/server APIs in client components" ], "pending": [ "app dir - rsc basics should support partial hydration with inlined server data in browser" @@ -8985,12 +8983,11 @@ "runtimeError": false }, "test/e2e/app-dir/use-cache-unknown-cache-kind/use-cache-unknown-cache-kind.test.ts": { - "passed": [], - "failed": [ + "passed": [ "use-cache-unknown-cache-kind should not show an error for default cache kinds", - "use-cache-unknown-cache-kind should recover from the build error if the cache handler is defined", - "use-cache-unknown-cache-kind should show a build error" + "use-cache-unknown-cache-kind should recover from the build error if the cache handler is defined" ], + "failed": ["use-cache-unknown-cache-kind should show a build error"], "pending": [], "flakey": [], "runtimeError": false @@ -10011,18 +10008,17 @@ }, "test/e2e/instrumentation-hook/instrumentation-hook.test.ts": { "passed": [ + "Instrumentation Hook general should not overlap with a instrumentation page", "Instrumentation Hook with-async-edge-page with-async-edge-page should run the instrumentation hook", "Instrumentation Hook with-async-node-page with-async-node-page should run the instrumentation hook", "Instrumentation Hook with-edge-api with-edge-api should run the instrumentation hook", "Instrumentation Hook with-edge-page with-edge-page should run the instrumentation hook", + "Instrumentation Hook with-esm-import with-esm-import should run the instrumentation hook", "Instrumentation Hook with-middleware with-middleware should run the instrumentation hook", "Instrumentation Hook with-node-api with-node-api should run the instrumentation hook", "Instrumentation Hook with-node-page with-node-page should run the instrumentation hook" ], - "failed": [ - "Instrumentation Hook general should not overlap with a instrumentation page", - "Instrumentation Hook with-esm-import with-esm-import should run the instrumentation hook" - ], + "failed": [], "pending": [ "Instrumentation Hook general should reload the server when the instrumentation hook changes" ], @@ -10944,8 +10940,7 @@ "runtimeError": false }, "test/e2e/opentelemetry/client-trace-metadata/client-trace-metadata.test.ts": { - "passed": [], - "failed": [ + "passed": [ "clientTraceMetadata app router hard loading a dynamic page twice should yield different dynamic trace data", "clientTraceMetadata app router next dev only should inject propagation data for a statically server-side-rendered page", "clientTraceMetadata app router next dev only soft navigating to a dynamic page should not transform previous propagation data", @@ -10958,6 +10953,7 @@ "clientTraceMetadata pages router next dev only soft navigating to a static page should not transform previous propagation data", "clientTraceMetadata pages router should inject propagation data for a dynamically server-side-rendered page" ], + "failed": [], "pending": [], "flakey": [], "runtimeError": false @@ -11226,11 +11222,11 @@ "runtimeError": false }, "test/e2e/rsc-layers-transform/rsc-layers-transform.test.ts": { - "passed": [], - "failed": [ + "passed": [ "rsc layers transform should call instrumentation hook without errors", "rsc layers transform should render installed react-server condition for middleware" ], + "failed": [], "pending": [], "flakey": [], "runtimeError": false
diff --git a/test/rspack-dev-tests-manifest.json b/test/rspack-dev-tests-manifest.json index 4bf9e16ccaf63..797662f1acbbf 100644 --- a/test/rspack-dev-tests-manifest.json +++ b/test/rspack-dev-tests-manifest.json @@ -2213,12 +2213,13 @@ "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cacheTag is not allowed", "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expirePath is not allowed", "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expireTag is not allowed", - "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_noStore is allowed", + "Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_noStore is allowed" + "failed": [ "Error Overlay for server components compiler errors in pages importing 'next/headers' in pages", "Error Overlay for server components compiler errors in pages importing 'server-only' in pages", "Error Overlay for server components compiler errors in pages importing after from 'next/server' in pages" @@ -2270,8 +2271,8 @@ "test/development/app-dir/build-error-logs/build-error-logs.test.ts": { - "passed": ["build-error-logs should only log error a single time"], + "passed": [], + "failed": ["build-error-logs should only log error a single time"], @@ -2385,11 +2386,10 @@ "test/development/app-dir/edge-errors-hmr/index.test.ts": { "develop - app-dir - edge errros hmr should recover from build errors when server component error" @@ -3827,6 +3827,7 @@ "app-dir action handling Edge SSR should handle calls to redirect() with a relative URL in a single pass", "app-dir action handling Edge SSR should handle calls to redirect() with external URLs", "app-dir action handling Edge SSR should return error response for hoc auth wrappers in edge runtime", "app-dir action handling caching disabled by default should not override force-cache in server action", "app-dir action handling caching disabled by default should not override revalidate in server action", "app-dir action handling caching disabled by default should use no-store as default for server action", @@ -3845,6 +3846,7 @@ "app-dir action handling fetch actions should revalidate when cookies.set is called", "app-dir action handling fetch actions should revalidate when cookies.set is called in a client action", "app-dir action handling fetch actions should store revalidation data in the prefetch cache", + "app-dir action handling redirects displays searchParams correctly when redirecting with SearchParams", "app-dir action handling redirects merges cookies correctly when redirecting", "app-dir action handling redirects redirects properly when server action handler redirects with a 307 status code", "app-dir action handling redirects redirects properly when server action handler redirects with a 308 status code", @@ -3858,6 +3860,8 @@ "app-dir action handling should be possible to catch network errors", "app-dir action handling should be possible to catch regular errors", "app-dir action handling should bundle external libraries if they are on the action layer", + "app-dir action handling should forward action request to a worker that contains the action handler (edge)", + "app-dir action handling should forward action request to a worker that contains the action handler (node)", "app-dir action handling should handle action correctly with middleware rewrite", "app-dir action handling should handle actions executed in quick succession", "app-dir action handling should handle basic actions correctly", @@ -3866,6 +3870,7 @@ "app-dir action handling should log a warning when a server action is not found but an id is provided", "app-dir action handling should not block navigation events while a server action is in flight", "app-dir action handling should not block router.back() while a server action is in flight", + "app-dir action handling should not error when a forwarded action triggers a redirect (edge)", "app-dir action handling should not error when a forwarded action triggers a redirect (node)", "app-dir action handling should not log errors for non-action form POSTs", "app-dir action handling should only submit action once when resubmitting an action after navigation", @@ -3897,12 +3902,7 @@ "app-dir action handling should work with interception routes" - "app-dir action handling Edge SSR should handle unicode search params", - "app-dir action handling HMR should support updating the action", - "app-dir action handling redirects displays searchParams correctly when redirecting with SearchParams", - "app-dir action handling should forward action request to a worker that contains the action handler (edge)", - "app-dir action handling should forward action request to a worker that contains the action handler (node)", - "app-dir action handling should not error when a forwarded action triggers a redirect (edge)" + "app-dir action handling Edge SSR should handle unicode search params" "app-dir action handling fetch actions should handle unstable_expireTag + redirect", @@ -4741,6 +4741,7 @@ "app dir - basic <Link /> should replace to external url", "app dir - basic <Link /> should soft push", "app dir - basic <Link /> should soft replace", + "app dir - basic HMR should HMR correctly for client component", "app dir - basic HMR should HMR correctly for server component", "app dir - basic bootstrap scripts should fail to bootstrap when using CSP in Dev due to eval", "app dir - basic bootstrap scripts should only bootstrap with one script, prinitializing the rest", @@ -4763,7 +4764,6 @@ "app dir - basic next/script should pass nonce when using next/font", "app dir - basic next/script should pass on extra props for beforeInteractive scripts with a src prop", "app dir - basic next/script should pass on extra props for beforeInteractive scripts without a src prop", - "app dir - basic next/script should support next/script and render in correct order", "app dir - basic rewrites should support rewrites on client-side navigation", "app dir - basic rewrites should support rewrites on client-side navigation from pages to app with existing pages path", "app dir - basic rewrites should support rewrites on initial load", @@ -4830,7 +4830,7 @@ "app dir - basic <Link /> should navigate to pages dynamic route from pages page if it overlaps with an app page", - "app dir - basic HMR should HMR correctly for client component", + "app dir - basic next/script should support next/script and render in correct order", "app dir - basic should serve polyfills for browsers that do not support modules" @@ -6681,8 +6681,10 @@ "app dir - navigation hash-with-scroll-offset should scroll to the specified hash", "app dir - navigation locale warnings should have no warnings in pages router", "app dir - navigation locale warnings should warn about using the `locale` prop with `next/link` in app router", + "app dir - navigation middleware redirect should change browser location when router.refresh() gets a redirect response", "app dir - navigation navigating to a page with async metadata shows a fallback when prefetch completed", "app dir - navigation navigating to a page with async metadata shows a fallback when prefetch was pending", + "app dir - navigation navigating to dynamic params & changing the casing should load the page correctly", "app dir - navigation navigation between pages and app should not contain _rsc query while navigating from app to pages", "app dir - navigation navigation between pages and app should not contain _rsc query while navigating from pages to app", "app dir - navigation navigation between pages and app should not omit the hash while navigating from app to pages", @@ -6721,10 +6723,7 @@ "app dir - navigation useRouter identity between navigations should preserve identity when navigating between different pages", "app dir - navigation useRouter identity between navigations should preserve identity when navigating to the same page" - "app dir - navigation middleware redirect should change browser location when router.refresh() gets a redirect response", - "app dir - navigation navigating to dynamic params & changing the casing should load the page correctly" @@ -7305,6 +7304,7 @@ "parallel-routes-and-interception parallel routes should support parallel route tab bars", "parallel-routes-and-interception parallel routes should support parallel routes with no page component", "parallel-routes-and-interception parallel routes should throw a 404 when no matching parallel route is found", + "parallel-routes-and-interception route intercepting should intercept on routes that contain hyphenated/special dynamic params", "parallel-routes-and-interception route intercepting should re-render the layout on the server when it had a default child route", "parallel-routes-and-interception route intercepting should render an intercepted route at the top level from a nested path", "parallel-routes-and-interception route intercepting should render an intercepted route from a slot", @@ -7318,9 +7318,7 @@ "parallel-routes-and-interception route intercepting with dynamic routes should render intercepted route", "parallel-routes-and-interception-conflicting-pages should gracefully handle when two page segments match the `children` parallel slot" - "parallel-routes-and-interception route intercepting should intercept on routes that contain hyphenated/special dynamic params" @@ -8010,6 +8008,7 @@ "app dir - rsc basics next internal shared context should not error if just load next/router module in app page", "app dir - rsc basics react@experimental should opt into the react@experimental when enabling ppr", "app dir - rsc basics react@experimental should opt into the react@experimental when enabling taint", + "app dir - rsc basics should be able to navigate between rsc routes", "app dir - rsc basics should correctly render component returning null", "app dir - rsc basics should correctly render component returning undefined", "app dir - rsc basics should correctly render layout returning null", @@ -8042,8 +8041,7 @@ "app dir - rsc basics should use canary react for app" - "app dir - rsc basics should be able to call legacy react-dom/server APIs in client components", - "app dir - rsc basics should be able to navigate between rsc routes" + "app dir - rsc basics should be able to call legacy react-dom/server APIs in client components" "app dir - rsc basics should support partial hydration with inlined server data in browser" @@ -8985,12 +8983,11 @@ "test/e2e/app-dir/use-cache-unknown-cache-kind/use-cache-unknown-cache-kind.test.ts": { "use-cache-unknown-cache-kind should not show an error for default cache kinds", - "use-cache-unknown-cache-kind should recover from the build error if the cache handler is defined", - "use-cache-unknown-cache-kind should show a build error" + "use-cache-unknown-cache-kind should recover from the build error if the cache handler is defined" + "failed": ["use-cache-unknown-cache-kind should show a build error"], @@ -10011,18 +10008,17 @@ "test/e2e/instrumentation-hook/instrumentation-hook.test.ts": { + "Instrumentation Hook general should not overlap with a instrumentation page", "Instrumentation Hook with-async-edge-page with-async-edge-page should run the instrumentation hook", "Instrumentation Hook with-async-node-page with-async-node-page should run the instrumentation hook", "Instrumentation Hook with-edge-api with-edge-api should run the instrumentation hook", "Instrumentation Hook with-edge-page with-edge-page should run the instrumentation hook", + "Instrumentation Hook with-esm-import with-esm-import should run the instrumentation hook", "Instrumentation Hook with-middleware with-middleware should run the instrumentation hook", "Instrumentation Hook with-node-api with-node-api should run the instrumentation hook", "Instrumentation Hook with-node-page with-node-page should run the instrumentation hook" - "Instrumentation Hook general should not overlap with a instrumentation page", - "Instrumentation Hook with-esm-import with-esm-import should run the instrumentation hook" "Instrumentation Hook general should reload the server when the instrumentation hook changes" @@ -10944,8 +10940,7 @@ "test/e2e/opentelemetry/client-trace-metadata/client-trace-metadata.test.ts": { "clientTraceMetadata app router hard loading a dynamic page twice should yield different dynamic trace data", "clientTraceMetadata app router next dev only should inject propagation data for a statically server-side-rendered page", "clientTraceMetadata app router next dev only soft navigating to a dynamic page should not transform previous propagation data", @@ -10958,6 +10953,7 @@ "clientTraceMetadata pages router next dev only soft navigating to a static page should not transform previous propagation data", "clientTraceMetadata pages router should inject propagation data for a dynamically server-side-rendered page" @@ -11226,11 +11222,11 @@ "test/e2e/rsc-layers-transform/rsc-layers-transform.test.ts": { "rsc layers transform should call instrumentation hook without errors", "rsc layers transform should render installed react-server condition for middleware"
[ "+ ],", "+ \"develop - app-dir - edge errros hmr should recover from build errors when client component error\",", "- \"develop - app-dir - edge errros hmr should recover from build errors when client component error\"", "+ \"app-dir action handling HMR should support updating the action\"," ]
[ 10, 35, 39, 49 ]
{ "additions": 32, "author": "vercel-release-bot", "deletions": 36, "html_url": "https://github.com/vercel/next.js/pull/77959", "issue_id": 77959, "merged_at": "2025-04-09T16:14:37Z", "omission_probability": 0.1, "pr_number": 77959, "repo": "vercel/next.js", "title": "Update bundler development test manifest", "total_changes": 68 }
347
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 89a9c7dda34454..7451611ff3270d 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -69,8 +69,9 @@ If a window is focusable, it is part of the "navigation stack", that is, editor commands such as :windo, |CTRL-W|, etc., will consider the window as one that can be made the "current window". A non-focusable window will be skipped by such commands (though it can be explicitly focused by -|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, and -are not counted by the default 'tabline'. +|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, +or counted by the default 'tabline'. Their buffer content is not included +in 'complete' "w" completion. Windows (especially floating windows) can have many other |api-win_config| properties such as "hide" and "fixed" which also affect behavior. diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index 3e206a2cf53fe0..2582213db044d1 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2460,8 +2460,8 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) while (true) { // Move to next window (wrap to first window if at the end) wp = (wp->w_next != NULL) ? wp->w_next : firstwin; - // Break if we're back at start or found an unscanned buffer - if (wp == curwin || !wp->w_buffer->b_scanned) { + // Break if we're back at start or found an unscanned buffer (in a focusable window) + if (wp == curwin || (!wp->w_buffer->b_scanned && wp->w_config.focusable)) { break; } } diff --git a/test/functional/editor/completion_spec.lua b/test/functional/editor/completion_spec.lua index 3e5d0e48e8afdb..8b22295b09996e 100644 --- a/test/functional/editor/completion_spec.lua +++ b/test/functional/editor/completion_spec.lua @@ -1351,4 +1351,26 @@ describe('completion', function() eq('completeopt option does not include popup', api.nvim_get_var('err_msg')) end) end) + + it([[does not include buffer from non-focusable window for 'complete' "w"]], function() + local buf = api.nvim_create_buf(false, true) + local cfg = { focusable = false, relative = 'win', bufpos = { 1, 0 }, width = 1, height = 1 } + local win = api.nvim_open_win(buf, false, cfg) + api.nvim_buf_set_lines(buf, 0, -1, false, { 'foo' }) + feed('i<C-N>') + screen:expect([[ + ^ | + {4:f}{1: }| + {1:~ }|*5 + {5:-- Keyword completion (^N^P) }{9:Pattern not found} | + ]]) + api.nvim_win_set_config(win, { focusable = true }) + feed('<Esc>i<C-N>') + screen:expect([[ + foo^ | + {4:f}{1: }| + {1:~ }|*5 + {5:-- Keyword completion (^N^P) The only match} | + ]]) + end) end)
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 89a9c7dda34454..7451611ff3270d 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -69,8 +69,9 @@ If a window is focusable, it is part of the "navigation stack", that is, editor commands such as :windo, |CTRL-W|, etc., will consider the window as one that can be made the "current window". A non-focusable window will be skipped by such commands (though it can be explicitly focused by -|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, and -are not counted by the default 'tabline'. +|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, +or counted by the default 'tabline'. Their buffer content is not included +in 'complete' "w" completion. Windows (especially floating windows) can have many other |api-win_config| properties such as "hide" and "fixed" which also affect behavior. diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index 3e206a2cf53fe0..2582213db044d1 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2460,8 +2460,8 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) while (true) { // Move to next window (wrap to first window if at the end) wp = (wp->w_next != NULL) ? wp->w_next : firstwin; - // Break if we're back at start or found an unscanned buffer - if (wp == curwin || !wp->w_buffer->b_scanned) { + // Break if we're back at start or found an unscanned buffer (in a focusable window) + if (wp == curwin || (!wp->w_buffer->b_scanned && wp->w_config.focusable)) { break; } } diff --git a/test/functional/editor/completion_spec.lua b/test/functional/editor/completion_spec.lua index 3e5d0e48e8afdb..8b22295b09996e 100644 --- a/test/functional/editor/completion_spec.lua +++ b/test/functional/editor/completion_spec.lua @@ -1351,4 +1351,26 @@ describe('completion', function() eq('completeopt option does not include popup', api.nvim_get_var('err_msg')) end) end) + + it([[does not include buffer from non-focusable window for 'complete' "w"]], function() + local buf = api.nvim_create_buf(false, true) + local cfg = { focusable = false, relative = 'win', bufpos = { 1, 0 }, width = 1, height = 1 } + local win = api.nvim_open_win(buf, false, cfg) + api.nvim_buf_set_lines(buf, 0, -1, false, { 'foo' }) + feed('i<C-N>') + ^ | + {5:-- Keyword completion (^N^P) }{9:Pattern not found} | + api.nvim_win_set_config(win, { focusable = true }) + feed('<Esc>i<C-N>') + foo^ | + {5:-- Keyword completion (^N^P) The only match} | + end) end)
[]
[]
{ "additions": 27, "author": "neovim-backports[bot]", "deletions": 4, "html_url": "https://github.com/neovim/neovim/pull/33636", "issue_id": 33636, "merged_at": "2025-04-25T23:19:28Z", "omission_probability": 0.1, "pr_number": 33636, "repo": "neovim/neovim", "title": "fix(ui): exclude unfocusable windows from 'complete' \"w\" completion", "total_changes": 31 }
348
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 89a9c7dda34454..7451611ff3270d 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -69,8 +69,9 @@ If a window is focusable, it is part of the "navigation stack", that is, editor commands such as :windo, |CTRL-W|, etc., will consider the window as one that can be made the "current window". A non-focusable window will be skipped by such commands (though it can be explicitly focused by -|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, and -are not counted by the default 'tabline'. +|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, +or counted by the default 'tabline'. Their buffer content is not included +in 'complete' "w" completion. Windows (especially floating windows) can have many other |api-win_config| properties such as "hide" and "fixed" which also affect behavior. diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index cd536144a0f0b2..453d9535c56cb6 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2613,8 +2613,8 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) while (true) { // Move to next window (wrap to first window if at the end) wp = (wp->w_next != NULL) ? wp->w_next : firstwin; - // Break if we're back at start or found an unscanned buffer - if (wp == curwin || !wp->w_buffer->b_scanned) { + // Break if we're back at start or found an unscanned buffer (in a focusable window) + if (wp == curwin || (!wp->w_buffer->b_scanned && wp->w_config.focusable)) { break; } } diff --git a/test/functional/editor/completion_spec.lua b/test/functional/editor/completion_spec.lua index 3e5d0e48e8afdb..8b22295b09996e 100644 --- a/test/functional/editor/completion_spec.lua +++ b/test/functional/editor/completion_spec.lua @@ -1351,4 +1351,26 @@ describe('completion', function() eq('completeopt option does not include popup', api.nvim_get_var('err_msg')) end) end) + + it([[does not include buffer from non-focusable window for 'complete' "w"]], function() + local buf = api.nvim_create_buf(false, true) + local cfg = { focusable = false, relative = 'win', bufpos = { 1, 0 }, width = 1, height = 1 } + local win = api.nvim_open_win(buf, false, cfg) + api.nvim_buf_set_lines(buf, 0, -1, false, { 'foo' }) + feed('i<C-N>') + screen:expect([[ + ^ | + {4:f}{1: }| + {1:~ }|*5 + {5:-- Keyword completion (^N^P) }{9:Pattern not found} | + ]]) + api.nvim_win_set_config(win, { focusable = true }) + feed('<Esc>i<C-N>') + screen:expect([[ + foo^ | + {4:f}{1: }| + {1:~ }|*5 + {5:-- Keyword completion (^N^P) The only match} | + ]]) + end) end)
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt index 89a9c7dda34454..7451611ff3270d 100644 --- a/runtime/doc/windows.txt +++ b/runtime/doc/windows.txt @@ -69,8 +69,9 @@ If a window is focusable, it is part of the "navigation stack", that is, editor commands such as :windo, |CTRL-W|, etc., will consider the window as one that can be made the "current window". A non-focusable window will be skipped by such commands (though it can be explicitly focused by -|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, and -are not counted by the default 'tabline'. +|nvim_set_current_win()|). Non-focusable windows are not listed by |:tabs|, +or counted by the default 'tabline'. Their buffer content is not included +in 'complete' "w" completion. Windows (especially floating windows) can have many other |api-win_config| properties such as "hide" and "fixed" which also affect behavior. diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index cd536144a0f0b2..453d9535c56cb6 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2613,8 +2613,8 @@ static buf_T *ins_compl_next_buf(buf_T *buf, int flag) while (true) { // Move to next window (wrap to first window if at the end) wp = (wp->w_next != NULL) ? wp->w_next : firstwin; - // Break if we're back at start or found an unscanned buffer - if (wp == curwin || !wp->w_buffer->b_scanned) { + // Break if we're back at start or found an unscanned buffer (in a focusable window) + if (wp == curwin || (!wp->w_buffer->b_scanned && wp->w_config.focusable)) { break; } } diff --git a/test/functional/editor/completion_spec.lua b/test/functional/editor/completion_spec.lua index 3e5d0e48e8afdb..8b22295b09996e 100644 --- a/test/functional/editor/completion_spec.lua +++ b/test/functional/editor/completion_spec.lua @@ -1351,4 +1351,26 @@ describe('completion', function() eq('completeopt option does not include popup', api.nvim_get_var('err_msg')) end) end) + + it([[does not include buffer from non-focusable window for 'complete' "w"]], function() + local buf = api.nvim_create_buf(false, true) + local cfg = { focusable = false, relative = 'win', bufpos = { 1, 0 }, width = 1, height = 1 } + local win = api.nvim_open_win(buf, false, cfg) + api.nvim_buf_set_lines(buf, 0, -1, false, { 'foo' }) + feed('i<C-N>') + ^ | + {5:-- Keyword completion (^N^P) }{9:Pattern not found} | + feed('<Esc>i<C-N>') + foo^ | + {5:-- Keyword completion (^N^P) The only match} | + end) end)
[ "+ api.nvim_win_set_config(win, { focusable = true })" ]
[ 52 ]
{ "additions": 27, "author": "luukvbaal", "deletions": 4, "html_url": "https://github.com/neovim/neovim/pull/33609", "issue_id": 33609, "merged_at": "2025-04-25T15:45:57Z", "omission_probability": 0.1, "pr_number": 33609, "repo": "neovim/neovim", "title": "fix(ui): exclude unfocusable windows from 'complete' \"w\" completion", "total_changes": 31 }
349
diff --git a/runtime/compiler/gleam_build.vim b/runtime/compiler/gleam_build.vim new file mode 100644 index 00000000000000..c2b1679b3c2eb1 --- /dev/null +++ b/runtime/compiler/gleam_build.vim @@ -0,0 +1,25 @@ +" Vim compiler file +" Language: Gleam +" Maintainer: Kirill Morozov <[email protected]> +" Based On: https://github.com/gleam-lang/gleam.vim +" Last Change: 2025 Apr 21 + +if exists('current_compiler') + finish +endif +let current_compiler = "gleam_build" + +CompilerSet makeprg=gleam\ build + +" Example error message: +" +" error: Unknown variable +" ┌─ /home/michael/root/projects/tutorials/gleam/try/code/src/main.gleam:19:18 +" │ +" 19 │ Ok(tuple(name, spot)) +" │ ^^^^ did you mean `sport`? +" +" The name `spot` is not in scope here. +CompilerSet errorformat=%Eerror:\ %m,%Wwarning:\ %m,%C\ %#┌─%#\ %f:%l:%c\ %#-%# + +" vim: sw=2 sts=2 et diff --git a/runtime/ftplugin/gleam.vim b/runtime/ftplugin/gleam.vim index 70958c70fc8209..3ea68fa0a7c1ca 100644 --- a/runtime/ftplugin/gleam.vim +++ b/runtime/ftplugin/gleam.vim @@ -2,24 +2,32 @@ " Language: Gleam " Maintainer: Kirill Morozov <[email protected]> " Previous Maintainer: Trilowy (https://github.com/trilowy) -" Last Change: 2025 Apr 16 +" Based On: https://github.com/gleam-lang/gleam.vim +" Last Change: 2025 Apr 21 if exists('b:did_ftplugin') finish endif let b:did_ftplugin = 1 -setlocal comments=://,:///,://// +setlocal comments=:////,:///,:// setlocal commentstring=//\ %s setlocal formatprg=gleam\ format\ --stdin - -let b:undo_ftplugin = "setlocal com< cms< fp<" +setlocal suffixesadd=.gleam +let b:undo_ftplugin = "setlocal com< cms< fp< sua<" if get(g:, "gleam_recommended_style", 1) setlocal expandtab setlocal shiftwidth=2 + setlocal smartindent setlocal softtabstop=2 - let b:undo_ftplugin ..= " | setlocal et< sw< sts<" + setlocal tabstop=2 + let b:undo_ftplugin ..= " | setlocal et< sw< si< sts< ts<" +endif + +if !exists('current_compiler') + compiler gleam_build + let b:undo_ftplugin ..= "| compiler make" endif " vim: sw=2 sts=2 et diff --git a/runtime/ftplugin/groff.vim b/runtime/ftplugin/groff.vim new file mode 100644 index 00000000000000..3ebfa03c6e85ea --- /dev/null +++ b/runtime/ftplugin/groff.vim @@ -0,0 +1,15 @@ +" Vim syntax file +" Language: groff(7) +" Maintainer: Eisuke Kawashima ( e.kawaschima+vim AT gmail.com ) +" Last Change: 2025 Apr 24 + +if exists('b:did_ftplugin') + finish +endif + +let b:nroff_is_groff = 1 + +runtime! ftplugin/nroff.vim + +let b:undo_ftplugin .= '| unlet! b:nroff_is_groff' +let b:did_ftplugin = 1 diff --git a/runtime/ftplugin/nroff.vim b/runtime/ftplugin/nroff.vim index 1c6d4ebc799aa6..cd2680ef584a58 100644 --- a/runtime/ftplugin/nroff.vim +++ b/runtime/ftplugin/nroff.vim @@ -8,6 +8,7 @@ " 2024 May 24 by Riley Bruins <[email protected]> ('commentstring' #14843) " 2025 Feb 12 by Wu, Zhenyu <[email protected]> (matchit configuration #16619) " 2025 Apr 16 by Eisuke Kawashima (cpoptions #17121) +" 2025 Apr 24 by Eisuke Kawashima (move options from syntax to ftplugin #17174) if exists("b:did_ftplugin") finish @@ -22,7 +23,17 @@ setlocal comments=:.\\\" setlocal sections+=Sh setlocal define=.\s*de -let b:undo_ftplugin = 'setlocal commentstring< comments< sections< define<' +if get(b:, 'preprocs_as_sections') + setlocal sections=EQTSPS[\ G1GS +endif + +let b:undo_ftplugin = 'setlocal commentstring< comments< sections& define<' + +if get(b:, 'nroff_is_groff') + " groff_ms exdented paragraphs are not in the default paragraphs list. + setlocal paragraphs+=XP + let b:undo_ftplugin .= ' paragraphs&' +endif if exists('loaded_matchit') let b:match_words = '^\.\s*ie\>:^\.\s*el\>' diff --git a/runtime/syntax/gleam.vim b/runtime/syntax/gleam.vim new file mode 100644 index 00000000000000..6c2bab7badb60e --- /dev/null +++ b/runtime/syntax/gleam.vim @@ -0,0 +1,97 @@ +" Vim syntax file +" Language: Gleam +" Maintainer: Kirill Morozov <[email protected]> +" Based On: https://github.com/gleam-lang/gleam.vim +" Last Change: 2025 Apr 20 + +if exists("b:current_syntax") + finish +endif +let b:current_syntax = "gleam" + +syntax case match + +" Keywords +syntax keyword gleamConditional case if +syntax keyword gleamConstant const +syntax keyword gleamDebug echo +syntax keyword gleamException panic assert todo +syntax keyword gleamInclude import +syntax keyword gleamKeyword as let use +syntax keyword gleamStorageClass pub opaque +syntax keyword gleamType type + +" Number +"" Int +syntax match gleamNumber "\<-\=\%(0\|\%(\d\|\d_\d\)\+\)\>" + +"" Binary +syntax match gleamNumber "\<-\=0[bB]_\?\%([01]\|[01]_[01]\)\+\>" + +"" Octet +syntax match gleamNumber "\<-\=0[oO]\?_\?\%(\o\|\o_\o\)\+\>" + +"" Hexadecimal +syntax match gleamNumber "\<-\=0[xX]_\?\%(\x\|\x_\x\)\+\>" + +"" Float +syntax match gleamFloat "\(0*[1-9][0-9_]*\|0\)\.\(0*[1-9][0-9_]*\|0\)\(e-\=0*[1-9][0-9_]*\)\=" + +" String +syntax region gleamString start=/"/ end=/"/ contains=gleamSpecial +syntax match gleamSpecial '\\.' contained + +" Operators +"" Basic +syntax match gleamOperator "[-+/*]\.\=\|[%=]" + +"" Arrows + Pipeline +syntax match gleamOperator "<-\|[-|]>" + +"" Bool +syntax match gleamOperator "&&\|||" + +"" Comparison +syntax match gleamOperator "[<>]=\=\.\=\|[=!]=" + +"" Misc +syntax match gleamOperator "\.\.\|<>\||" + +" Type +syntax match gleamIdentifier "\<[A-Z][a-zA-Z0-9]*\>" + +" Attribute +syntax match gleamPreProc "@[a-z][a-z_]*" + +" Function definition +syntax keyword gleamKeyword fn nextgroup=gleamFunction skipwhite skipempty +syntax match gleamFunction "[a-z][a-z0-9_]*\ze\s*(" skipwhite skipnl + +" Comments +syntax region gleamComment start="//" end="$" contains=gleamTodo +syntax region gleamSpecialComment start="///" end="$" +syntax region gleamSpecialComment start="////" end="$" +syntax keyword gleamTodo contained TODO FIXME XXX NB NOTE + +" Highlight groups +highlight link gleamComment Comment +highlight link gleamConditional Conditional +highlight link gleamConstant Constant +highlight link gleamDebug Debug +highlight link gleamException Exception +highlight link gleamFloat Float +highlight link gleamFunction Function +highlight link gleamIdentifier Identifier +highlight link gleamInclude Include +highlight link gleamKeyword Keyword +highlight link gleamNumber Number +highlight link gleamOperator Operator +highlight link gleamPreProc PreProc +highlight link gleamSpecial Special +highlight link gleamSpecialComment SpecialComment +highlight link gleamStorageClass StorageClass +highlight link gleamString String +highlight link gleamTodo Todo +highlight link gleamType Type + +" vim: sw=2 sts=2 et diff --git a/runtime/syntax/nroff.vim b/runtime/syntax/nroff.vim index 5667042515586b..fec966f3345d39 100644 --- a/runtime/syntax/nroff.vim +++ b/runtime/syntax/nroff.vim @@ -4,6 +4,7 @@ " Previous Maintainer: Pedro Alejandro López-Valencia <[email protected]> " Previous Maintainer: Jérôme Plût <[email protected]> " Last Change: 2021 Mar 28 +" 2025 Apr 24 by Eisuke Kawashima (move options from syntax to ftplugin #17174) " " {{{1 Todo " @@ -40,19 +41,6 @@ if exists("nroff_space_errors") syn match nroffError /\s\+$/ syn match nroffSpaceError /[.,:;!?]\s\{2,}/ endif -" -" -" {{{1 Special file settings -" -" {{{2 ms exdented paragraphs are not in the default paragraphs list. -" -setlocal paragraphs+=XP -" -" {{{2 Activate navigation to preprocessor sections. -" -if exists("b:preprocs_as_sections") - setlocal sections=EQTSPS[\ G1GS -endif " {{{1 Escape sequences " ------------------------------------------------------------
diff --git a/runtime/compiler/gleam_build.vim b/runtime/compiler/gleam_build.vim index 00000000000000..c2b1679b3c2eb1 +++ b/runtime/compiler/gleam_build.vim @@ -0,0 +1,25 @@ +" Vim compiler file +" Last Change: 2025 Apr 21 +if exists('current_compiler') +let current_compiler = "gleam_build" +CompilerSet makeprg=gleam\ build +" Example error message: +" error: Unknown variable +" │ +" │ ^^^^ did you mean `sport`? +" The name `spot` is not in scope here. +CompilerSet errorformat=%Eerror:\ %m,%Wwarning:\ %m,%C\ %#┌─%#\ %f:%l:%c\ %#-%# diff --git a/runtime/ftplugin/gleam.vim b/runtime/ftplugin/gleam.vim index 70958c70fc8209..3ea68fa0a7c1ca 100644 --- a/runtime/ftplugin/gleam.vim +++ b/runtime/ftplugin/gleam.vim @@ -2,24 +2,32 @@ " Language: Gleam " Maintainer: Kirill Morozov <[email protected]> " Previous Maintainer: Trilowy (https://github.com/trilowy) -" Last Change: 2025 Apr 16 +" Based On: https://github.com/gleam-lang/gleam.vim +" Last Change: 2025 Apr 21 if exists('b:did_ftplugin') let b:did_ftplugin = 1 -setlocal comments=://,:///,://// +setlocal comments=:////,:///,:// setlocal commentstring=//\ %s setlocal formatprg=gleam\ format\ --stdin - -let b:undo_ftplugin = "setlocal com< cms< fp<" +setlocal suffixesadd=.gleam +let b:undo_ftplugin = "setlocal com< cms< fp< sua<" if get(g:, "gleam_recommended_style", 1) setlocal expandtab setlocal shiftwidth=2 setlocal softtabstop=2 - let b:undo_ftplugin ..= " | setlocal et< sw< sts<" + setlocal tabstop=2 + let b:undo_ftplugin ..= " | setlocal et< sw< si< sts< ts<" +if !exists('current_compiler') + compiler gleam_build + let b:undo_ftplugin ..= "| compiler make" " vim: sw=2 sts=2 et diff --git a/runtime/ftplugin/groff.vim b/runtime/ftplugin/groff.vim index 00000000000000..3ebfa03c6e85ea +++ b/runtime/ftplugin/groff.vim @@ -0,0 +1,15 @@ +" Language: groff(7) +" Maintainer: Eisuke Kawashima ( e.kawaschima+vim AT gmail.com ) +" Last Change: 2025 Apr 24 +if exists('b:did_ftplugin') +runtime! ftplugin/nroff.vim +let b:undo_ftplugin .= '| unlet! b:nroff_is_groff' diff --git a/runtime/ftplugin/nroff.vim b/runtime/ftplugin/nroff.vim index 1c6d4ebc799aa6..cd2680ef584a58 100644 --- a/runtime/ftplugin/nroff.vim +++ b/runtime/ftplugin/nroff.vim @@ -8,6 +8,7 @@ " 2024 May 24 by Riley Bruins <[email protected]> ('commentstring' #14843) " 2025 Feb 12 by Wu, Zhenyu <[email protected]> (matchit configuration #16619) " 2025 Apr 16 by Eisuke Kawashima (cpoptions #17121) if exists("b:did_ftplugin") @@ -22,7 +23,17 @@ setlocal comments=:.\\\" setlocal sections+=Sh setlocal define=.\s*de -let b:undo_ftplugin = 'setlocal commentstring< comments< sections< define<' +if get(b:, 'preprocs_as_sections') + setlocal sections=EQTSPS[\ G1GS +let b:undo_ftplugin = 'setlocal commentstring< comments< sections& define<' +if get(b:, 'nroff_is_groff') + " groff_ms exdented paragraphs are not in the default paragraphs list. + setlocal paragraphs+=XP + let b:undo_ftplugin .= ' paragraphs&' if exists('loaded_matchit') let b:match_words = '^\.\s*ie\>:^\.\s*el\>' diff --git a/runtime/syntax/gleam.vim b/runtime/syntax/gleam.vim index 00000000000000..6c2bab7badb60e +++ b/runtime/syntax/gleam.vim @@ -0,0 +1,97 @@ +" Last Change: 2025 Apr 20 +let b:current_syntax = "gleam" +syntax case match +" Keywords +syntax keyword gleamConditional case if +syntax keyword gleamConstant const +syntax keyword gleamDebug echo +syntax keyword gleamException panic assert todo +syntax keyword gleamInclude import +syntax keyword gleamKeyword as let use +syntax keyword gleamStorageClass pub opaque +syntax keyword gleamType type +" Number +"" Int +"" Binary +"" Octet +syntax match gleamNumber "\<-\=0[oO]\?_\?\%(\o\|\o_\o\)\+\>" +"" Hexadecimal +syntax match gleamFloat "\(0*[1-9][0-9_]*\|0\)\.\(0*[1-9][0-9_]*\|0\)\(e-\=0*[1-9][0-9_]*\)\=" +" String +syntax region gleamString start=/"/ end=/"/ contains=gleamSpecial +syntax match gleamSpecial '\\.' contained +" Operators +"" Basic +syntax match gleamOperator "[-+/*]\.\=\|[%=]" +"" Arrows + Pipeline +syntax match gleamOperator "<-\|[-|]>" +"" Bool +syntax match gleamOperator "&&\|||" +"" Comparison +syntax match gleamOperator "[<>]=\=\.\=\|[=!]=" +"" Misc +syntax match gleamOperator "\.\.\|<>\||" +" Type +syntax match gleamIdentifier "\<[A-Z][a-zA-Z0-9]*\>" +" Attribute +syntax match gleamPreProc "@[a-z][a-z_]*" +" Function definition +syntax keyword gleamKeyword fn nextgroup=gleamFunction skipwhite skipempty +syntax match gleamFunction "[a-z][a-z0-9_]*\ze\s*(" skipwhite skipnl +" Comments +syntax region gleamComment start="//" end="$" contains=gleamTodo +syntax region gleamSpecialComment start="///" end="$" +syntax region gleamSpecialComment start="////" end="$" +syntax keyword gleamTodo contained TODO FIXME XXX NB NOTE +highlight link gleamComment Comment +highlight link gleamConditional Conditional +highlight link gleamConstant Constant +highlight link gleamDebug Debug +highlight link gleamException Exception +highlight link gleamFloat Float +highlight link gleamFunction Function +highlight link gleamIdentifier Identifier +highlight link gleamInclude Include +highlight link gleamKeyword Keyword +highlight link gleamNumber Number +highlight link gleamOperator Operator +highlight link gleamPreProc PreProc +highlight link gleamSpecial Special +highlight link gleamSpecialComment SpecialComment +highlight link gleamStorageClass StorageClass +highlight link gleamString String +highlight link gleamTodo Todo +highlight link gleamType Type diff --git a/runtime/syntax/nroff.vim b/runtime/syntax/nroff.vim index 5667042515586b..fec966f3345d39 100644 --- a/runtime/syntax/nroff.vim +++ b/runtime/syntax/nroff.vim @@ -4,6 +4,7 @@ " Previous Maintainer: Pedro Alejandro López-Valencia <[email protected]> " Previous Maintainer: Jérôme Plût <[email protected]> " Last Change: 2021 Mar 28 " {{{1 Todo @@ -40,19 +41,6 @@ if exists("nroff_space_errors") syn match nroffError /\s\+$/ syn match nroffSpaceError /[.,:;!?]\s\{2,}/ -" {{{1 Special file settings -" {{{2 ms exdented paragraphs are not in the default paragraphs list. -setlocal paragraphs+=XP -" {{{2 Activate navigation to preprocessor sections. -if exists("b:preprocs_as_sections") - setlocal sections=EQTSPS[\ G1GS -endif " {{{1 Escape sequences " ------------------------------------------------------------
[ "+\" ┌─ /home/michael/root/projects/tutorials/gleam/try/code/src/main.gleam:19:18", "+\" 19 │ Ok(tuple(name, spot))", "+ setlocal smartindent", "+let b:nroff_is_groff = 1", "+let b:did_ftplugin = 1", "+if exists(\"b:current_syntax\")", "+syntax match gleamNumber \"\\<-\\=\\%(0\\|\\%(\\d\\|\\d_\\d\\)\\+\\)\\>\"", "+syntax match gleamNumber \"\\<-\\=0[bB]_\\?\\%([01]\\|[01]_[01]\\)\\+\\>\"", "+syntax match gleamNumber \"\\<-\\=0[xX]_\\?\\%(\\x\\|\\x_\\x\\)\\+\\>\"", "+\"\" Float", "+\" Highlight groups" ]
[ 22, 24, 60, 88, 93, 137, 156, 159, 165, 167, 206 ]
{ "additions": 163, "author": "clason", "deletions": 19, "html_url": "https://github.com/neovim/neovim/pull/33632", "issue_id": 33632, "merged_at": "2025-04-25T08:58:49Z", "omission_probability": 0.1, "pr_number": 33632, "repo": "neovim/neovim", "title": "vim-patch: update runtime files", "total_changes": 182 }
350
diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index a8721093e893ed..87a0d88976876d 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -6793,7 +6793,7 @@ describe('builtin popupmenu', function() end if multigrid then api.nvim_input_mouse('right', 'press', '', 2, 0, 18) - screen:expect { + screen:expect({ grid = [[ ## grid 1 [2:--------------------------------]|*5 @@ -6809,7 +6809,7 @@ describe('builtin popupmenu', function() {n: baz }| ]], float_pos = { [4] = { -1, 'NW', 2, 1, 17, false, 250, 2, 1, 17 } }, - } + }) else feed('<RightMouse><18,0>') screen:expect([[ @@ -6904,37 +6904,13 @@ describe('builtin popupmenu', function() no_menu_screen = no_menu_screen:gsub([['baz']], [['foo']]) screen:expect(no_menu_screen) eq('foo', api.nvim_get_var('menustr')) + no_sel_screen = screen_replace(no_sel_screen, [['baz']], [['foo']]) eq(false, screen.options.mousemoveevent) if multigrid then api.nvim_input_mouse('right', 'press', '', 2, 0, 4) - no_sel_screen = { - grid = [[ - ## grid 1 - [2:--------------------------------]|*5 - [3:--------------------------------]| - ## grid 2 - ^popup menu test | - {1:~ }|*4 - ## grid 3 - :let g:menustr = 'foo' | - ## grid 4 - {n: foo }| - {n: bar }| - {n: baz }| - ]], - float_pos = { [4] = { -1, 'NW', 2, 1, 3, false, 250, 2, 1, 3 } }, - } else feed('<RightMouse><4,0>') - no_sel_screen = [[ - ^popup menu test | - {1:~ }{n: foo }{1: }| - {1:~ }{n: bar }{1: }| - {1:~ }{n: baz }{1: }| - {1:~ }| - :let g:menustr = 'foo' | - ]] end screen:expect(no_sel_screen) eq(true, screen.options.mousemoveevent)
diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index a8721093e893ed..87a0d88976876d 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -6793,7 +6793,7 @@ describe('builtin popupmenu', function() api.nvim_input_mouse('right', 'press', '', 2, 0, 18) - screen:expect { + screen:expect({ grid = [[ ## grid 1 [2:--------------------------------]|*5 @@ -6809,7 +6809,7 @@ describe('builtin popupmenu', function() {n: baz }| ]], float_pos = { [4] = { -1, 'NW', 2, 1, 17, false, 250, 2, 1, 17 } }, + }) feed('<RightMouse><18,0>') screen:expect([[ @@ -6904,37 +6904,13 @@ describe('builtin popupmenu', function() no_menu_screen = no_menu_screen:gsub([['baz']], [['foo']]) screen:expect(no_menu_screen) eq('foo', api.nvim_get_var('menustr')) + no_sel_screen = screen_replace(no_sel_screen, [['baz']], [['foo']]) eq(false, screen.options.mousemoveevent) api.nvim_input_mouse('right', 'press', '', 2, 0, 4) - no_sel_screen = { - grid = [[ - ## grid 1 - [2:--------------------------------]|*5 - [3:--------------------------------]| - ## grid 2 - {1:~ }|*4 - ## grid 3 - ## grid 4 - {n: foo }| - {n: bar }| - {n: baz }| - ]], - float_pos = { [4] = { -1, 'NW', 2, 1, 3, false, 250, 2, 1, 3 } }, feed('<RightMouse><4,0>') - no_sel_screen = [[ - {1:~ }{n: foo }{1: }| - {1:~ }{n: bar }{1: }| - {1:~ }{n: baz }{1: }| - ]] screen:expect(no_sel_screen) eq(true, screen.options.mousemoveevent)
[ "- {1:~ }|" ]
[ 55 ]
{ "additions": 3, "author": "zeertzjq", "deletions": 27, "html_url": "https://github.com/neovim/neovim/pull/33628", "issue_id": 33628, "merged_at": "2025-04-25T07:19:09Z", "omission_probability": 0.1, "pr_number": 33628, "repo": "neovim/neovim", "title": "test(pum): remove two more duplicate screen states", "total_changes": 30 }
351
diff --git a/runtime/lua/vim/lsp/document_color.lua b/runtime/lua/vim/lsp/document_color.lua index b03055c2337a05..1c2d9ecb67c06b 100644 --- a/runtime/lua/vim/lsp/document_color.lua +++ b/runtime/lua/vim/lsp/document_color.lua @@ -175,6 +175,18 @@ end local function buf_enable(bufnr) reset_bufstate(bufnr, true) + api.nvim_buf_attach(bufnr, false, { + on_reload = function(_, buf) + buf_clear(buf) + if bufstates[buf].enabled then + buf_refresh(buf) + end + end, + on_detach = function(_, buf) + buf_disable(buf) + end, + }) + api.nvim_create_autocmd('LspNotify', { buffer = bufnr, group = document_color_augroup, @@ -191,25 +203,6 @@ local function buf_enable(bufnr) end, }) - api.nvim_create_autocmd('LspAttach', { - buffer = bufnr, - group = document_color_augroup, - desc = 'Enable document_color when LSP client attaches', - callback = function(args) - api.nvim_buf_attach(args.buf, false, { - on_reload = function(_, buf) - buf_clear(buf) - if bufstates[buf].enabled then - buf_refresh(buf) - end - end, - on_detach = function(_, buf) - buf_disable(buf) - end, - }) - end, - }) - api.nvim_create_autocmd('LspDetach', { buffer = bufnr, group = document_color_augroup, @@ -238,7 +231,13 @@ end function M.is_enabled(bufnr) vim.validate('bufnr', bufnr, 'number', true) - return bufstates[vim._resolve_bufnr(bufnr)].enabled + bufnr = vim._resolve_bufnr(bufnr) + + if not bufstates[bufnr] then + reset_bufstate(bufnr, false) + end + + return bufstates[bufnr].enabled end --- Enables document highlighting from the given language client in the given buffer. diff --git a/test/functional/plugin/lsp/document_color_spec.lua b/test/functional/plugin/lsp/document_color_spec.lua index b08757de9adada..a938d367d497f3 100644 --- a/test/functional/plugin/lsp/document_color_spec.lua +++ b/test/functional/plugin/lsp/document_color_spec.lua @@ -159,6 +159,15 @@ body { end) ) end) + + it('does not error when called on a new unattached buffer', function() + eq( + false, + exec_lua(function() + return vim.lsp.document_color.is_enabled(vim.api.nvim_create_buf(false, true)) + end) + ) + end) end) describe('enable()', function()
diff --git a/runtime/lua/vim/lsp/document_color.lua b/runtime/lua/vim/lsp/document_color.lua index b03055c2337a05..1c2d9ecb67c06b 100644 --- a/runtime/lua/vim/lsp/document_color.lua +++ b/runtime/lua/vim/lsp/document_color.lua @@ -175,6 +175,18 @@ end local function buf_enable(bufnr) reset_bufstate(bufnr, true) + api.nvim_buf_attach(bufnr, false, { + on_reload = function(_, buf) + buf_clear(buf) + if bufstates[buf].enabled then + buf_refresh(buf) + end + on_detach = function(_, buf) + buf_disable(buf) + }) api.nvim_create_autocmd('LspNotify', { @@ -191,25 +203,6 @@ local function buf_enable(bufnr) end, }) - api.nvim_create_autocmd('LspAttach', { - buffer = bufnr, - group = document_color_augroup, - desc = 'Enable document_color when LSP client attaches', - callback = function(args) - api.nvim_buf_attach(args.buf, false, { - buf_clear(buf) - if bufstates[buf].enabled then - buf_refresh(buf) - end - buf_disable(buf) - }) - }) api.nvim_create_autocmd('LspDetach', { @@ -238,7 +231,13 @@ end function M.is_enabled(bufnr) vim.validate('bufnr', bufnr, 'number', true) + bufnr = vim._resolve_bufnr(bufnr) + if not bufstates[bufnr] then + reset_bufstate(bufnr, false) + end end --- Enables document highlighting from the given language client in the given buffer. diff --git a/test/functional/plugin/lsp/document_color_spec.lua b/test/functional/plugin/lsp/document_color_spec.lua index b08757de9adada..a938d367d497f3 100644 --- a/test/functional/plugin/lsp/document_color_spec.lua +++ b/test/functional/plugin/lsp/document_color_spec.lua @@ -159,6 +159,15 @@ body { end) ) end) + it('does not error when called on a new unattached buffer', function() + eq( + false, + exec_lua(function() + end) + ) + end) end) describe('enable()', function()
[ "- on_reload = function(_, buf)", "- on_detach = function(_, buf)", "- end,", "-", "- return bufstates[vim._resolve_bufnr(bufnr)].enabled", "+ return bufstates[bufnr].enabled", "+ return vim.lsp.document_color.is_enabled(vim.api.nvim_create_buf(false, true))" ]
[ 33, 39, 43, 45, 53, 60, 77 ]
{ "additions": 28, "author": "MariaSolOs", "deletions": 20, "html_url": "https://github.com/neovim/neovim/pull/33611", "issue_id": 33611, "merged_at": "2025-04-24T19:03:44Z", "omission_probability": 0.1, "pr_number": 33611, "repo": "neovim/neovim", "title": "fix(lsp): ensure `bufstate` exists when invoking `vim.lsp.document_color.is_enabled`", "total_changes": 48 }
352
diff --git a/src/nvim/edit.c b/src/nvim/edit.c index e6ed80bba81cb2..a6191be21db457 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -3458,7 +3458,7 @@ static bool ins_esc(int *count, int cmdchar, bool nomove) showmode(); } else if (p_smd && (got_int || !skip_showmode()) && !(p_ch == 0 && !ui_has(kUIMessages))) { - msg("", 0); + unshowmode(false); } // Exit Insert mode return true; diff --git a/test/functional/treesitter/highlight_spec.lua b/test/functional/treesitter/highlight_spec.lua index 9bf32bf8a7a583..f661fde5030826 100644 --- a/test/functional/treesitter/highlight_spec.lua +++ b/test/functional/treesitter/highlight_spec.lua @@ -82,7 +82,7 @@ local hl_grid_legacy_c = [[ {15:return} {26:0}; | } | {1:~ }|*2 - | + 14 more lines | ]] local hl_grid_ts_c = [[ @@ -102,7 +102,7 @@ local hl_grid_ts_c = [[ {15:return} {26:0}; | } | {1:~ }|*2 - | + {MATCH:1?4? m?o?r?e? l?i?n?e?s?.*}| ]] local test_text_c = [[ diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index 469b0ed2029af8..65cf6efbfaaeec 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -1663,6 +1663,22 @@ stack traceback: }, }) end) + + it('clears showmode after insert_expand mode', function() + feed('i<C-N>') + screen:expect({ + grid = [[ + ^ | + {1:~ }|*4 + ]], + showmode = { { '-- Keyword completion (^N^P) ', 5, 11 }, { 'Pattern not found', 9, 6 } }, + }) + feed('<Esc>') + screen:expect([[ + ^ | + {1:~ }|*4 + ]]) + end) end) describe('ui/builtin messages', function()
diff --git a/src/nvim/edit.c b/src/nvim/edit.c index e6ed80bba81cb2..a6191be21db457 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -3458,7 +3458,7 @@ static bool ins_esc(int *count, int cmdchar, bool nomove) showmode(); } else if (p_smd && (got_int || !skip_showmode()) && !(p_ch == 0 && !ui_has(kUIMessages))) { - msg("", 0); + unshowmode(false); } // Exit Insert mode return true; diff --git a/test/functional/treesitter/highlight_spec.lua b/test/functional/treesitter/highlight_spec.lua index 9bf32bf8a7a583..f661fde5030826 100644 --- a/test/functional/treesitter/highlight_spec.lua +++ b/test/functional/treesitter/highlight_spec.lua @@ -82,7 +82,7 @@ local hl_grid_legacy_c = [[ + 14 more lines | local hl_grid_ts_c = [[ @@ -102,7 +102,7 @@ local hl_grid_ts_c = [[ + {MATCH:1?4? m?o?r?e? l?i?n?e?s?.*}| local test_text_c = [[ diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index 469b0ed2029af8..65cf6efbfaaeec 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -1663,6 +1663,22 @@ stack traceback: }, }) end) + + it('clears showmode after insert_expand mode', function() + feed('i<C-N>') + screen:expect({ + grid = [[ + ^ | + {1:~ }|*4 + ]], + showmode = { { '-- Keyword completion (^N^P) ', 5, 11 }, { 'Pattern not found', 9, 6 } }, + }) + feed('<Esc>') + screen:expect([[ + ^ | + {1:~ }|*4 + ]]) + end) end) describe('ui/builtin messages', function()
[]
[]
{ "additions": 19, "author": "luukvbaal", "deletions": 3, "html_url": "https://github.com/neovim/neovim/pull/33607", "issue_id": 33607, "merged_at": "2025-04-24T19:11:49Z", "omission_probability": 0.1, "pr_number": 33607, "repo": "neovim/neovim", "title": "fix(messages): clear 'showmode' message after insert_expand", "total_changes": 22 }
353
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 6cebc77394cdb2..c95a16cd254355 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -3401,6 +3401,7 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* file file and directory names file_in_path file and directory names in |'path'| filetype filetype names |'filetype'| + filetypecmd |:filetype| suboptions function function name help help subjects highlight highlight groups diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua index a253a87a49f8aa..5ba94663cdacc1 100644 --- a/runtime/lua/vim/_meta/vimfn.lua +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -3048,6 +3048,7 @@ function vim.fn.getcmdwintype() end --- file file and directory names --- file_in_path file and directory names in |'path'| --- filetype filetype names |'filetype'| +--- filetypecmd |:filetype| suboptions --- function function name --- help help subjects --- highlight highlight groups diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 573f56d50f5ee4..0ea6be35788275 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -110,6 +110,7 @@ static bool cmdline_fuzzy_completion_supported(const expand_T *const xp) && xp->xp_context != EXPAND_FILES && xp->xp_context != EXPAND_FILES_IN_PATH && xp->xp_context != EXPAND_FILETYPE + && xp->xp_context != EXPAND_FILETYPECMD && xp->xp_context != EXPAND_FINDFUNC && xp->xp_context != EXPAND_HELP && xp->xp_context != EXPAND_KEYMAP @@ -1764,6 +1765,19 @@ static const char *set_context_in_lang_cmd(expand_T *xp, const char *arg) return NULL; } +static enum { + EXP_FILETYPECMD_ALL, ///< expand all :filetype values + EXP_FILETYPECMD_PLUGIN, ///< expand plugin on off + EXP_FILETYPECMD_INDENT, ///< expand indent on off + EXP_FILETYPECMD_ONOFF, ///< expand on off +} filetype_expand_what; + +enum { + EXPAND_FILETYPECMD_PLUGIN = 0x01, + EXPAND_FILETYPECMD_INDENT = 0x02, + EXPAND_FILETYPECMD_ONOFF = 0x04, +}; + static enum { EXP_BREAKPT_ADD, ///< expand ":breakadd" sub-commands EXP_BREAKPT_DEL, ///< expand ":breakdel" sub-commands @@ -1836,6 +1850,47 @@ static const char *set_context_in_scriptnames_cmd(expand_T *xp, const char *arg) return NULL; } +/// Set the completion context for the :filetype command. Always returns NULL. +static const char *set_context_in_filetype_cmd(expand_T *xp, const char *arg) +{ + xp->xp_context = EXPAND_FILETYPECMD; + xp->xp_pattern = (char *)arg; + filetype_expand_what = EXP_FILETYPECMD_ALL; + + char *p = skipwhite(arg); + if (*p == NUL) { + return NULL; + } + + int val = 0; + + while (true) { + if (strncmp(p, "plugin", 6) == 0) { + val |= EXPAND_FILETYPECMD_PLUGIN; + p = skipwhite(p + 6); + continue; + } + if (strncmp(p, "indent", 6) == 0) { + val |= EXPAND_FILETYPECMD_INDENT; + p = skipwhite(p + 6); + continue; + } + break; + } + + if ((val & EXPAND_FILETYPECMD_PLUGIN) && (val & EXPAND_FILETYPECMD_INDENT)) { + filetype_expand_what = EXP_FILETYPECMD_ONOFF; + } else if ((val & EXPAND_FILETYPECMD_PLUGIN)) { + filetype_expand_what = EXP_FILETYPECMD_INDENT; + } else if ((val & EXPAND_FILETYPECMD_INDENT)) { + filetype_expand_what = EXP_FILETYPECMD_PLUGIN; + } + + xp->xp_pattern = p; + + return NULL; +} + /// Set the completion context in "xp" for command "cmd" with index "cmdidx". /// The argument to the command is "arg" and the argument flags is "argt". /// For user-defined commands and for environment variables, "context" has the @@ -2198,6 +2253,9 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, expa case CMD_scriptnames: return set_context_in_scriptnames_cmd(xp, arg); + case CMD_filetype: + return set_context_in_filetype_cmd(xp, arg); + case CMD_lua: case CMD_equal: xp->xp_context = EXPAND_LUA; @@ -2565,6 +2623,30 @@ static int expand_files_and_dirs(expand_T *xp, char *pat, char ***matches, int * return ret; } +/// Function given to ExpandGeneric() to obtain the possible arguments of the +/// ":filetype {plugin,indent}" command. +static char *get_filetypecmd_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) +{ + char *opts_all[] = { "indent", "plugin", "on", "off" }; + char *opts_plugin[] = { "plugin", "on", "off" }; + char *opts_indent[] = { "indent", "on", "off" }; + char *opts_onoff[] = { "on", "off" }; + + if (filetype_expand_what == EXP_FILETYPECMD_ALL && idx < 4) { + return opts_all[idx]; + } + if (filetype_expand_what == EXP_FILETYPECMD_PLUGIN && idx < 3) { + return opts_plugin[idx]; + } + if (filetype_expand_what == EXP_FILETYPECMD_INDENT && idx < 3) { + return opts_indent[idx]; + } + if (filetype_expand_what == EXP_FILETYPECMD_ONOFF && idx < 2) { + return opts_onoff[idx]; + } + return NULL; +} + /// Function given to ExpandGeneric() to obtain the possible arguments of the /// ":breakadd {expr, file, func, here}" command. /// ":breakdel {func, file, here}" command. @@ -2660,6 +2742,7 @@ static int ExpandOther(char *pat, expand_T *xp, regmatch_T *rmp, char ***matches int escaped; } tab[] = { { EXPAND_COMMANDS, get_command_name, false, true }, + { EXPAND_FILETYPECMD, get_filetypecmd_arg, true, true }, { EXPAND_MAPCLEAR, get_mapclear_arg, true, true }, { EXPAND_MESSAGES, get_messages_arg, true, true }, { EXPAND_HISTORY, get_history_arg, true, true }, @@ -3643,6 +3726,9 @@ void f_getcompletion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) set_context_for_wildcard_arg(NULL, xpc.xp_pattern, false, &xpc, &context); xpc.xp_pattern_len = strlen(xpc.xp_pattern); } + if (xpc.xp_context == EXPAND_FILETYPECMD) { + filetype_expand_what = EXP_FILETYPECMD_ALL; + } theend: if (xpc.xp_context == EXPAND_LUA) { diff --git a/src/nvim/cmdexpand_defs.h b/src/nvim/cmdexpand_defs.h index dfda9fdaedbb73..29ad9ff2513b6d 100644 --- a/src/nvim/cmdexpand_defs.h +++ b/src/nvim/cmdexpand_defs.h @@ -108,6 +108,7 @@ enum { EXPAND_DIRS_IN_CDPATH, EXPAND_SHELLCMDLINE, EXPAND_FINDFUNC, + EXPAND_FILETYPECMD, EXPAND_CHECKHEALTH, EXPAND_LUA, }; diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 26d0ec036079ce..0013134857458f 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -3831,6 +3831,7 @@ M.funcs = { file file and directory names file_in_path file and directory names in |'path'| filetype filetype names |'filetype'| + filetypecmd |:filetype| suboptions function function name help help subjects highlight highlight groups diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index 2aa789a2ee75e1..c1904de610d015 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -72,6 +72,7 @@ static const char *command_complete[] = { [EXPAND_FILES] = "file", [EXPAND_FILES_IN_PATH] = "file_in_path", [EXPAND_FILETYPE] = "filetype", + [EXPAND_FILETYPECMD] = "filetypecmd", [EXPAND_FUNCTIONS] = "function", [EXPAND_HELP] = "help", [EXPAND_HIGHLIGHT] = "highlight", diff --git a/test/old/testdir/test_cmdline.vim b/test/old/testdir/test_cmdline.vim index df2091bf7d8ec0..08139071deb410 100644 --- a/test/old/testdir/test_cmdline.vim +++ b/test/old/testdir/test_cmdline.vim @@ -548,6 +548,13 @@ func Test_getcompletion() let l = getcompletion('kill', 'expression') call assert_equal([], l) + let l = getcompletion('', 'filetypecmd') + call assert_equal(["indent", "off", "on", "plugin"], l) + let l = getcompletion('not', 'filetypecmd') + call assert_equal([], l) + let l = getcompletion('o', 'filetypecmd') + call assert_equal(['off', 'on'], l) + let l = getcompletion('tag', 'function') call assert_true(index(l, 'taglist(') >= 0) let l = getcompletion('paint', 'function') @@ -3240,6 +3247,26 @@ func Test_fuzzy_completion_behave() set wildoptions& endfunc +" :filetype suboptions completion +func Test_completion_filetypecmd() + set wildoptions& + call feedkeys(":filetype \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype indent off on plugin', @:) + call feedkeys(":filetype plugin \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype plugin indent off on', @:) + call feedkeys(":filetype indent \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype indent off on plugin', @:) + call feedkeys(":filetype i\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype indent', @:) + call feedkeys(":filetype p\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype plugin', @:) + call feedkeys(":filetype o\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype off on', @:) + call feedkeys(":filetype indent of\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype indent off', @:) + set wildoptions& +endfunc + " " colorscheme name fuzzy completion - NOT supported " func Test_fuzzy_completion_colorscheme() " endfunc
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 6cebc77394cdb2..c95a16cd254355 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -3401,6 +3401,7 @@ getcompletion({pat}, {type} [, {filtered}]) *getcompletion()* file file and directory names file_in_path file and directory names in |'path'| filetype filetype names |'filetype'| + filetypecmd |:filetype| suboptions function function name help help subjects highlight highlight groups diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua index a253a87a49f8aa..5ba94663cdacc1 100644 --- a/runtime/lua/vim/_meta/vimfn.lua +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -3048,6 +3048,7 @@ function vim.fn.getcmdwintype() end --- file file and directory names --- file_in_path file and directory names in |'path'| --- filetype filetype names |'filetype'| +--- filetypecmd |:filetype| suboptions --- function function name --- help help subjects --- highlight highlight groups diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c index 573f56d50f5ee4..0ea6be35788275 100644 --- a/src/nvim/cmdexpand.c +++ b/src/nvim/cmdexpand.c @@ -110,6 +110,7 @@ static bool cmdline_fuzzy_completion_supported(const expand_T *const xp) && xp->xp_context != EXPAND_FILES && xp->xp_context != EXPAND_FILES_IN_PATH && xp->xp_context != EXPAND_FILETYPE + && xp->xp_context != EXPAND_FILETYPECMD && xp->xp_context != EXPAND_FINDFUNC && xp->xp_context != EXPAND_HELP && xp->xp_context != EXPAND_KEYMAP @@ -1764,6 +1765,19 @@ static const char *set_context_in_lang_cmd(expand_T *xp, const char *arg) +static enum { + EXP_FILETYPECMD_PLUGIN, ///< expand plugin on off + EXP_FILETYPECMD_INDENT, ///< expand indent on off + EXP_FILETYPECMD_ONOFF, ///< expand on off +} filetype_expand_what; +enum { + EXPAND_FILETYPECMD_PLUGIN = 0x01, + EXPAND_FILETYPECMD_ONOFF = 0x04, +}; static enum { EXP_BREAKPT_ADD, ///< expand ":breakadd" sub-commands EXP_BREAKPT_DEL, ///< expand ":breakdel" sub-commands @@ -1836,6 +1850,47 @@ static const char *set_context_in_scriptnames_cmd(expand_T *xp, const char *arg) +/// Set the completion context for the :filetype command. Always returns NULL. +static const char *set_context_in_filetype_cmd(expand_T *xp, const char *arg) + xp->xp_context = EXPAND_FILETYPECMD; + xp->xp_pattern = (char *)arg; + filetype_expand_what = EXP_FILETYPECMD_ALL; + return NULL; + int val = 0; + while (true) { + if (strncmp(p, "plugin", 6) == 0) { + val |= EXPAND_FILETYPECMD_PLUGIN; + val |= EXPAND_FILETYPECMD_INDENT; + break; + if ((val & EXPAND_FILETYPECMD_PLUGIN) && (val & EXPAND_FILETYPECMD_INDENT)) { + filetype_expand_what = EXP_FILETYPECMD_ONOFF; + } else if ((val & EXPAND_FILETYPECMD_PLUGIN)) { + filetype_expand_what = EXP_FILETYPECMD_INDENT; + } else if ((val & EXPAND_FILETYPECMD_INDENT)) { + filetype_expand_what = EXP_FILETYPECMD_PLUGIN; + xp->xp_pattern = p; /// Set the completion context in "xp" for command "cmd" with index "cmdidx". /// The argument to the command is "arg" and the argument flags is "argt". /// For user-defined commands and for environment variables, "context" has the @@ -2198,6 +2253,9 @@ static const char *set_context_by_cmdname(const char *cmd, cmdidx_T cmdidx, expa case CMD_scriptnames: return set_context_in_scriptnames_cmd(xp, arg); + case CMD_filetype: + return set_context_in_filetype_cmd(xp, arg); case CMD_lua: case CMD_equal: xp->xp_context = EXPAND_LUA; @@ -2565,6 +2623,30 @@ static int expand_files_and_dirs(expand_T *xp, char *pat, char ***matches, int * return ret; +/// Function given to ExpandGeneric() to obtain the possible arguments of the +/// ":filetype {plugin,indent}" command. +static char *get_filetypecmd_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) + char *opts_all[] = { "indent", "plugin", "on", "off" }; + char *opts_plugin[] = { "plugin", "on", "off" }; + char *opts_indent[] = { "indent", "on", "off" }; + char *opts_onoff[] = { "on", "off" }; + if (filetype_expand_what == EXP_FILETYPECMD_ALL && idx < 4) { + return opts_all[idx]; + if (filetype_expand_what == EXP_FILETYPECMD_PLUGIN && idx < 3) { + return opts_plugin[idx]; + if (filetype_expand_what == EXP_FILETYPECMD_INDENT && idx < 3) { + return opts_indent[idx]; + if (filetype_expand_what == EXP_FILETYPECMD_ONOFF && idx < 2) { + return opts_onoff[idx]; /// Function given to ExpandGeneric() to obtain the possible arguments of the /// ":breakadd {expr, file, func, here}" command. /// ":breakdel {func, file, here}" command. @@ -2660,6 +2742,7 @@ static int ExpandOther(char *pat, expand_T *xp, regmatch_T *rmp, char ***matches int escaped; } tab[] = { { EXPAND_COMMANDS, get_command_name, false, true }, + { EXPAND_FILETYPECMD, get_filetypecmd_arg, true, true }, { EXPAND_MAPCLEAR, get_mapclear_arg, true, true }, { EXPAND_MESSAGES, get_messages_arg, true, true }, { EXPAND_HISTORY, get_history_arg, true, true }, @@ -3643,6 +3726,9 @@ void f_getcompletion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) set_context_for_wildcard_arg(NULL, xpc.xp_pattern, false, &xpc, &context); xpc.xp_pattern_len = strlen(xpc.xp_pattern); } + if (xpc.xp_context == EXPAND_FILETYPECMD) { + filetype_expand_what = EXP_FILETYPECMD_ALL; theend: if (xpc.xp_context == EXPAND_LUA) { diff --git a/src/nvim/cmdexpand_defs.h b/src/nvim/cmdexpand_defs.h index dfda9fdaedbb73..29ad9ff2513b6d 100644 --- a/src/nvim/cmdexpand_defs.h +++ b/src/nvim/cmdexpand_defs.h @@ -108,6 +108,7 @@ enum { EXPAND_DIRS_IN_CDPATH, EXPAND_SHELLCMDLINE, EXPAND_FINDFUNC, + EXPAND_FILETYPECMD, EXPAND_CHECKHEALTH, EXPAND_LUA, }; diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 26d0ec036079ce..0013134857458f 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -3831,6 +3831,7 @@ M.funcs = { file file and directory names file_in_path file and directory names in |'path'| filetype filetype names |'filetype'| + filetypecmd |:filetype| suboptions function function name help help subjects highlight highlight groups diff --git a/src/nvim/usercmd.c b/src/nvim/usercmd.c index 2aa789a2ee75e1..c1904de610d015 100644 --- a/src/nvim/usercmd.c +++ b/src/nvim/usercmd.c @@ -72,6 +72,7 @@ static const char *command_complete[] = { [EXPAND_FILES] = "file", [EXPAND_FILES_IN_PATH] = "file_in_path", [EXPAND_FILETYPE] = "filetype", + [EXPAND_FILETYPECMD] = "filetypecmd", [EXPAND_FUNCTIONS] = "function", [EXPAND_HELP] = "help", [EXPAND_HIGHLIGHT] = "highlight", diff --git a/test/old/testdir/test_cmdline.vim b/test/old/testdir/test_cmdline.vim index df2091bf7d8ec0..08139071deb410 100644 --- a/test/old/testdir/test_cmdline.vim +++ b/test/old/testdir/test_cmdline.vim @@ -548,6 +548,13 @@ func Test_getcompletion() let l = getcompletion('kill', 'expression') call assert_equal([], l) + let l = getcompletion('', 'filetypecmd') + call assert_equal(["indent", "off", "on", "plugin"], l) + let l = getcompletion('not', 'filetypecmd') + call assert_equal([], l) + let l = getcompletion('o', 'filetypecmd') + call assert_equal(['off', 'on'], l) let l = getcompletion('tag', 'function') call assert_true(index(l, 'taglist(') >= 0) let l = getcompletion('paint', 'function') @@ -3240,6 +3247,26 @@ func Test_fuzzy_completion_behave() set wildoptions& endfunc +" :filetype suboptions completion +func Test_completion_filetypecmd() + call feedkeys(":filetype \<C-A>\<C-B>\"\<CR>", 'tx') + call feedkeys(":filetype plugin \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype plugin indent off on', @:) + call feedkeys(":filetype indent \<C-A>\<C-B>\"\<CR>", 'tx') + call feedkeys(":filetype i\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype indent', @:) + call feedkeys(":filetype p\<C-A>\<C-B>\"\<CR>", 'tx') + call feedkeys(":filetype o\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype off on', @:) + call feedkeys(":filetype indent of\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"filetype indent off', @:) +endfunc " " colorscheme name fuzzy completion - NOT supported " func Test_fuzzy_completion_colorscheme() " endfunc
[ "+ EXP_FILETYPECMD_ALL, ///< expand all :filetype values", "+ EXPAND_FILETYPECMD_INDENT = 0x02,", "+ char *p = skipwhite(arg);", "+ if (*p == NUL) {", "+ if (strncmp(p, \"indent\", 6) == 0) {", "+ call assert_equal('\"filetype plugin', @:)" ]
[ 41, 49, 67, 68, 80, 233 ]
{ "additions": 118, "author": "zeertzjq", "deletions": 0, "html_url": "https://github.com/neovim/neovim/pull/33602", "issue_id": 33602, "merged_at": "2025-04-24T00:50:33Z", "omission_probability": 0.1, "pr_number": 33602, "repo": "neovim/neovim", "title": "vim-patch:9.1.1340: cannot complete :filetype arguments", "total_changes": 118 }
354
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index 0b7b5c37c24898..3e206a2cf53fe0 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2181,9 +2181,10 @@ static bool set_ctrl_x_mode(const int c) static bool ins_compl_stop(const int c, const int prev_mode, bool retval) { // Remove pre-inserted text when present. - if (ins_compl_preinsert_effect()) { + if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin)) { ins_compl_delete(false); } + // Get here when we have finished typing a sequence of ^N and // ^P or other completion characters in CTRL-X mode. Free up // memory that was used, and make sure we can redo the insert. diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index 526ac9f7f45616..90205c54504e71 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -2997,7 +2997,7 @@ func Test_complete_info_completed() set cot& endfunc -function Test_completeopt_preinsert() +func Test_completeopt_preinsert() func Omni_test(findstart, base) if a:findstart return col(".") @@ -3137,6 +3137,47 @@ function Test_completeopt_preinsert() call assert_equal(4, g:col) call assert_equal("wp.", getline('.')) + %delete _ + let &l:undolevels = &l:undolevels + normal! ifoo + let &l:undolevels = &l:undolevels + normal! obar + let &l:undolevels = &l:undolevels + normal! obaz + let &l:undolevels = &l:undolevels + + func CheckUndo() + let g:errmsg = '' + call assert_equal(['foo', 'bar', 'baz'], getline(1, '$')) + undo + call assert_equal(['foo', 'bar'], getline(1, '$')) + undo + call assert_equal(['foo'], getline(1, '$')) + undo + call assert_equal([''], getline(1, '$')) + later 3 + call assert_equal(['foo', 'bar', 'baz'], getline(1, '$')) + call assert_equal('', v:errmsg) + endfunc + + " Check that switching buffer with "preinsert" doesn't corrupt undo. + new + setlocal bufhidden=wipe + inoremap <buffer> <F2> <Cmd>enew!<CR> + call feedkeys("i\<C-X>\<C-O>\<F2>\<Esc>", 'tx') + bwipe! + call CheckUndo() + + " Check that closing window with "preinsert" doesn't corrupt undo. + new + setlocal bufhidden=wipe + inoremap <buffer> <F2> <Cmd>close!<CR> + call feedkeys("i\<C-X>\<C-O>\<F2>\<Esc>", 'tx') + call CheckUndo() + + %delete _ + delfunc CheckUndo + bw! set cot& set omnifunc&
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index 0b7b5c37c24898..3e206a2cf53fe0 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2181,9 +2181,10 @@ static bool set_ctrl_x_mode(const int c) static bool ins_compl_stop(const int c, const int prev_mode, bool retval) { // Remove pre-inserted text when present. - if (ins_compl_preinsert_effect()) { + if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin)) { ins_compl_delete(false); } // Get here when we have finished typing a sequence of ^N and // ^P or other completion characters in CTRL-X mode. Free up // memory that was used, and make sure we can redo the insert. diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index 526ac9f7f45616..90205c54504e71 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -2997,7 +2997,7 @@ func Test_complete_info_completed() endfunc -function Test_completeopt_preinsert() +func Test_completeopt_preinsert() func Omni_test(findstart, base) if a:findstart return col(".") @@ -3137,6 +3137,47 @@ function Test_completeopt_preinsert() call assert_equal(4, g:col) call assert_equal("wp.", getline('.')) + normal! ifoo + normal! obar + normal! obaz + let g:errmsg = '' + call assert_equal(['foo', 'bar'], getline(1, '$')) + call assert_equal(['foo'], getline(1, '$')) + call assert_equal([''], getline(1, '$')) + later 3 + call assert_equal('', v:errmsg) + endfunc + " Check that switching buffer with "preinsert" doesn't corrupt undo. + inoremap <buffer> <F2> <Cmd>enew!<CR> + bwipe! + " Check that closing window with "preinsert" doesn't corrupt undo. + inoremap <buffer> <F2> <Cmd>close!<CR> + delfunc CheckUndo bw! set omnifunc&
[ "+ func CheckUndo()" ]
[ 42 ]
{ "additions": 44, "author": "neovim-backports[bot]", "deletions": 2, "html_url": "https://github.com/neovim/neovim/pull/33601", "issue_id": 33601, "merged_at": "2025-04-24T00:45:05Z", "omission_probability": 0.1, "pr_number": 33601, "repo": "neovim/neovim", "title": "vim-patch:9.1.1337: Undo corrupted with 'completeopt' \"preinsert\" when switching buffer", "total_changes": 46 }
355
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index ab8bf2eec81465..cd536144a0f0b2 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2334,9 +2334,10 @@ static bool set_ctrl_x_mode(const int c) static bool ins_compl_stop(const int c, const int prev_mode, bool retval) { // Remove pre-inserted text when present. - if (ins_compl_preinsert_effect()) { + if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin)) { ins_compl_delete(false); } + // Get here when we have finished typing a sequence of ^N and // ^P or other completion characters in CTRL-X mode. Free up // memory that was used, and make sure we can redo the insert. diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index 066a538906ce70..ded4f7392efa0a 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -3223,7 +3223,7 @@ func Test_complete_info_completed() set cot& endfunc -function Test_completeopt_preinsert() +func Test_completeopt_preinsert() func Omni_test(findstart, base) if a:findstart return col(".") @@ -3363,6 +3363,47 @@ function Test_completeopt_preinsert() call assert_equal(4, g:col) call assert_equal("wp.", getline('.')) + %delete _ + let &l:undolevels = &l:undolevels + normal! ifoo + let &l:undolevels = &l:undolevels + normal! obar + let &l:undolevels = &l:undolevels + normal! obaz + let &l:undolevels = &l:undolevels + + func CheckUndo() + let g:errmsg = '' + call assert_equal(['foo', 'bar', 'baz'], getline(1, '$')) + undo + call assert_equal(['foo', 'bar'], getline(1, '$')) + undo + call assert_equal(['foo'], getline(1, '$')) + undo + call assert_equal([''], getline(1, '$')) + later 3 + call assert_equal(['foo', 'bar', 'baz'], getline(1, '$')) + call assert_equal('', v:errmsg) + endfunc + + " Check that switching buffer with "preinsert" doesn't corrupt undo. + new + setlocal bufhidden=wipe + inoremap <buffer> <F2> <Cmd>enew!<CR> + call feedkeys("i\<C-X>\<C-O>\<F2>\<Esc>", 'tx') + bwipe! + call CheckUndo() + + " Check that closing window with "preinsert" doesn't corrupt undo. + new + setlocal bufhidden=wipe + inoremap <buffer> <F2> <Cmd>close!<CR> + call feedkeys("i\<C-X>\<C-O>\<F2>\<Esc>", 'tx') + call CheckUndo() + + %delete _ + delfunc CheckUndo + bw! set cot& set omnifunc&
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index ab8bf2eec81465..cd536144a0f0b2 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -2334,9 +2334,10 @@ static bool set_ctrl_x_mode(const int c) static bool ins_compl_stop(const int c, const int prev_mode, bool retval) { // Remove pre-inserted text when present. - if (ins_compl_preinsert_effect()) { + if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin)) { ins_compl_delete(false); } // Get here when we have finished typing a sequence of ^N and // ^P or other completion characters in CTRL-X mode. Free up // memory that was used, and make sure we can redo the insert. diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index 066a538906ce70..ded4f7392efa0a 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -3223,7 +3223,7 @@ func Test_complete_info_completed() endfunc -function Test_completeopt_preinsert() +func Test_completeopt_preinsert() func Omni_test(findstart, base) if a:findstart return col(".") @@ -3363,6 +3363,47 @@ function Test_completeopt_preinsert() call assert_equal(4, g:col) call assert_equal("wp.", getline('.')) + normal! ifoo + normal! obar + func CheckUndo() + let g:errmsg = '' + call assert_equal(['foo', 'bar'], getline(1, '$')) + call assert_equal(['foo'], getline(1, '$')) + call assert_equal([''], getline(1, '$')) + later 3 + call assert_equal('', v:errmsg) + endfunc + " Check that switching buffer with "preinsert" doesn't corrupt undo. + inoremap <buffer> <F2> <Cmd>enew!<CR> + " Check that closing window with "preinsert" doesn't corrupt undo. + inoremap <buffer> <F2> <Cmd>close!<CR> bw! set omnifunc&
[ "+ normal! obaz", "+ bwipe!", "+ delfunc CheckUndo" ]
[ 39, 61, 72 ]
{ "additions": 44, "author": "zeertzjq", "deletions": 2, "html_url": "https://github.com/neovim/neovim/pull/33600", "issue_id": 33600, "merged_at": "2025-04-23T23:35:11Z", "omission_probability": 0.1, "pr_number": 33600, "repo": "neovim/neovim", "title": "vim-patch:9.1.1337: Undo corrupted with 'completeopt' \"preinsert\" when switching buffer", "total_changes": 46 }
356
diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index 5a697322412947..533572427c4c64 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -643,24 +643,17 @@ static void handle_unknown_csi(TermInput *input, const TermKeyKey *key) switch (initial) { case '?': // Kitty keyboard protocol query response. - if (input->waiting_for_kkp_response) { - input->waiting_for_kkp_response = false; - input->key_encoding = kKeyEncodingKitty; - tui_set_key_encoding(input->tui_data); - } - + input->key_encoding = kKeyEncodingKitty; break; } break; case 'c': switch (initial) { case '?': - // Primary Device Attributes response - if (input->waiting_for_kkp_response) { - input->waiting_for_kkp_response = false; - - // Enable the fallback key encoding (if any) - tui_set_key_encoding(input->tui_data); + // Primary Device Attributes (DA1) response + if (input->callbacks.primary_device_attr) { + input->callbacks.primary_device_attr(input->tui_data); + input->callbacks.primary_device_attr = NULL; } break; diff --git a/src/nvim/tui/input.h b/src/nvim/tui/input.h index e48982f9a4b5bc..4c5a64df9d66ab 100644 --- a/src/nvim/tui/input.h +++ b/src/nvim/tui/input.h @@ -17,6 +17,10 @@ typedef enum { kKeyEncodingXterm, ///< Xterm's modifyOtherKeys encoding (XTMODKEYS) } KeyEncoding; +typedef struct { + void (*primary_device_attr)(TUIData *tui); +} TermInputCallbacks; + #define KEY_BUFFER_SIZE 0x1000 typedef struct { int in_fd; @@ -24,8 +28,7 @@ typedef struct { int8_t paste; bool ttimeout; - bool waiting_for_kkp_response; ///< True if we are expecting to receive a response to a query for - ///< Kitty keyboard protocol support + TermInputCallbacks callbacks; KeyEncoding key_encoding; ///< The key encoding used by the terminal emulator diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 16f3d308d858f7..7332a84166dea8 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -18,6 +18,7 @@ #include "nvim/cursor_shape.h" #include "nvim/event/defs.h" #include "nvim/event/loop.h" +#include "nvim/event/multiqueue.h" #include "nvim/event/signal.h" #include "nvim/event/stream.h" #include "nvim/globals.h" @@ -46,6 +47,10 @@ # include "nvim/os/os_win_console.h" #endif +// Maximum amount of time (in ms) to wait to receive a Device Attributes +// response before exiting. +#define EXIT_TIMEOUT_MS 1000 + #define OUTBUF_SIZE 0xffff #define TOO_MANY_EVENTS 1000000 @@ -100,6 +105,7 @@ struct TUIData { bool bce; bool mouse_enabled; bool mouse_move_enabled; + bool mouse_enabled_save; bool title_enabled; bool sync_output; bool busy, is_invisible, want_invisible; @@ -287,7 +293,8 @@ void tui_enable_extended_underline(TUIData *tui) static void tui_query_kitty_keyboard(TUIData *tui) FUNC_ATTR_NONNULL_ALL { - tui->input.waiting_for_kkp_response = true; + // Set the key encoding whenever the Device Attributes (DA1) response is received. + tui->input.callbacks.primary_device_attr = tui_set_key_encoding; out(tui, S_LEN("\x1b[?u\x1b[c")); } @@ -514,8 +521,8 @@ static void terminfo_start(TUIData *tui) xfree(term_program_version_env); } -/// Disable the alternate screen and prepare for the TUI to close. -static void terminfo_stop(TUIData *tui) +/// Disable various terminal modes and other features. +static void terminfo_disable(TUIData *tui) { // Disable theme update notifications. We do this first to avoid getting any // more notifications after we reset the cursor and any color palette changes. @@ -540,9 +547,29 @@ static void terminfo_stop(TUIData *tui) // May restore old title before exiting alternate screen. tui_set_title(tui, NULL_STRING); + if (tui->cursor_has_color) { + unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); + } + // Disable bracketed paste + unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); + // Disable focus reporting + unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); + + // Send a DA1 request. When the terminal responds we know that it has + // processed all of our requests and won't be emitting anymore sequences. + out(tui, S_LEN("\x1b[c")); + + // Immediately flush the buffer and wait for the DA1 response. + flush_buf(tui); +} + +/// Disable the alternate screen and prepare for the TUI to close. +static void terminfo_stop(TUIData *tui) +{ if (ui_client_exit_status == 0) { ui_client_exit_status = tui->seen_error_exit; } + // if nvim exited with nonzero status, without indicated this was an // intentional exit (like `:1cquit`), it likely was an internal failure. // Don't clobber the stderr error message in this case. @@ -550,13 +577,6 @@ static void terminfo_stop(TUIData *tui) // Exit alternate screen. unibi_out(tui, unibi_exit_ca_mode); } - if (tui->cursor_has_color) { - unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); - } - // Disable bracketed paste - unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); - // Disable focus reporting - unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); flush_buf(tui); uv_tty_reset_mode(); @@ -592,8 +612,14 @@ static void tui_terminal_after_startup(TUIData *tui) flush_buf(tui); } -/// Stop the terminal but allow it to restart later (like after suspend) -static void tui_terminal_stop(TUIData *tui) +void tui_error_exit(TUIData *tui, Integer status) + FUNC_ATTR_NONNULL_ALL +{ + tui->seen_error_exit = (int)status; +} + +void tui_stop(TUIData *tui) + FUNC_ATTR_NONNULL_ALL { if (uv_is_closing((uv_handle_t *)&tui->output_handle)) { // Race between SIGCONT (tui.c) and SIGHUP (os/signal.c)? #8075 @@ -601,28 +627,42 @@ static void tui_terminal_stop(TUIData *tui) tui->stopped = true; return; } - tinput_stop(&tui->input); - // Position the cursor on the last screen line, below all the text - cursor_goto(tui, tui->height - 1, 0); - terminfo_stop(tui); -} -void tui_error_exit(TUIData *tui, Integer status) -{ - tui->seen_error_exit = (int)status; -} + tui->input.callbacks.primary_device_attr = tui_stop_cb; + terminfo_disable(tui); + + // Wait until DA1 response is received + LOOP_PROCESS_EVENTS_UNTIL(tui->loop, tui->loop->events, EXIT_TIMEOUT_MS, tui->stopped); -void tui_stop(TUIData *tui) -{ tui_terminal_stop(tui); stream_set_blocking(tui->input.in_fd, true); // normalize stream (#2598) tinput_destroy(&tui->input); - tui->stopped = true; signal_watcher_stop(&tui->winch_handle); signal_watcher_close(&tui->winch_handle, NULL); uv_close((uv_handle_t *)&tui->startup_delay_timer, NULL); } +/// Callback function called when the response to the Device Attributes (DA1) +/// request is sent during shutdown. +static void tui_stop_cb(TUIData *tui) + FUNC_ATTR_NONNULL_ALL +{ + tui->stopped = true; +} + +/// Stop the terminal but allow it to restart later (like after suspend) +/// +/// This is called after we receive the response to the DA1 request sent from +/// terminfo_disable. +static void tui_terminal_stop(TUIData *tui) + FUNC_ATTR_NONNULL_ALL +{ + tinput_stop(&tui->input); + // Position the cursor on the last screen line, below all the text + cursor_goto(tui, tui->height - 1, 0); + terminfo_stop(tui); +} + /// Returns true if UI `ui` is stopped. bool tui_is_stopped(TUIData *tui) { @@ -1581,7 +1621,16 @@ void tui_suspend(TUIData *tui) // on a non-UNIX system, this is a no-op #ifdef UNIX ui_client_detach(); - bool enable_mouse = tui->mouse_enabled; + tui->mouse_enabled_save = tui->mouse_enabled; + tui->input.callbacks.primary_device_attr = tui_suspend_cb; + terminfo_disable(tui); +#endif +} + +#ifdef UNIX +static void tui_suspend_cb(TUIData *tui) + FUNC_ATTR_NONNULL_ALL +{ tui_terminal_stop(tui); stream_set_blocking(tui->input.in_fd, true); // normalize stream (#2598) @@ -1590,13 +1639,13 @@ void tui_suspend(TUIData *tui) tui_terminal_start(tui); tui_terminal_after_startup(tui); - if (enable_mouse) { + if (tui->mouse_enabled_save) { tui_mouse_on(tui); } stream_set_blocking(tui->input.in_fd, false); // libuv expects this ui_client_attach(tui->width, tui->height, tui->term, tui->rgb); -#endif } +#endif void tui_set_title(TUIData *tui, String title) { @@ -2481,7 +2530,9 @@ static void augment_terminfo(TUIData *tui, const char *term, int vte_version, in if (!kitty && (vte_version == 0 || vte_version >= 5400)) { // Fallback to Xterm's modifyOtherKeys if terminal does not support the - // Kitty keyboard protocol + // Kitty keyboard protocol. We don't actually enable the key encoding here + // though: it won't be enabled until the terminal responds to our query for + // kitty keyboard support. tui->input.key_encoding = kKeyEncodingXterm; }
diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index 5a697322412947..533572427c4c64 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -643,24 +643,17 @@ static void handle_unknown_csi(TermInput *input, const TermKeyKey *key) // Kitty keyboard protocol query response. - input->key_encoding = kKeyEncodingKitty; - } + input->key_encoding = kKeyEncodingKitty; } break; case 'c': - // Primary Device Attributes response - // Enable the fallback key encoding (if any) + // Primary Device Attributes (DA1) response + if (input->callbacks.primary_device_attr) { + input->callbacks.primary_device_attr(input->tui_data); + input->callbacks.primary_device_attr = NULL; } diff --git a/src/nvim/tui/input.h b/src/nvim/tui/input.h index e48982f9a4b5bc..4c5a64df9d66ab 100644 --- a/src/nvim/tui/input.h +++ b/src/nvim/tui/input.h @@ -17,6 +17,10 @@ typedef enum { kKeyEncodingXterm, ///< Xterm's modifyOtherKeys encoding (XTMODKEYS) } KeyEncoding; + void (*primary_device_attr)(TUIData *tui); +} TermInputCallbacks; #define KEY_BUFFER_SIZE 0x1000 typedef struct { int in_fd; @@ -24,8 +28,7 @@ typedef struct { int8_t paste; bool ttimeout; - bool waiting_for_kkp_response; ///< True if we are expecting to receive a response to a query for - ///< Kitty keyboard protocol support + TermInputCallbacks callbacks; KeyEncoding key_encoding; ///< The key encoding used by the terminal emulator diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 16f3d308d858f7..7332a84166dea8 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -18,6 +18,7 @@ #include "nvim/cursor_shape.h" #include "nvim/event/defs.h" #include "nvim/event/loop.h" +#include "nvim/event/multiqueue.h" #include "nvim/event/signal.h" #include "nvim/event/stream.h" #include "nvim/globals.h" @@ -46,6 +47,10 @@ # include "nvim/os/os_win_console.h" #endif +// Maximum amount of time (in ms) to wait to receive a Device Attributes +// response before exiting. +#define EXIT_TIMEOUT_MS 1000 #define OUTBUF_SIZE 0xffff #define TOO_MANY_EVENTS 1000000 @@ -100,6 +105,7 @@ struct TUIData { bool bce; bool mouse_enabled; bool mouse_move_enabled; + bool mouse_enabled_save; bool title_enabled; bool sync_output; bool busy, is_invisible, want_invisible; @@ -287,7 +293,8 @@ void tui_enable_extended_underline(TUIData *tui) static void tui_query_kitty_keyboard(TUIData *tui) FUNC_ATTR_NONNULL_ALL - tui->input.waiting_for_kkp_response = true; + // Set the key encoding whenever the Device Attributes (DA1) response is received. out(tui, S_LEN("\x1b[?u\x1b[c")); @@ -514,8 +521,8 @@ static void terminfo_start(TUIData *tui) xfree(term_program_version_env); -static void terminfo_stop(TUIData *tui) +/// Disable various terminal modes and other features. +static void terminfo_disable(TUIData *tui) // Disable theme update notifications. We do this first to avoid getting any // more notifications after we reset the cursor and any color palette changes. @@ -540,9 +547,29 @@ static void terminfo_stop(TUIData *tui) // May restore old title before exiting alternate screen. tui_set_title(tui, NULL_STRING); + if (tui->cursor_has_color) { + unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); + } + // Disable bracketed paste + unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); + // Disable focus reporting + unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); + // Send a DA1 request. When the terminal responds we know that it has + // processed all of our requests and won't be emitting anymore sequences. + out(tui, S_LEN("\x1b[c")); + // Immediately flush the buffer and wait for the DA1 response. + flush_buf(tui); +/// Disable the alternate screen and prepare for the TUI to close. +static void terminfo_stop(TUIData *tui) if (ui_client_exit_status == 0) { ui_client_exit_status = tui->seen_error_exit; // if nvim exited with nonzero status, without indicated this was an // intentional exit (like `:1cquit`), it likely was an internal failure. // Don't clobber the stderr error message in this case. @@ -550,13 +577,6 @@ static void terminfo_stop(TUIData *tui) // Exit alternate screen. unibi_out(tui, unibi_exit_ca_mode); - if (tui->cursor_has_color) { - unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); - } - // Disable bracketed paste - unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); - // Disable focus reporting - unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); uv_tty_reset_mode(); @@ -592,8 +612,14 @@ static void tui_terminal_after_startup(TUIData *tui) -static void tui_terminal_stop(TUIData *tui) +void tui_error_exit(TUIData *tui, Integer status) + tui->seen_error_exit = (int)status; +void tui_stop(TUIData *tui) if (uv_is_closing((uv_handle_t *)&tui->output_handle)) { // Race between SIGCONT (tui.c) and SIGHUP (os/signal.c)? #8075 @@ -601,28 +627,42 @@ static void tui_terminal_stop(TUIData *tui) tui->stopped = true; return; - tinput_stop(&tui->input); - // Position the cursor on the last screen line, below all the text - terminfo_stop(tui); -void tui_error_exit(TUIData *tui, Integer status) - tui->seen_error_exit = (int)status; + tui->input.callbacks.primary_device_attr = tui_stop_cb; + // Wait until DA1 response is received -void tui_stop(TUIData *tui) tinput_destroy(&tui->input); - tui->stopped = true; signal_watcher_stop(&tui->winch_handle); signal_watcher_close(&tui->winch_handle, NULL); uv_close((uv_handle_t *)&tui->startup_delay_timer, NULL); +/// Callback function called when the response to the Device Attributes (DA1) +/// request is sent during shutdown. +static void tui_stop_cb(TUIData *tui) + tui->stopped = true; +/// Stop the terminal but allow it to restart later (like after suspend) +/// +/// This is called after we receive the response to the DA1 request sent from +/// terminfo_disable. + tinput_stop(&tui->input); + // Position the cursor on the last screen line, below all the text + cursor_goto(tui, tui->height - 1, 0); + terminfo_stop(tui); /// Returns true if UI `ui` is stopped. bool tui_is_stopped(TUIData *tui) @@ -1581,7 +1621,16 @@ void tui_suspend(TUIData *tui) // on a non-UNIX system, this is a no-op #ifdef UNIX ui_client_detach(); - bool enable_mouse = tui->mouse_enabled; + tui->mouse_enabled_save = tui->mouse_enabled; + tui->input.callbacks.primary_device_attr = tui_suspend_cb; +#ifdef UNIX @@ -1590,13 +1639,13 @@ void tui_suspend(TUIData *tui) tui_terminal_start(tui); tui_terminal_after_startup(tui); - if (enable_mouse) { + if (tui->mouse_enabled_save) { tui_mouse_on(tui); stream_set_blocking(tui->input.in_fd, false); // libuv expects this ui_client_attach(tui->width, tui->height, tui->term, tui->rgb); -#endif void tui_set_title(TUIData *tui, String title) @@ -2481,7 +2530,9 @@ static void augment_terminfo(TUIData *tui, const char *term, int vte_version, in if (!kitty && (vte_version == 0 || vte_version >= 5400)) { // Fallback to Xterm's modifyOtherKeys if terminal does not support the - // Kitty keyboard protocol + // though: it won't be enabled until the terminal responds to our query for + // kitty keyboard support. tui->input.key_encoding = kKeyEncodingXterm;
[ "+typedef struct {", "+ tui->input.callbacks.primary_device_attr = tui_set_key_encoding;", "-/// Disable the alternate screen and prepare for the TUI to close.", "-/// Stop the terminal but allow it to restart later (like after suspend)", "- cursor_goto(tui, tui->height - 1, 0);", "+ LOOP_PROCESS_EVENTS_UNTIL(tui->loop, tui->loop->events, EXIT_TIMEOUT_MS, tui->stopped);", "+static void tui_terminal_stop(TUIData *tui)", "+static void tui_suspend_cb(TUIData *tui)", "+ // Kitty keyboard protocol. We don't actually enable the key encoding here" ]
[ 42, 96, 104, 159, 178, 190, 215, 239, 266 ]
{ "additions": 89, "author": "gpanders", "deletions": 42, "html_url": "https://github.com/neovim/neovim/pull/32151", "issue_id": 32151, "merged_at": "2025-04-22T12:18:34Z", "omission_probability": 0.1, "pr_number": 32151, "repo": "neovim/neovim", "title": "fix(tui): ensure all pending escape sequences are processed before exiting", "total_changes": 131 }
357
diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index 4b93f09c61b3d1..ce51205d505d41 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -154,14 +154,12 @@ Dict(cmd) nvim_parse_cmd(String str, Dict(empty) *opts, Arena *arena, Error *err char *name = (cmd != NULL ? cmd->uc_name : get_command_name(NULL, ea.cmdidx)); PUT_KEY(result, cmd, cmd, cstr_as_string(name)); - if (ea.argt & EX_RANGE) { + if ((ea.argt & EX_RANGE) && ea.addr_count > 0) { Array range = arena_array(arena, 2); - if (ea.addr_count > 0) { - if (ea.addr_count > 1) { - ADD_C(range, INTEGER_OBJ(ea.line1)); - } - ADD_C(range, INTEGER_OBJ(ea.line2)); + if (ea.addr_count > 1) { + ADD_C(range, INTEGER_OBJ(ea.line1)); } + ADD_C(range, INTEGER_OBJ(ea.line2)); PUT_KEY(result, cmd, range, range); } diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua index 249ba611f0de3a..03253f2b471f23 100644 --- a/test/functional/api/vim_spec.lua +++ b/test/functional/api/vim_spec.lua @@ -4307,7 +4307,6 @@ describe('API', function() cmd = 'put', args = {}, bang = false, - range = {}, reg = '+', addr = 'line', magic = { @@ -4346,7 +4345,6 @@ describe('API', function() cmd = 'put', args = {}, bang = false, - range = {}, reg = '', addr = 'line', magic = { @@ -4429,7 +4427,6 @@ describe('API', function() cmd = 'write', args = {}, bang = true, - range = {}, addr = 'line', magic = { file = true, @@ -4470,7 +4467,6 @@ describe('API', function() cmd = 'split', args = { 'foo.txt' }, bang = false, - range = {}, addr = '?', magic = { file = true, @@ -4514,7 +4510,6 @@ describe('API', function() cmd = 'split', args = { 'foo.txt' }, bang = false, - range = {}, addr = '?', magic = { file = true, @@ -4600,7 +4595,6 @@ describe('API', function() cmd = 'argadd', args = { 'a.txt' }, bang = false, - range = {}, addr = 'arg', magic = { file = true, @@ -4775,6 +4769,8 @@ describe('API', function() eq('foo', api.nvim_cmd(api.nvim_parse_cmd('echo "foo"', {}), { output = true })) api.nvim_cmd(api.nvim_parse_cmd('set cursorline', {}), {}) eq(true, api.nvim_get_option_value('cursorline', {})) + -- Roundtrip on :bdelete which does not accept "range". #33394 + api.nvim_cmd(api.nvim_parse_cmd('bdelete', {}), {}) end) it('no side-effects (error messages) in pcall() #20339', function() eq(
diff --git a/src/nvim/api/command.c b/src/nvim/api/command.c index 4b93f09c61b3d1..ce51205d505d41 100644 --- a/src/nvim/api/command.c +++ b/src/nvim/api/command.c @@ -154,14 +154,12 @@ Dict(cmd) nvim_parse_cmd(String str, Dict(empty) *opts, Arena *arena, Error *err char *name = (cmd != NULL ? cmd->uc_name : get_command_name(NULL, ea.cmdidx)); PUT_KEY(result, cmd, cmd, cstr_as_string(name)); - if (ea.argt & EX_RANGE) { + if ((ea.argt & EX_RANGE) && ea.addr_count > 0) { Array range = arena_array(arena, 2); - if (ea.addr_count > 0) { - if (ea.addr_count > 1) { - ADD_C(range, INTEGER_OBJ(ea.line1)); - } - ADD_C(range, INTEGER_OBJ(ea.line2)); + if (ea.addr_count > 1) { + ADD_C(range, INTEGER_OBJ(ea.line1)); } + ADD_C(range, INTEGER_OBJ(ea.line2)); PUT_KEY(result, cmd, range, range); } diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua index 249ba611f0de3a..03253f2b471f23 100644 --- a/test/functional/api/vim_spec.lua +++ b/test/functional/api/vim_spec.lua @@ -4307,7 +4307,6 @@ describe('API', function() reg = '+', @@ -4346,7 +4345,6 @@ describe('API', function() reg = '', @@ -4429,7 +4427,6 @@ describe('API', function() cmd = 'write', bang = true, @@ -4470,7 +4467,6 @@ describe('API', function() @@ -4514,7 +4510,6 @@ describe('API', function() @@ -4600,7 +4595,6 @@ describe('API', function() cmd = 'argadd', args = { 'a.txt' }, addr = 'arg', @@ -4775,6 +4769,8 @@ describe('API', function() eq('foo', api.nvim_cmd(api.nvim_parse_cmd('echo "foo"', {}), { output = true })) api.nvim_cmd(api.nvim_parse_cmd('set cursorline', {}), {}) eq(true, api.nvim_get_option_value('cursorline', {})) + -- Roundtrip on :bdelete which does not accept "range". #33394 + api.nvim_cmd(api.nvim_parse_cmd('bdelete', {}), {}) end) it('no side-effects (error messages) in pcall() #20339', function() eq(
[]
[]
{ "additions": 6, "author": "acehinnnqru", "deletions": 12, "html_url": "https://github.com/neovim/neovim/pull/33536", "issue_id": 33536, "merged_at": "2025-04-23T14:56:18Z", "omission_probability": 0.1, "pr_number": 33536, "repo": "neovim/neovim", "title": "fix(api): nvim_parse_cmd don't put key 'range' when ea.addr_count == 0", "total_changes": 18 }
358
diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c index c1e123c9258b31..e18e2a711d5c96 100644 --- a/src/nvim/ui_compositor.c +++ b/src/nvim/ui_compositor.c @@ -422,10 +422,12 @@ static void compose_line(Integer row, Integer startcol, Integer endcol, LineFlag for (int i = col - (int)startcol; i < until - startcol; i += width) { width = 1; // negative space - bool thru = linebuf[i] == schar_from_ascii(' ') && bg_line[i] != NUL; + bool thru = (linebuf[i] == schar_from_ascii(' ') + || linebuf[i] == schar_from_char(L'\u2800')) && bg_line[i] != NUL; if (i + 1 < endcol - startcol && bg_line[i + 1] == NUL) { width = 2; - thru &= linebuf[i + 1] == schar_from_ascii(' '); + thru &= (linebuf[i + 1] == schar_from_ascii(' ') + || linebuf[i + 1] == schar_from_char(L'\u2800')); } attrbuf[i] = (sattr_T)hl_blend_attrs(bg_attrs[i], attrbuf[i], &thru); if (width == 2) { diff --git a/test/functional/ui/float_spec.lua b/test/functional/ui/float_spec.lua index fc0849b450ebf8..dda5f2096a18c2 100644 --- a/test/functional/ui/float_spec.lua +++ b/test/functional/ui/float_spec.lua @@ -7947,7 +7947,8 @@ describe('float window', function() qui officia deserunt mollit anim id est laborum.]]) local buf = api.nvim_create_buf(false,false) - api.nvim_buf_set_lines(buf, 0, -1, true, {"test", "", "popup text"}) + local test_data = {"test", "", "popup text"} + api.nvim_buf_set_lines(buf, 0, -1, true, test_data) local win = api.nvim_open_win(buf, false, {relative='editor', width=15, height=3, row=2, col=5}) if multigrid then screen:expect{grid=[[ @@ -8020,6 +8021,45 @@ describe('float window', function() ]]) end + -- Test for \u2800 (braille blank unicode character) + local braille_blank = "\226\160\128" + api.nvim_buf_set_lines(buf, 0, -1, true, {"test" .. braille_blank, "", "popup"..braille_blank.." text"}) + if multigrid then + screen:expect{grid=[[ + ## grid 1 + [2:--------------------------------------------------]|*8 + [3:--------------------------------------------------]| + ## grid 2 + Ut enim ad minim veniam, quis nostrud | + exercitation ullamco laboris nisi ut aliquip ex | + ea commodo consequat. Duis aute irure dolor in | + reprehenderit in voluptate velit esse cillum | + dolore eu fugiat nulla pariatur. Excepteur sint | + occaecat cupidatat non proident, sunt in culpa | + qui officia deserunt mollit anim id est | + laborum^. | + ## grid 3 + | + ## grid 4 + {9:test]] .. braille_blank .. [[ }| + {9: }| + {9:popup]] .. braille_blank .. [[ text }| + ]], float_pos={[4] = {1001, "NW", 1, 2, 5, true, 50, 1, 2, 5}}, unchanged=true} + else + screen:expect([[ + Ut enim ad minim veniam, quis nostrud | + exercitation ullamco laboris nisi ut aliquip ex | + ea co{2:test}{3:o consequat}. Duis aute irure dolor in | + repre{3:henderit in vol}uptate velit esse cillum | + dolor{2:popup}{3:fugi}{2:text}{3:ul}la pariatur. Excepteur sint | + occaecat cupidatat non proident, sunt in culpa | + qui officia deserunt mollit anim id est | + laborum^. | + | + ]]) + end + api.nvim_buf_set_lines(buf, 0, -1, true, test_data) + -- Check that 'winblend' works with NormalNC highlight api.nvim_set_option_value('winhighlight', 'NormalNC:Visual', {win = win}) if multigrid then
diff --git a/src/nvim/ui_compositor.c b/src/nvim/ui_compositor.c index c1e123c9258b31..e18e2a711d5c96 100644 --- a/src/nvim/ui_compositor.c +++ b/src/nvim/ui_compositor.c @@ -422,10 +422,12 @@ static void compose_line(Integer row, Integer startcol, Integer endcol, LineFlag for (int i = col - (int)startcol; i < until - startcol; i += width) { width = 1; // negative space + bool thru = (linebuf[i] == schar_from_ascii(' ') + || linebuf[i] == schar_from_char(L'\u2800')) && bg_line[i] != NUL; if (i + 1 < endcol - startcol && bg_line[i + 1] == NUL) { width = 2; - thru &= linebuf[i + 1] == schar_from_ascii(' '); + thru &= (linebuf[i + 1] == schar_from_ascii(' ') + || linebuf[i + 1] == schar_from_char(L'\u2800')); } attrbuf[i] = (sattr_T)hl_blend_attrs(bg_attrs[i], attrbuf[i], &thru); if (width == 2) { diff --git a/test/functional/ui/float_spec.lua b/test/functional/ui/float_spec.lua index fc0849b450ebf8..dda5f2096a18c2 100644 --- a/test/functional/ui/float_spec.lua +++ b/test/functional/ui/float_spec.lua @@ -7947,7 +7947,8 @@ describe('float window', function() qui officia deserunt mollit anim id est laborum.]]) local buf = api.nvim_create_buf(false,false) - api.nvim_buf_set_lines(buf, 0, -1, true, {"test", "", "popup text"}) + local test_data = {"test", "", "popup text"} local win = api.nvim_open_win(buf, false, {relative='editor', width=15, height=3, row=2, col=5}) screen:expect{grid=[[ @@ -8020,6 +8021,45 @@ describe('float window', function() ]]) end + -- Test for \u2800 (braille blank unicode character) + local braille_blank = "\226\160\128" + api.nvim_buf_set_lines(buf, 0, -1, true, {"test" .. braille_blank, "", "popup"..braille_blank.." text"}) + if multigrid then + screen:expect{grid=[[ + [2:--------------------------------------------------]|*8 + [3:--------------------------------------------------]| + ## grid 2 + ea commodo consequat. Duis aute irure dolor in | + reprehenderit in voluptate velit esse cillum | + dolore eu fugiat nulla pariatur. Excepteur sint | + ## grid 3 + ## grid 4 + {9:test]] .. braille_blank .. [[ }| + {9: }| + {9:popup]] .. braille_blank .. [[ text }| + ]], float_pos={[4] = {1001, "NW", 1, 2, 5, true, 50, 1, 2, 5}}, unchanged=true} + else + screen:expect([[ + ea co{2:test}{3:o consequat}. Duis aute irure dolor in | + dolor{2:popup}{3:fugi}{2:text}{3:ul}la pariatur. Excepteur sint | + ]]) + end + -- Check that 'winblend' works with NormalNC highlight api.nvim_set_option_value('winhighlight', 'NormalNC:Visual', {win = win})
[ "- bool thru = linebuf[i] == schar_from_ascii(' ') && bg_line[i] != NUL;", "+ ## grid 1", "+ repre{3:henderit in vol}uptate velit esse cillum |" ]
[ 8, 42, 66 ]
{ "additions": 45, "author": "SkohTV", "deletions": 3, "html_url": "https://github.com/neovim/neovim/pull/32741", "issue_id": 32741, "merged_at": "2025-04-23T12:27:21Z", "omission_probability": 0.1, "pr_number": 32741, "repo": "neovim/neovim", "title": "fix(winblend): treat braille blank (\\u2800) as whitespace #32741", "total_changes": 48 }
359
diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index 6e60535a88688e..a205e9a44640e4 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -458,7 +458,7 @@ function vim.api.nvim_buf_get_lines(buffer, start, end_, strict_indexing) end --- @see vim.api.nvim_buf_del_mark --- @param buffer integer Buffer id, or 0 for current buffer --- @param name string Mark name ---- @return integer[] # (row, col) tuple, (0, 0) if the mark is not set, or is an +--- @return [integer, integer] # (row, col) tuple, (0, 0) if the mark is not set, or is an --- uppercase/file mark set in another buffer. function vim.api.nvim_buf_get_mark(buffer, name) end @@ -2382,7 +2382,7 @@ function vim.api.nvim_win_get_config(window) end --- --- @see `:help getcurpos()` --- @param window integer `window-ID`, or 0 for current window ---- @return integer[] # (row, col) tuple +--- @return [integer, integer] # (row, col) tuple function vim.api.nvim_win_get_cursor(window) end --- Gets the window height @@ -2406,7 +2406,7 @@ function vim.api.nvim_win_get_option(window, name) end --- Gets the window position in display cells. First position is zero. --- --- @param window integer `window-ID`, or 0 for current window ---- @return integer[] # (row, col) tuple with the window position +--- @return [integer, integer] # (row, col) tuple with the window position function vim.api.nvim_win_get_position(window) end --- Gets the window tabpage @@ -2467,7 +2467,7 @@ function vim.api.nvim_win_set_config(window, config) end --- This scrolls the window even if it is not the current one. --- --- @param window integer `window-ID`, or 0 for current window ---- @param pos integer[] (row, col) tuple representing the new position +--- @param pos [integer, integer] (row, col) tuple representing the new position function vim.api.nvim_win_set_cursor(window, pos) end --- Sets the window height. diff --git a/src/gen/gen_eval_files.lua b/src/gen/gen_eval_files.lua index ffff3fa82d484b..4bf648f934b80a 100755 --- a/src/gen/gen_eval_files.lua +++ b/src/gen/gen_eval_files.lua @@ -174,7 +174,13 @@ local function api_type(t) local as0 = t:match('^ArrayOf%((.*)%)') if as0 then local as = split(as0, ', ') - return api_type(as[1]) .. '[]' + local a = api_type(as[1]) + local count = tonumber(as[2]) + if count then + return ('[%s]'):format(a:rep(count, ', ')) + else + return a .. '[]' + end end local d = t:match('^Dict%((.*)%)')
diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index 6e60535a88688e..a205e9a44640e4 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -458,7 +458,7 @@ function vim.api.nvim_buf_get_lines(buffer, start, end_, strict_indexing) end --- @see vim.api.nvim_buf_del_mark --- @param buffer integer Buffer id, or 0 for current buffer --- @param name string Mark name ---- @return integer[] # (row, col) tuple, (0, 0) if the mark is not set, or is an +--- @return [integer, integer] # (row, col) tuple, (0, 0) if the mark is not set, or is an --- uppercase/file mark set in another buffer. function vim.api.nvim_buf_get_mark(buffer, name) end @@ -2382,7 +2382,7 @@ function vim.api.nvim_win_get_config(window) end --- @see `:help getcurpos()` ---- @return integer[] # (row, col) tuple +--- @return [integer, integer] # (row, col) tuple function vim.api.nvim_win_get_cursor(window) end --- Gets the window height @@ -2406,7 +2406,7 @@ function vim.api.nvim_win_get_option(window, name) end --- Gets the window position in display cells. First position is zero. ---- @return integer[] # (row, col) tuple with the window position +--- @return [integer, integer] # (row, col) tuple with the window position function vim.api.nvim_win_get_position(window) end --- Gets the window tabpage @@ -2467,7 +2467,7 @@ function vim.api.nvim_win_set_config(window, config) end --- This scrolls the window even if it is not the current one. ---- @param pos integer[] (row, col) tuple representing the new position +--- @param pos [integer, integer] (row, col) tuple representing the new position function vim.api.nvim_win_set_cursor(window, pos) end --- Sets the window height. diff --git a/src/gen/gen_eval_files.lua b/src/gen/gen_eval_files.lua index ffff3fa82d484b..4bf648f934b80a 100755 --- a/src/gen/gen_eval_files.lua +++ b/src/gen/gen_eval_files.lua @@ -174,7 +174,13 @@ local function api_type(t) local as0 = t:match('^ArrayOf%((.*)%)') if as0 then local as = split(as0, ', ') - return api_type(as[1]) .. '[]' + local a = api_type(as[1]) + local count = tonumber(as[2]) + if count then + return ('[%s]'):format(a:rep(count, ', ')) + else + return a .. '[]' + end end local d = t:match('^Dict%((.*)%)')
[]
[]
{ "additions": 11, "author": "lewis6991", "deletions": 1, "html_url": "https://github.com/neovim/neovim/pull/33594", "issue_id": 33594, "merged_at": "2025-04-23T10:58:30Z", "omission_probability": 0.1, "pr_number": 33594, "repo": "neovim/neovim", "title": "feat: render tuple types for API methods", "total_changes": 12 }
360
diff --git a/runtime/lua/vim/snippet.lua b/runtime/lua/vim/snippet.lua index e84a9e376a7cab..0d7dd6a0348fbe 100644 --- a/runtime/lua/vim/snippet.lua +++ b/runtime/lua/vim/snippet.lua @@ -278,15 +278,6 @@ local function select_tabstop(tabstop) vim.api.nvim_feedkeys(keys, 'n', true) end - --- NOTE: We don't use `vim.api.nvim_win_set_cursor` here because it causes the cursor to end - --- at the end of the selection instead of the start. - --- - --- @param row integer - --- @param col integer - local function move_cursor_to(row, col) - feedkeys(string.format('%sG%s|', row, col)) - end - local range = tabstop:get_range() local mode = vim.fn.mode() @@ -311,13 +302,16 @@ local function select_tabstop(tabstop) end else -- Else, select the tabstop's text. - if mode ~= 'n' then - feedkeys('<Esc>') - end - move_cursor_to(range[1] + 1, range[2] + 1) - feedkeys('v') - move_cursor_to(range[3] + 1, range[4]) - feedkeys('o<c-g><c-r>_') + -- Need this exact order so cannot mix regular API calls with feedkeys, which + -- are not executed immediately. Use <Cmd> to set the cursor position. + local keys = { + mode ~= 'n' and '<Esc>' or '', + ('<Cmd>call cursor(%s,%s)<CR>'):format(range[1] + 1, range[2] + 1), + 'v', + ('<Cmd>call cursor(%s,%s)<CR>'):format(range[3] + 1, range[4]), + 'o<c-g><c-r>_', + } + feedkeys(table.concat(keys)) end end diff --git a/test/functional/lua/snippet_spec.lua b/test/functional/lua/snippet_spec.lua index 724437f0b245e4..33f2ef6222909b 100644 --- a/test/functional/lua/snippet_spec.lua +++ b/test/functional/lua/snippet_spec.lua @@ -307,4 +307,10 @@ describe('vim.snippet', function() ]] ) end) + + it('correct visual selection with multi-byte text', function() + test_expand_success({ 'function(${1:var})' }, { '口口function(var)' }, nil, '口口') + feed('foo') + eq({ '口口function(foo)' }, buf_lines(0)) + end) end)
diff --git a/runtime/lua/vim/snippet.lua b/runtime/lua/vim/snippet.lua index e84a9e376a7cab..0d7dd6a0348fbe 100644 --- a/runtime/lua/vim/snippet.lua +++ b/runtime/lua/vim/snippet.lua @@ -278,15 +278,6 @@ local function select_tabstop(tabstop) vim.api.nvim_feedkeys(keys, 'n', true) - --- NOTE: We don't use `vim.api.nvim_win_set_cursor` here because it causes the cursor to end - --- at the end of the selection instead of the start. - --- - --- @param row integer - --- @param col integer - local function move_cursor_to(row, col) - feedkeys(string.format('%sG%s|', row, col)) - end - local range = tabstop:get_range() local mode = vim.fn.mode() @@ -311,13 +302,16 @@ local function select_tabstop(tabstop) end else -- Else, select the tabstop's text. - if mode ~= 'n' then - feedkeys('<Esc>') - end - move_cursor_to(range[1] + 1, range[2] + 1) - feedkeys('v') - move_cursor_to(range[3] + 1, range[4]) - feedkeys('o<c-g><c-r>_') + -- Need this exact order so cannot mix regular API calls with feedkeys, which + -- are not executed immediately. Use <Cmd> to set the cursor position. + local keys = { + 'v', + ('<Cmd>call cursor(%s,%s)<CR>'):format(range[3] + 1, range[4]), + 'o<c-g><c-r>_', + } + feedkeys(table.concat(keys)) end diff --git a/test/functional/lua/snippet_spec.lua b/test/functional/lua/snippet_spec.lua index 724437f0b245e4..33f2ef6222909b 100644 --- a/test/functional/lua/snippet_spec.lua +++ b/test/functional/lua/snippet_spec.lua @@ -307,4 +307,10 @@ describe('vim.snippet', function() ]] ) end) + + it('correct visual selection with multi-byte text', function() + test_expand_success({ 'function(${1:var})' }, { '口口function(var)' }, nil, '口口') + eq({ '口口function(foo)' }, buf_lines(0)) + end) end)
[ "+ mode ~= 'n' and '<Esc>' or '',", "+ ('<Cmd>call cursor(%s,%s)<CR>'):format(range[1] + 1, range[2] + 1),", "+ feed('foo')" ]
[ 34, 35, 55 ]
{ "additions": 16, "author": "neovim-backports[bot]", "deletions": 16, "html_url": "https://github.com/neovim/neovim/pull/33592", "issue_id": 33592, "merged_at": "2025-04-23T09:24:54Z", "omission_probability": 0.1, "pr_number": 33592, "repo": "neovim/neovim", "title": "fix(snippet): use <cmd>call cursor() for visual range", "total_changes": 32 }
361
diff --git a/runtime/lua/vim/snippet.lua b/runtime/lua/vim/snippet.lua index e84a9e376a7cab..0d7dd6a0348fbe 100644 --- a/runtime/lua/vim/snippet.lua +++ b/runtime/lua/vim/snippet.lua @@ -278,15 +278,6 @@ local function select_tabstop(tabstop) vim.api.nvim_feedkeys(keys, 'n', true) end - --- NOTE: We don't use `vim.api.nvim_win_set_cursor` here because it causes the cursor to end - --- at the end of the selection instead of the start. - --- - --- @param row integer - --- @param col integer - local function move_cursor_to(row, col) - feedkeys(string.format('%sG%s|', row, col)) - end - local range = tabstop:get_range() local mode = vim.fn.mode() @@ -311,13 +302,16 @@ local function select_tabstop(tabstop) end else -- Else, select the tabstop's text. - if mode ~= 'n' then - feedkeys('<Esc>') - end - move_cursor_to(range[1] + 1, range[2] + 1) - feedkeys('v') - move_cursor_to(range[3] + 1, range[4]) - feedkeys('o<c-g><c-r>_') + -- Need this exact order so cannot mix regular API calls with feedkeys, which + -- are not executed immediately. Use <Cmd> to set the cursor position. + local keys = { + mode ~= 'n' and '<Esc>' or '', + ('<Cmd>call cursor(%s,%s)<CR>'):format(range[1] + 1, range[2] + 1), + 'v', + ('<Cmd>call cursor(%s,%s)<CR>'):format(range[3] + 1, range[4]), + 'o<c-g><c-r>_', + } + feedkeys(table.concat(keys)) end end diff --git a/test/functional/lua/snippet_spec.lua b/test/functional/lua/snippet_spec.lua index 724437f0b245e4..33f2ef6222909b 100644 --- a/test/functional/lua/snippet_spec.lua +++ b/test/functional/lua/snippet_spec.lua @@ -307,4 +307,10 @@ describe('vim.snippet', function() ]] ) end) + + it('correct visual selection with multi-byte text', function() + test_expand_success({ 'function(${1:var})' }, { '口口function(var)' }, nil, '口口') + feed('foo') + eq({ '口口function(foo)' }, buf_lines(0)) + end) end)
diff --git a/runtime/lua/vim/snippet.lua b/runtime/lua/vim/snippet.lua index e84a9e376a7cab..0d7dd6a0348fbe 100644 --- a/runtime/lua/vim/snippet.lua +++ b/runtime/lua/vim/snippet.lua @@ -278,15 +278,6 @@ local function select_tabstop(tabstop) vim.api.nvim_feedkeys(keys, 'n', true) - --- NOTE: We don't use `vim.api.nvim_win_set_cursor` here because it causes the cursor to end - --- at the end of the selection instead of the start. - --- - --- @param col integer - local function move_cursor_to(row, col) - feedkeys(string.format('%sG%s|', row, col)) - end - local range = tabstop:get_range() local mode = vim.fn.mode() @@ -311,13 +302,16 @@ local function select_tabstop(tabstop) end else -- Else, select the tabstop's text. - if mode ~= 'n' then - feedkeys('<Esc>') - end - move_cursor_to(range[1] + 1, range[2] + 1) - feedkeys('v') - move_cursor_to(range[3] + 1, range[4]) + -- Need this exact order so cannot mix regular API calls with feedkeys, which + -- are not executed immediately. Use <Cmd> to set the cursor position. + local keys = { + 'v', + ('<Cmd>call cursor(%s,%s)<CR>'):format(range[3] + 1, range[4]), + 'o<c-g><c-r>_', + } + feedkeys(table.concat(keys)) end diff --git a/test/functional/lua/snippet_spec.lua b/test/functional/lua/snippet_spec.lua index 724437f0b245e4..33f2ef6222909b 100644 --- a/test/functional/lua/snippet_spec.lua +++ b/test/functional/lua/snippet_spec.lua @@ -307,4 +307,10 @@ describe('vim.snippet', function() ]] ) end) + + it('correct visual selection with multi-byte text', function() + test_expand_success({ 'function(${1:var})' }, { '口口function(var)' }, nil, '口口') + feed('foo') + eq({ '口口function(foo)' }, buf_lines(0)) + end) end)
[ "- --- @param row integer", "- feedkeys('o<c-g><c-r>_')", "+ mode ~= 'n' and '<Esc>' or '',", "+ ('<Cmd>call cursor(%s,%s)<CR>'):format(range[1] + 1, range[2] + 1)," ]
[ 11, 30, 34, 35 ]
{ "additions": 16, "author": "luukvbaal", "deletions": 16, "html_url": "https://github.com/neovim/neovim/pull/33582", "issue_id": 33582, "merged_at": "2025-04-23T08:58:23Z", "omission_probability": 0.1, "pr_number": 33582, "repo": "neovim/neovim", "title": "fix(snippet): use <cmd>call cursor() for visual range", "total_changes": 32 }
362
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index d913df7e2f1b9f..29f68dbd0205f9 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -1129,6 +1129,13 @@ functions with [[ and ]]. Move around comments with ]" and [". The mappings can be disabled with: > let g:no_vim_maps = 1 +YAML *ft-yaml-plugin* +By default, the YAML filetype plugin enables the following options: > + setlocal shiftwidth=2 softtabstop=2 + +To disable this, set the following variable: > + let g:yaml_recommended_style = 0 + ZIG *ft-zig-plugin* diff --git a/runtime/ftplugin/yaml.vim b/runtime/ftplugin/yaml.vim index 4e12350c22bf90..12036a86aacb0d 100644 --- a/runtime/ftplugin/yaml.vim +++ b/runtime/ftplugin/yaml.vim @@ -1,7 +1,8 @@ " Vim filetype plugin file " Language: YAML (YAML Ain't Markup Language) " Previous Maintainer: Nikolai Weibull <[email protected]> (inactive) -" Last Change: 2024 Oct 04 +" Last Change: 2024 Oct 04 +" 2025 Apr 22 by Vim project re-order b:undo_ftplugin (#17179) if exists("b:did_ftplugin") finish @@ -16,20 +17,25 @@ let b:undo_ftplugin = "setl com< cms< et< fo<" setlocal comments=:# commentstring=#\ %s expandtab setlocal formatoptions-=t formatoptions+=croql -" rime input method engine uses `*.custom.yaml` as its config files +if get(g:, "yaml_recommended_style",1) + let b:undo_ftplugin ..= " sw< sts<" + setlocal shiftwidth=2 softtabstop=2 +endif + +" rime input method engine(https://rime.im/) +" uses `*.custom.yaml` as its config files if expand('%:r:e') ==# 'custom' + " `__include` command in `*.custom.yaml` + " see: https://github.com/rime/home/wiki/Configuration#%E5%8C%85%E5%90%AB + setlocal include=__include:\\s* + let b:undo_ftplugin ..= " inc<" + if !exists('current_compiler') compiler rime_deployer - let b:undo_ftplugin ..= "| compiler make" + let b:undo_ftplugin ..= " | compiler make" endif - setlocal include=__include:\\s* - let b:undo_ftplugin ..= " inc<" endif -if !exists("g:yaml_recommended_style") || g:yaml_recommended_style != 0 - let b:undo_ftplugin ..= " sw< sts<" - setlocal shiftwidth=2 softtabstop=2 -endif let &cpo = s:cpo_save unlet s:cpo_save diff --git a/runtime/indent/make.vim b/runtime/indent/make.vim index 4d1838b3aa000c..aeea4de741d477 100644 --- a/runtime/indent/make.vim +++ b/runtime/indent/make.vim @@ -3,6 +3,7 @@ " Maintainer: Doug Kearns <[email protected]> " Previous Maintainer: Nikolai Weibull <[email protected]> " Last Change: 2022 Apr 06 +" 2025 Apr 22 by Vim Project: do not indent after special targets #17183 if exists("b:did_indent") finish @@ -21,6 +22,8 @@ endif let s:comment_rx = '^\s*#' let s:rule_rx = '^[^ \t#:][^#:]*:\{1,2}\%([^=:]\|$\)' +" .PHONY, .DELETE_ON_ERROR, etc +let s:rule_special = '^\.[A-Z_]\+\s*:' let s:continued_rule_rx = '^[^#:]*:\{1,2}\%([^=:]\|$\)' let s:continuation_rx = '\\$' let s:assignment_rx = '^\s*\h\w*\s*[+:?]\==\s*\zs.*\\$' @@ -50,7 +53,7 @@ function GetMakeIndent() if prev_line =~ s:continuation_rx if prev_prev_line =~ s:continuation_rx return indent(prev_lnum) - elseif prev_line =~ s:rule_rx + elseif prev_line =~ s:rule_rx && prev_line !~ s:rule_special return shiftwidth() elseif prev_line =~ s:assignment_rx call cursor(prev_lnum, 1) @@ -81,15 +84,15 @@ function GetMakeIndent() let line = getline(lnum) endwhile let folded_lnum = lnum + 1 - if folded_line =~ s:rule_rx - if getline(v:lnum) =~ s:rule_rx + if folded_line =~ s:rule_rx && prev_line !~ s:rule_special + if getline(v:lnum) =~ s:rule_rx && prev_line !~ s:rule_special return 0 else return &ts endif else " elseif folded_line =~ s:folded_assignment_rx - if getline(v:lnum) =~ s:rule_rx + if getline(v:lnum) =~ s:rule_rx && prev_line !~ s:rule_special return 0 else return indent(folded_lnum) @@ -98,8 +101,8 @@ function GetMakeIndent() " " TODO: ? " return indent(prev_lnum) endif - elseif prev_line =~ s:rule_rx - if getline(v:lnum) =~ s:rule_rx + elseif prev_line =~ s:rule_rx && prev_line !~ s:rule_special + if getline(v:lnum) =~ s:rule_rx && prev_line !~ s:rule_special return 0 else return &ts diff --git a/runtime/indent/testdir/make.in b/runtime/indent/testdir/make.in new file mode 100644 index 00000000000000..e9b2781bb777df --- /dev/null +++ b/runtime/indent/testdir/make.in @@ -0,0 +1,20 @@ +# vim:ft=make +# START_INDENT +.POSIX : +MAKEFLAGS += -rR + +.SUFFIXES: .F .f +FC = f95 +FFLAGS = +CPPFLAGS = + +.PHONY: help +help: +@echo indentation test + +.F.f: +$(FC) $(CPPFLAGS) -E $< > $@ + +.f.o: +$(FC) $(FFLAGS) -c -o $@ $< +# END_INDENT diff --git a/runtime/indent/testdir/make.ok b/runtime/indent/testdir/make.ok new file mode 100644 index 00000000000000..32055400889dd8 --- /dev/null +++ b/runtime/indent/testdir/make.ok @@ -0,0 +1,20 @@ +# vim:ft=make +# START_INDENT +.POSIX : +MAKEFLAGS += -rR + +.SUFFIXES: .F .f +FC = f95 +FFLAGS = +CPPFLAGS = + +.PHONY: help +help: + @echo indentation test + +.F.f: + $(FC) $(CPPFLAGS) -E $< > $@ + +.f.o: + $(FC) $(FFLAGS) -c -o $@ $< +# END_INDENT
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index d913df7e2f1b9f..29f68dbd0205f9 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -1129,6 +1129,13 @@ functions with [[ and ]]. Move around comments with ]" and [". The mappings can be disabled with: > let g:no_vim_maps = 1 +YAML *ft-yaml-plugin* +By default, the YAML filetype plugin enables the following options: > + setlocal shiftwidth=2 softtabstop=2 +To disable this, set the following variable: > + let g:yaml_recommended_style = 0 ZIG *ft-zig-plugin* diff --git a/runtime/ftplugin/yaml.vim b/runtime/ftplugin/yaml.vim index 4e12350c22bf90..12036a86aacb0d 100644 --- a/runtime/ftplugin/yaml.vim +++ b/runtime/ftplugin/yaml.vim @@ -1,7 +1,8 @@ " Vim filetype plugin file " Language: YAML (YAML Ain't Markup Language) " Previous Maintainer: Nikolai Weibull <[email protected]> (inactive) +" Last Change: 2024 Oct 04 if exists("b:did_ftplugin") @@ -16,20 +17,25 @@ let b:undo_ftplugin = "setl com< cms< et< fo<" setlocal comments=:# commentstring=#\ %s expandtab setlocal formatoptions-=t formatoptions+=croql -" rime input method engine uses `*.custom.yaml` as its config files +if get(g:, "yaml_recommended_style",1) + let b:undo_ftplugin ..= " sw< sts<" + setlocal shiftwidth=2 softtabstop=2 +endif +" rime input method engine(https://rime.im/) +" uses `*.custom.yaml` as its config files if expand('%:r:e') ==# 'custom' + " `__include` command in `*.custom.yaml` + " see: https://github.com/rime/home/wiki/Configuration#%E5%8C%85%E5%90%AB + setlocal include=__include:\\s* + let b:undo_ftplugin ..= " inc<" if !exists('current_compiler') compiler rime_deployer - let b:undo_ftplugin ..= "| compiler make" + let b:undo_ftplugin ..= " | compiler make" endif - setlocal include=__include:\\s* - let b:undo_ftplugin ..= " inc<" endif -if !exists("g:yaml_recommended_style") || g:yaml_recommended_style != 0 - let b:undo_ftplugin ..= " sw< sts<" -endif let &cpo = s:cpo_save unlet s:cpo_save diff --git a/runtime/indent/make.vim b/runtime/indent/make.vim index 4d1838b3aa000c..aeea4de741d477 100644 --- a/runtime/indent/make.vim +++ b/runtime/indent/make.vim @@ -3,6 +3,7 @@ " Maintainer: Doug Kearns <[email protected]> " Previous Maintainer: Nikolai Weibull <[email protected]> " Last Change: 2022 Apr 06 +" 2025 Apr 22 by Vim Project: do not indent after special targets #17183 if exists("b:did_indent") @@ -21,6 +22,8 @@ endif let s:comment_rx = '^\s*#' let s:rule_rx = '^[^ \t#:][^#:]*:\{1,2}\%([^=:]\|$\)' +" .PHONY, .DELETE_ON_ERROR, etc +let s:rule_special = '^\.[A-Z_]\+\s*:' let s:continued_rule_rx = '^[^#:]*:\{1,2}\%([^=:]\|$\)' let s:continuation_rx = '\\$' let s:assignment_rx = '^\s*\h\w*\s*[+:?]\==\s*\zs.*\\$' @@ -50,7 +53,7 @@ function GetMakeIndent() if prev_line =~ s:continuation_rx if prev_prev_line =~ s:continuation_rx return indent(prev_lnum) - elseif prev_line =~ s:rule_rx + elseif prev_line =~ s:rule_rx && prev_line !~ s:rule_special return shiftwidth() elseif prev_line =~ s:assignment_rx call cursor(prev_lnum, 1) @@ -81,15 +84,15 @@ function GetMakeIndent() let line = getline(lnum) endwhile let folded_lnum = lnum + 1 - if folded_line =~ s:rule_rx + if folded_line =~ s:rule_rx && prev_line !~ s:rule_special return &ts endif " elseif folded_line =~ s:folded_assignment_rx return indent(folded_lnum) @@ -98,8 +101,8 @@ function GetMakeIndent() " " TODO: ? " return indent(prev_lnum) endif - if getline(v:lnum) =~ s:rule_rx + elseif prev_line =~ s:rule_rx && prev_line !~ s:rule_special + if getline(v:lnum) =~ s:rule_rx && prev_line !~ s:rule_special return 0 return &ts diff --git a/runtime/indent/testdir/make.in b/runtime/indent/testdir/make.in index 00000000000000..e9b2781bb777df +++ b/runtime/indent/testdir/make.in +@echo indentation test +$(FC) $(CPPFLAGS) -E $< > $@ +$(FC) $(FFLAGS) -c -o $@ $< diff --git a/runtime/indent/testdir/make.ok b/runtime/indent/testdir/make.ok index 00000000000000..32055400889dd8 +++ b/runtime/indent/testdir/make.ok + @echo indentation test + $(FC) $(CPPFLAGS) -E $< > $@ + $(FC) $(FFLAGS) -c -o $@ $<
[ "-\" Last Change: 2024 Oct 04", "+\" 2025 Apr 22 by Vim project re-order b:undo_ftplugin (#17179)", "- setlocal shiftwidth=2 softtabstop=2", "- elseif prev_line =~ s:rule_rx" ]
[ 26, 28, 61, 119 ]
{ "additions": 71, "author": "clason", "deletions": 15, "html_url": "https://github.com/neovim/neovim/pull/33583", "issue_id": 33583, "merged_at": "2025-04-23T06:37:36Z", "omission_probability": 0.1, "pr_number": 33583, "repo": "neovim/neovim", "title": "vim-patch: update runtime files", "total_changes": 86 }
363
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 1246b2fc5ce410..d795dd2aa74cf2 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -1050,9 +1050,10 @@ int autocmd_register(int64_t id, event_T event, const char *pat, int patlen, int get_mode(last_mode); } - // If the event is CursorMoved, update the last cursor position + // If the event is CursorMoved or CursorMovedI, update the last cursor position // position to avoid immediately triggering the autocommand - if (event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) { + if ((event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) + || (event == EVENT_CURSORMOVEDI && !has_event(EVENT_CURSORMOVEDI))) { last_cursormoved_win = curwin; last_cursormoved = curwin->w_cursor; } diff --git a/test/functional/autocmd/cursormoved_spec.lua b/test/functional/autocmd/cursormoved_spec.lua index 2cf02e00f3c452..7cc3a26bfb8418 100644 --- a/test/functional/autocmd/cursormoved_spec.lua +++ b/test/functional/autocmd/cursormoved_spec.lua @@ -7,6 +7,7 @@ local eval = n.eval local api = n.api local source = n.source local command = n.command +local feed = n.feed describe('CursorMoved', function() before_each(clear) @@ -49,11 +50,34 @@ describe('CursorMoved', function() end) it('is not triggered by cursor movement prior to first CursorMoved instantiation', function() + eq({}, api.nvim_get_autocmds({ event = 'CursorMoved' })) + feed('ifoobar<Esc>') source([[ let g:cursormoved = 0 - autocmd! CursorMoved autocmd CursorMoved * let g:cursormoved += 1 ]]) eq(0, eval('g:cursormoved')) + feed('<Ignore>') + eq(0, eval('g:cursormoved')) + feed('0') + eq(1, eval('g:cursormoved')) + end) +end) + +describe('CursorMovedI', function() + before_each(clear) + + it('is not triggered by cursor movement prior to first CursorMovedI instantiation', function() + eq({}, api.nvim_get_autocmds({ event = 'CursorMovedI' })) + feed('ifoobar') + source([[ + let g:cursormovedi = 0 + autocmd CursorMovedI * let g:cursormovedi += 1 + ]]) + eq(0, eval('g:cursormovedi')) + feed('<Ignore>') + eq(0, eval('g:cursormovedi')) + feed('<Home>') + eq(1, eval('g:cursormovedi')) end) end)
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 1246b2fc5ce410..d795dd2aa74cf2 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -1050,9 +1050,10 @@ int autocmd_register(int64_t id, event_T event, const char *pat, int patlen, int get_mode(last_mode); - // If the event is CursorMoved, update the last cursor position + // If the event is CursorMoved or CursorMovedI, update the last cursor position // position to avoid immediately triggering the autocommand - if (event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) { + if ((event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) + || (event == EVENT_CURSORMOVEDI && !has_event(EVENT_CURSORMOVEDI))) { last_cursormoved_win = curwin; last_cursormoved = curwin->w_cursor; diff --git a/test/functional/autocmd/cursormoved_spec.lua b/test/functional/autocmd/cursormoved_spec.lua index 2cf02e00f3c452..7cc3a26bfb8418 100644 --- a/test/functional/autocmd/cursormoved_spec.lua +++ b/test/functional/autocmd/cursormoved_spec.lua @@ -7,6 +7,7 @@ local eval = n.eval local api = n.api local source = n.source local command = n.command +local feed = n.feed describe('CursorMoved', function() before_each(clear) @@ -49,11 +50,34 @@ describe('CursorMoved', function() it('is not triggered by cursor movement prior to first CursorMoved instantiation', function() + eq({}, api.nvim_get_autocmds({ event = 'CursorMoved' })) + feed('ifoobar<Esc>') source([[ let g:cursormoved = 0 - autocmd! CursorMoved autocmd CursorMoved * let g:cursormoved += 1 ]]) eq(0, eval('g:cursormoved')) + eq(0, eval('g:cursormoved')) + feed('0') +end) +describe('CursorMovedI', function() + before_each(clear) + eq({}, api.nvim_get_autocmds({ event = 'CursorMovedI' })) + feed('ifoobar') + source([[ + let g:cursormovedi = 0 + autocmd CursorMovedI * let g:cursormovedi += 1 + ]]) + feed('<Home>') + eq(1, eval('g:cursormovedi')) end)
[ "+ eq(1, eval('g:cursormoved'))", "+ end)", "+ it('is not triggered by cursor movement prior to first CursorMovedI instantiation', function()" ]
[ 44, 45, 51 ]
{ "additions": 28, "author": "neovim-backports[bot]", "deletions": 3, "html_url": "https://github.com/neovim/neovim/pull/33590", "issue_id": 33590, "merged_at": "2025-04-23T03:47:35Z", "omission_probability": 0.1, "pr_number": 33590, "repo": "neovim/neovim", "title": "fix(events): avoid superfluous CursorMovedI on first autocmd", "total_changes": 31 }
364
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 1246b2fc5ce410..d795dd2aa74cf2 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -1050,9 +1050,10 @@ int autocmd_register(int64_t id, event_T event, const char *pat, int patlen, int get_mode(last_mode); } - // If the event is CursorMoved, update the last cursor position + // If the event is CursorMoved or CursorMovedI, update the last cursor position // position to avoid immediately triggering the autocommand - if (event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) { + if ((event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) + || (event == EVENT_CURSORMOVEDI && !has_event(EVENT_CURSORMOVEDI))) { last_cursormoved_win = curwin; last_cursormoved = curwin->w_cursor; } diff --git a/test/functional/autocmd/cursormoved_spec.lua b/test/functional/autocmd/cursormoved_spec.lua index 2cf02e00f3c452..7cc3a26bfb8418 100644 --- a/test/functional/autocmd/cursormoved_spec.lua +++ b/test/functional/autocmd/cursormoved_spec.lua @@ -7,6 +7,7 @@ local eval = n.eval local api = n.api local source = n.source local command = n.command +local feed = n.feed describe('CursorMoved', function() before_each(clear) @@ -49,11 +50,34 @@ describe('CursorMoved', function() end) it('is not triggered by cursor movement prior to first CursorMoved instantiation', function() + eq({}, api.nvim_get_autocmds({ event = 'CursorMoved' })) + feed('ifoobar<Esc>') source([[ let g:cursormoved = 0 - autocmd! CursorMoved autocmd CursorMoved * let g:cursormoved += 1 ]]) eq(0, eval('g:cursormoved')) + feed('<Ignore>') + eq(0, eval('g:cursormoved')) + feed('0') + eq(1, eval('g:cursormoved')) + end) +end) + +describe('CursorMovedI', function() + before_each(clear) + + it('is not triggered by cursor movement prior to first CursorMovedI instantiation', function() + eq({}, api.nvim_get_autocmds({ event = 'CursorMovedI' })) + feed('ifoobar') + source([[ + let g:cursormovedi = 0 + autocmd CursorMovedI * let g:cursormovedi += 1 + ]]) + eq(0, eval('g:cursormovedi')) + feed('<Ignore>') + eq(0, eval('g:cursormovedi')) + feed('<Home>') + eq(1, eval('g:cursormovedi')) end) end)
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c index 1246b2fc5ce410..d795dd2aa74cf2 100644 --- a/src/nvim/autocmd.c +++ b/src/nvim/autocmd.c @@ -1050,9 +1050,10 @@ int autocmd_register(int64_t id, event_T event, const char *pat, int patlen, int get_mode(last_mode); - // If the event is CursorMoved, update the last cursor position + // If the event is CursorMoved or CursorMovedI, update the last cursor position // position to avoid immediately triggering the autocommand - if (event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) { + if ((event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) + || (event == EVENT_CURSORMOVEDI && !has_event(EVENT_CURSORMOVEDI))) { last_cursormoved_win = curwin; last_cursormoved = curwin->w_cursor; diff --git a/test/functional/autocmd/cursormoved_spec.lua b/test/functional/autocmd/cursormoved_spec.lua index 2cf02e00f3c452..7cc3a26bfb8418 100644 --- a/test/functional/autocmd/cursormoved_spec.lua +++ b/test/functional/autocmd/cursormoved_spec.lua @@ -7,6 +7,7 @@ local eval = n.eval local api = n.api local source = n.source local command = n.command +local feed = n.feed describe('CursorMoved', function() before_each(clear) @@ -49,11 +50,34 @@ describe('CursorMoved', function() it('is not triggered by cursor movement prior to first CursorMoved instantiation', function() + eq({}, api.nvim_get_autocmds({ event = 'CursorMoved' })) + feed('ifoobar<Esc>') source([[ let g:cursormoved = 0 - autocmd! CursorMoved autocmd CursorMoved * let g:cursormoved += 1 ]]) eq(0, eval('g:cursormoved')) + eq(0, eval('g:cursormoved')) + feed('0') + end) +end) +describe('CursorMovedI', function() + before_each(clear) + feed('ifoobar') + source([[ + let g:cursormovedi = 0 + autocmd CursorMovedI * let g:cursormovedi += 1 + ]]) + feed('<Home>') + eq(1, eval('g:cursormovedi')) end)
[ "+ eq(1, eval('g:cursormoved'))", "+ it('is not triggered by cursor movement prior to first CursorMovedI instantiation', function()", "+ eq({}, api.nvim_get_autocmds({ event = 'CursorMovedI' }))" ]
[ 44, 51, 52 ]
{ "additions": 28, "author": "zeertzjq", "deletions": 3, "html_url": "https://github.com/neovim/neovim/pull/33588", "issue_id": 33588, "merged_at": "2025-04-23T03:20:21Z", "omission_probability": 0.1, "pr_number": 33588, "repo": "neovim/neovim", "title": "fix(events): avoid superfluous CursorMovedI on first autocmd", "total_changes": 31 }
365
diff --git a/runtime/syntax/vim.vim b/runtime/syntax/vim.vim index fdf2b425ac9249..53a2dd7a2f5fa9 100644 --- a/runtime/syntax/vim.vim +++ b/runtime/syntax/vim.vim @@ -73,8 +73,13 @@ syn match vimOptionVarName contained "t_k;" syn keyword vimErrSetting contained akm altkeymap anti antialias ap autoprint bf beautify biosk bioskey consk conskey fk fkmap fl flash gr graphic ht hardtabs macatsui mesg novice open opt optimize oft osfiletype redraw slow slowopen sourceany w1200 w300 w9600 syn keyword vimErrSetting contained noakm noaltkeymap noanti noantialias noap noautoprint nobf nobeautify nobiosk nobioskey noconsk noconskey nofk nofkmap nofl noflash nogr nographic nomacatsui nomesg nonovice noopen noopt nooptimize noredraw noslow noslowopen nosourceany syn keyword vimErrSetting contained invakm invaltkeymap invanti invantialias invap invautoprint invbf invbeautify invbiosk invbioskey invconsk invconskey invfk invfkmap invfl invflash invgr invgraphic invmacatsui invmesg invnovice invopen invopt invoptimize invredraw invslow invslowopen invsourceany -"}}}2 + + " AutoCmd Events {{{2 syn case ignore + +syn keyword vimAutoEvent contained User skipwhite nextgroup=vimUserAutoEvent +syn match vimUserAutoEvent contained "\<\h\w*\>" skipwhite nextgroup=vimAutoEventSep,@vimAutocmdPattern + " Highlight commonly used Groupnames {{{2 syn keyword vimGroup contained Comment Constant String Character Number Boolean Float Identifier Function Statement Conditional Repeat Label Operator Keyword Exception PreProc Include Define Macro PreCondit Type StorageClass Structure Typedef Special SpecialChar Tag Delimiter SpecialComment Debug Underlined Ignore Error Todo @@ -214,7 +219,7 @@ syn match vimNumber '\<0z\%(\x\x\)\+\%(\.\%(\x\x\)\+\)*' skipwhite nextgroup=vim syn case match " All vimCommands are contained by vimIsCommand. {{{2 -syn cluster vimCmdList contains=vimAbb,vimAddress,vimAutoCmd,vimAugroup,vimBehave,vimCall,vimCatch,vimConst,vimDebuggreedy,vimDef,vimDefFold,vimDelcommand,@vimEcho,vimEnddef,vimEndfunction,vimExecute,vimIsCommand,vimExtCmd,vimExFilter,vimFor,vimFunction,vimFuncFold,vimGrep,vimGrepAdd,vimGlobal,vimHelpgrep,vimHighlight,vimLet,vimLoadkeymap,vimLockvar,vimMake,vimMap,vimMark,vimMatch,vimNotFunc,vimNormal,vimRedir,vimSet,vimSleep,vimSort,vimSyntax,vimThrow,vimUnlet,vimUnlockvar,vimUnmap,vimUserCmd,vimVimgrep,vimVimgrepadd,vimMenu,vimMenutranslate,@vim9CmdList,@vimExUserCmdList +syn cluster vimCmdList contains=vimAbb,vimAddress,vimAutocmd,vimAugroup,vimBehave,vimCall,vimCatch,vimConst,vimDoautocmd,vimDebuggreedy,vimDef,vimDefFold,vimDelcommand,@vimEcho,vimEnddef,vimEndfunction,vimExecute,vimIsCommand,vimExtCmd,vimExFilter,vimFor,vimFunction,vimFuncFold,vimGrep,vimGrepAdd,vimGlobal,vimHelpgrep,vimHighlight,vimLet,vimLoadkeymap,vimLockvar,vimMake,vimMap,vimMark,vimMatch,vimNotFunc,vimNormal,vimRedir,vimSet,vimSleep,vimSort,vimSyntax,vimThrow,vimUnlet,vimUnlockvar,vimUnmap,vimUserCmd,vimVimgrep,vimVimgrepadd,vimMenu,vimMenutranslate,@vim9CmdList,@vimExUserCmdList syn cluster vim9CmdList contains=vim9Abstract,vim9Class,vim9Const,vim9Enum,vim9Export,vim9Final,vim9For,vim9Interface,vim9Type,vim9Var syn match vimCmdSep "\\\@1<!|" skipwhite nextgroup=@vimCmdList,vimSubst1,vimFunc syn match vimCmdSep ":\+" skipwhite nextgroup=@vimCmdList,vimSubst1 @@ -303,21 +308,32 @@ syn keyword vimFTOption contained detect indent off on plugin " Augroup : vimAugroupError removed because long augroups caused sync'ing problems. {{{2 " ======= : Trade-off: Increasing synclines with slower editing vs augroup END error checking. syn cluster vimAugroupList contains=@vimCmdList,vimFilter,vimFunc,vimLineComment,vimSpecFile,vimOper,vimNumber,vimOperParen,@vimComment,vimString,vimSubst,vimRegister,vimCmplxRepeat,vimNotation,vimCtrlChar,vimContinue -syn match vimAugroup "\<aug\%[roup]\>" contains=vimAugroupKey,vimAugroupBang skipwhite nextgroup=vimAugroupBang,vimAutoCmdGroup -if exists("g:vimsyn_folding") && g:vimsyn_folding =~# 'a' - syn region vimAugroup fold start="\<aug\%[roup]\>\ze\s\+\%([eE][nN][dD]\)\@!\S\+" matchgroup=vimAugroupKey end="\<aug\%[roup]\>\ze\s\+[eE][nN][dD]\>" contains=vimAutoCmd,@vimAugroupList,vimAugroupkey skipwhite nextgroup=vimAugroupEnd -else - syn region vimAugroup start="\<aug\%[roup]\>\ze\s\+\%([eE][nN][dD]\)\@!\S\+" matchgroup=vimAugroupKey end="\<aug\%[roup]\>\ze\s\+[eE][nN][dD]\>" contains=vimAutoCmd,@vimAugroupList,vimAugroupkey skipwhite nextgroup=vimAugroupEnd -endif + +" define +VimFolda syn region vimAugroup + \ start="\<aug\%[roup]\>\ze\s\+\%([eE][nN][dD]\)\@!\S\+" + \ matchgroup=vimAugroupKey + \ end="\<aug\%[roup]\>\ze\s\+[eE][nN][dD]\>" + \ skipwhite nextgroup=vimAugroupEnd + \ contains=vimAutocmd,@vimAugroupList,vimAugroupkey if !exists("g:vimsyn_noerror") && !exists("g:vimsyn_noaugrouperror") - syn match vimAugroupError "\<aug\%[roup]\>\s\+[eE][nN][dD]\>" + syn match vimAugroupError "\<aug\%[roup]\>\s\+[eE][nN][dD]\>" endif -syn match vimAutoCmdGroup contained "\S\+" -syn match vimAugroupEnd contained "\c\<END\>" -syn match vimAugroupBang contained "\a\@1<=!" skipwhite nextgroup=vimAutoCmdGroup -syn keyword vimAugroupKey contained aug[roup] skipwhite nextgroup=vimAugroupBang,vimAutoCmdGroup,vimAugroupEnd +" TODO: Vim9 comment +syn match vimAugroupName contained "\%(\\["|[:space:]]\|[^"|[:space:]]\)\+" +syn match vimAugroupEnd contained "\c\<END\>" +syn match vimAugroupBang contained "\a\@1<=!" skipwhite nextgroup=vimAugroupName +syn keyword vimAugroupKey contained aug[roup] skipwhite nextgroup=vimAugroupBang,vimAugroupName,vimAugroupEnd + +" remove +syn match vimAugroup "\<aug\%[roup]!" skipwhite nextgroup=vimAugroupName contains=vimAugroupKey,vimAugroupBang + +" list +VimL syn match vimAugroup "\<aug\%[roup]\>\ze\s*\%(["|]\|$\)" skipwhite nextgroup=vimCmdSep,vimComment contains=vimAugroupKey +Vim9 syn match vimAugroup "\<aug\%[roup]\>\ze\s*\%([#|]\|$\)" skipwhite nextgroup=vimCmdSep,vim9Comment contains=vimAugroupKey +" hi def link vimAugroupEnd Special " Operators: {{{2 " ========= syn cluster vimOperGroup contains=@vimContinue,@vimExprList,vim9Comment @@ -876,16 +892,83 @@ syn keyword vimAbb ab[breviate] ca[bbrev] cnorea[bbrev] cuna[bbrev] ia[bbrev] in " GEN_SYN_VIM: vimCommand abclear, START_STR='syn keyword vimAbb', END_STR='skipwhite nextgroup=vimMapMod' syn keyword vimAbb abc[lear] cabc[lear] iabc[lear] skipwhite nextgroup=vimMapMod -" Autocmd: {{{2 -" ======= -syn match vimAutoCmdBang contained "\a\@1<=!" skipwhite nextgroup=vimAutoEventList -syn match vimAutoEventList contained "\%(\a\+,\)*\a\+" contains=vimAutoEvent,nvimAutoEvent nextgroup=vimAutoCmdSpace -syn match vimAutoCmdSpace contained "\s\+" nextgroup=vimAutoCmdSfxList -syn match vimAutoCmdSfxList contained "\S*" skipwhite nextgroup=vimAutoCmdMod,vimAutoCmdBlock -syn keyword vimAutoCmd au[tocmd] skipwhite nextgroup=vimAutoCmdBang,vimAutoEventList -syn keyword vimAutoCmd do[autocmd] doautoa[ll] skipwhite nextgroup=vimAutoEventList -syn match vimAutoCmdMod "\(++\)\=\(once\|nested\)" skipwhite nextgroup=vimAutoCmdBlock -syn region vimAutoCmdBlock contained matchgroup=vimSep start="{" end="^\s*\zs}" contains=@vimDefBodyList +" Filename Patterns: {{{2 +" ================= + +syn match vimWildcardQuestion contained "?" +syn match vimWildcardStar contained "*" + +syn match vimWildcardBraceComma contained "," +syn region vimWildcardBrace contained + \ matchgroup=vimWildcard + \ start="{" + \ end="}" + \ contains=vimWildcardEscape,vimWildcardBrace,vimWildcardBraceComma,vimWildcardQuestion,vimWildcardStar,vimWildcardBracket + \ oneline + +syn match vimWildcardIntervalNumber contained "\d\+" +syn match vimWildcardInterval contained "\\\\\\{\d\+\%(,\d\+\)\=\\}" contains=vimWildcardIntervalNumber + + +syn match vimWildcardBracket contained "\[\%(\^\=]\=\%(\\.\|\[\([:.=]\)[^:.=]\+\1]\|[^][:space:]]\)*\)\@>]" + \ contains=vimWildcardBracketStart,vimWildcardEscape + +syn match vimWildcardBracketCharacter contained "." nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketHyphen,vimWildcardBracketEnd +syn match vimWildcardBracketRightBracket contained "]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketHyphen contained "-]\@!" nextgroup=@vimWildcardBracketCharacter +syn match vimWildcardBracketEscape contained "\\." nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketHyphen,vimWildcardBracketEnd +syn match vimWildcardBracketCharacterClass contained "\[:[^:]\+:]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketEquivalenceClass contained "\[=[^=]\+=]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketCollatingSymbol contained "\[\.[^.]\+\.]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd + +syn match vimWildcardBracketStart contained "\[" nextgroup=vimWildcardBracketCaret,vimWildcardBracketRightBracket,@vimWildcardBracketCharacter +syn match vimWildcardBracketCaret contained "\^" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketRightBracket +syn match vimWildcardBracketEnd contained "]" + +syn cluster vimWildcardBracketCharacter contains=vimWildcardBracketCharacter,vimWildcardBracketEscape,vimWildcardBracketCharacterClass,vimWildcardBracketEquivalenceClass,vimWildcardBracketCollatingSymbol + +syn match vimWildcardEscape contained "\\." + +syn cluster vimWildcard contains=vimWildcardQuestion,vimWildcardStar,vimWildcardBrace,vimWildcardBracket,vimWildcardInterval + +" Autocmd and Doauto{cmd,all}: {{{2 +" =========================== + +" TODO: explicitly match the {cmd} arg rather than bailing out to TOP +syn region vimAutocmdBlock contained matchgroup=vimSep start="{" end="^\s*\zs}" contains=@vimDefBodyList + +syn match vimAutocmdGroup contained "\%(\\["|[:space:]]\|[^"|[:space:]]\)\+" skipwhite nextgroup=vimAutoEvent,nvimAutoEvent,vimAutoEventGlob +syn match vimAutocmdBang contained "\a\@1<=!" skipwhite nextgroup=vimAutocmdGroup,vimAutoEvent,nvimAutoEvent,vimAutoEventGlob + +" TODO: cleaner handling of | in pattern position +" : match pattern items in addition to wildcards +syn region vimAutocmdPattern contained + \ start="|\@!\S" + \ skip="\\\\\|\\[,[:space:]]" + \ end="\ze[,[:space:]]" + \ end="$" + \ skipwhite nextgroup=vimAutocmdPatternSep,vimAutocmdMod,vimAutocmdBlock + \ contains=vimEnvvar,@vimWildcard,vimAutocmdPatternEscape +syn match vimAutocmdBufferPattern contained "<buffer\%(=\%(\d\+\|abuf\)\)\=>" skipwhite nextgroup=vimAutocmdPatternSep,vimAutocmdMod,vimAutocmdBlock +" trailing pattern separator comma allowed +syn match vimAutocmdPatternSep contained "," skipwhite nextgroup=@vimAutocmdPattern,vimAutocmdMod,vimAutocmdBlock +syn match vimAutocmdPatternEscape contained "\\." +syn cluster vimAutocmdPattern contains=vimAutocmdPattern,vimAutocmdBufferPattern + +" TODO: Vim9 requires '++' prefix +syn match vimAutocmdMod contained "\%(++\)\=\<nested\>" skipwhite nextgroup=vimAutocmdMod,vimAutocmdBlock +syn match vimAutocmdMod contained "++once\>" skipwhite nextgroup=vimAutocmdMod,vimAutocmdBlock + +" higher priority than vimAutocmdGroup, assume no group is so named +syn match vimAutoEventGlob contained "*" skipwhite nextgroup=@vimAutocmdPattern +syn match vimAutoEventSep contained "\a\@1<=," nextgroup=vimAutoEvent,nvimAutoEvent + +syn match vimAutocmd "\<au\%[tocmd]\>" skipwhite nextgroup=vimAutocmdBang,vimAutocmdGroup,vimAutoEvent,nvimAutoEvent,vimAutoEventGlob + + +syn match vimDoautocmdMod contained "<nomodeline>" skipwhite nextgroup=vimAutocmdGroup,vimAutoEvent,nvimAutoEvent +syn match vimDoautocmd "\<do\%[autocmd]\>" skipwhite nextgroup=vimDoautocmdMod,vimAutocmdGroup,vimAutoEvent,nvimAutoEvent +syn match vimDoautocmd "\<doautoa\%[ll]\>" skipwhite nextgroup=vimDoautocmdMod,vimAutocmdGroup,vimAutoEvent,nvimAutoEvent " Echo And Execute: -- prefer strings! {{{2 " ================ @@ -1645,10 +1728,14 @@ if !exists("skip_vim_syntax_inits") hi def link vimAugroupBang vimBang hi def link vimAugroupError vimError hi def link vimAugroupKey vimCommand - hi def link vimAutoCmd vimCommand - hi def link vimAutoCmdBang vimBang + hi def link vimAutocmd vimCommand + hi def link vimAutocmdBang vimBang + hi def link vimAutocmdPatternEscape Special hi def link vimAutoEvent Type - hi def link vimAutoCmdMod Special + hi def link vimAutoEventGlob Type + hi def link vimAutocmdBufferPattern Special + hi def link vimAutocmdMod Special + hi def link vimAutocmdPatternSep vimSep hi def link vimBang vimOper hi def link vimBehaveBang vimBang hi def link vimBehaveModel vimBehave @@ -1674,6 +1761,8 @@ if !exists("skip_vim_syntax_inits") hi def link vimDefParam vimVar hi def link vimDelcommand vimCommand hi def link vimDelcommandAttr vimUserCmdAttr + hi def link vimDoautocmd vimCommand + hi def link vimDoautocmdMod Special hi def link vimEcho vimCommand hi def link vimEchohlNone vimGroup hi def link vimEchohl vimCommand @@ -1890,6 +1979,24 @@ if !exists("skip_vim_syntax_inits") hi def link vimVimVar Identifier hi def link vimVimVarName Identifier hi def link vimWarn WarningMsg + hi def link vimWildcard Special + hi def link vimWildcardBraceComma vimWildcard + hi def link vimWildcardBracket vimWildcard + hi def link vimWildcardBracketCaret vimWildcard + hi def link vimWildcardBracketCharacter Normal + hi def link vimWildcardBracketCharacter Normal + hi def link vimWildcardBracketCharacterClass vimWildCard + hi def link vimWildcardBracketCollatingSymbol vimWildCard + hi def link vimWildcardBracketEnd vimWildcard + hi def link vimWildcardBracketEquivalenceClass vimWildCard + hi def link vimWildcardBracketEscape vimWildcard + hi def link vimWildcardBracketHyphen vimWildcard + hi def link vimWildcardBracketRightBracket vimWildcardBracketCharacter + hi def link vimWildcardBracketStart vimWildcard + hi def link vimWildcardEscape vimWildcard + hi def link vimWildcardInterval vimWildcard + hi def link vimWildcardQuestion vimWildcard + hi def link vimWildcardStar vimWildcard hi def link vim9Abstract vimCommand hi def link vim9Boolean Boolean diff --git a/src/gen/gen_vimvim.lua b/src/gen/gen_vimvim.lua index 3de09425134d7b..4cd88f0188489c 100644 --- a/src/gen/gen_vimvim.lua +++ b/src/gen/gen_vimvim.lua @@ -40,7 +40,7 @@ local function cmd_kw(prev_cmd, cmd) end -- Exclude these from the vimCommand keyword list, they are handled specially --- in syntax/vim.vim (vimAugroupKey, vimAutoCmd, vimGlobal, vimSubst). #9327 +-- in syntax/vim.vim (vimAugroupKey, vimAutocmd, vimGlobal, vimSubst). #9327 local function is_special_cased_cmd(cmd) return ( cmd == 'augroup' @@ -122,26 +122,32 @@ end w('\n\nsyn case ignore') local vimau_start = 'syn keyword vimAutoEvent contained ' +local vimau_end = ' skipwhite nextgroup=vimAutoEventSep,@vimAutocmdPattern' w('\n\n' .. vimau_start) for au, _ in vim.spairs(vim.tbl_extend('error', auevents.events, auevents.aliases)) do - if not auevents.nvim_specific[au] then + -- "User" requires a user defined argument event. + -- (Separately specified in vim.vim). + if au ~= 'User' and not auevents.nvim_specific[au] then if lld.line_length > 850 then - w('\n' .. vimau_start) + w(vimau_end .. '\n' .. vimau_start) end w(' ' .. au) end end +w(vimau_end .. '\n') local nvimau_start = 'syn keyword nvimAutoEvent contained ' -w('\n\n' .. nvimau_start) +local nvimau_end = vimau_end +w('\n' .. nvimau_start) for au, _ in vim.spairs(auevents.nvim_specific) do if lld.line_length > 850 then - w('\n' .. nvimau_start) + w(nvimau_end .. '\n' .. nvimau_start) end w(' ' .. au) end +w(nvimau_end .. '\n') -w('\n\nsyn case match') +w('\nsyn case match') local vimfun_start = 'syn keyword vimFuncName contained ' w('\n\n' .. vimfun_start) local funcs = mpack.decode(io.open(funcs_file, 'rb'):read('*all'))
diff --git a/runtime/syntax/vim.vim b/runtime/syntax/vim.vim index fdf2b425ac9249..53a2dd7a2f5fa9 100644 --- a/runtime/syntax/vim.vim +++ b/runtime/syntax/vim.vim @@ -73,8 +73,13 @@ syn match vimOptionVarName contained "t_k;" syn keyword vimErrSetting contained akm altkeymap anti antialias ap autoprint bf beautify biosk bioskey consk conskey fk fkmap fl flash gr graphic ht hardtabs macatsui mesg novice open opt optimize oft osfiletype redraw slow slowopen sourceany w1200 w300 w9600 syn keyword vimErrSetting contained noakm noaltkeymap noanti noantialias noap noautoprint nobf nobeautify nobiosk nobioskey noconsk noconskey nofk nofkmap nofl noflash nogr nographic nomacatsui nomesg nonovice noopen noopt nooptimize noredraw noslow noslowopen nosourceany syn keyword vimErrSetting contained invakm invaltkeymap invanti invantialias invap invautoprint invbf invbeautify invbiosk invbioskey invconsk invconskey invfk invfkmap invfl invflash invgr invgraphic invmacatsui invmesg invnovice invopen invopt invoptimize invredraw invslow invslowopen invsourceany -"}}}2 + " AutoCmd Events {{{2 syn case ignore +syn keyword vimAutoEvent contained User skipwhite nextgroup=vimUserAutoEvent +syn match vimUserAutoEvent contained "\<\h\w*\>" skipwhite nextgroup=vimAutoEventSep,@vimAutocmdPattern " Highlight commonly used Groupnames {{{2 syn keyword vimGroup contained Comment Constant String Character Number Boolean Float Identifier Function Statement Conditional Repeat Label Operator Keyword Exception PreProc Include Define Macro PreCondit Type StorageClass Structure Typedef Special SpecialChar Tag Delimiter SpecialComment Debug Underlined Ignore Error Todo @@ -214,7 +219,7 @@ syn match vimNumber '\<0z\%(\x\x\)\+\%(\.\%(\x\x\)\+\)*' skipwhite nextgroup=vim syn case match " All vimCommands are contained by vimIsCommand. {{{2 -syn cluster vimCmdList contains=vimAbb,vimAddress,vimAutoCmd,vimAugroup,vimBehave,vimCall,vimCatch,vimConst,vimDebuggreedy,vimDef,vimDefFold,vimDelcommand,@vimEcho,vimEnddef,vimEndfunction,vimExecute,vimIsCommand,vimExtCmd,vimExFilter,vimFor,vimFunction,vimFuncFold,vimGrep,vimGrepAdd,vimGlobal,vimHelpgrep,vimHighlight,vimLet,vimLoadkeymap,vimLockvar,vimMake,vimMap,vimMark,vimMatch,vimNotFunc,vimNormal,vimRedir,vimSet,vimSleep,vimSort,vimSyntax,vimThrow,vimUnlet,vimUnlockvar,vimUnmap,vimUserCmd,vimVimgrep,vimVimgrepadd,vimMenu,vimMenutranslate,@vim9CmdList,@vimExUserCmdList +syn cluster vimCmdList contains=vimAbb,vimAddress,vimAutocmd,vimAugroup,vimBehave,vimCall,vimCatch,vimConst,vimDoautocmd,vimDebuggreedy,vimDef,vimDefFold,vimDelcommand,@vimEcho,vimEnddef,vimEndfunction,vimExecute,vimIsCommand,vimExtCmd,vimExFilter,vimFor,vimFunction,vimFuncFold,vimGrep,vimGrepAdd,vimGlobal,vimHelpgrep,vimHighlight,vimLet,vimLoadkeymap,vimLockvar,vimMake,vimMap,vimMark,vimMatch,vimNotFunc,vimNormal,vimRedir,vimSet,vimSleep,vimSort,vimSyntax,vimThrow,vimUnlet,vimUnlockvar,vimUnmap,vimUserCmd,vimVimgrep,vimVimgrepadd,vimMenu,vimMenutranslate,@vim9CmdList,@vimExUserCmdList syn cluster vim9CmdList contains=vim9Abstract,vim9Class,vim9Const,vim9Enum,vim9Export,vim9Final,vim9For,vim9Interface,vim9Type,vim9Var syn match vimCmdSep "\\\@1<!|" skipwhite nextgroup=@vimCmdList,vimSubst1,vimFunc syn match vimCmdSep ":\+" skipwhite nextgroup=@vimCmdList,vimSubst1 @@ -303,21 +308,32 @@ syn keyword vimFTOption contained detect indent off on plugin " Augroup : vimAugroupError removed because long augroups caused sync'ing problems. {{{2 " ======= : Trade-off: Increasing synclines with slower editing vs augroup END error checking. syn cluster vimAugroupList contains=@vimCmdList,vimFilter,vimFunc,vimLineComment,vimSpecFile,vimOper,vimNumber,vimOperParen,@vimComment,vimString,vimSubst,vimRegister,vimCmplxRepeat,vimNotation,vimCtrlChar,vimContinue -syn match vimAugroup "\<aug\%[roup]\>" contains=vimAugroupKey,vimAugroupBang skipwhite nextgroup=vimAugroupBang,vimAutoCmdGroup -if exists("g:vimsyn_folding") && g:vimsyn_folding =~# 'a' - syn region vimAugroup fold start="\<aug\%[roup]\>\ze\s\+\%([eE][nN][dD]\)\@!\S\+" matchgroup=vimAugroupKey end="\<aug\%[roup]\>\ze\s\+[eE][nN][dD]\>" contains=vimAutoCmd,@vimAugroupList,vimAugroupkey skipwhite nextgroup=vimAugroupEnd -endif +" define +VimFolda syn region vimAugroup + \ start="\<aug\%[roup]\>\ze\s\+\%([eE][nN][dD]\)\@!\S\+" + \ matchgroup=vimAugroupKey + \ skipwhite nextgroup=vimAugroupEnd + \ contains=vimAutocmd,@vimAugroupList,vimAugroupkey if !exists("g:vimsyn_noerror") && !exists("g:vimsyn_noaugrouperror") + syn match vimAugroupError "\<aug\%[roup]\>\s\+[eE][nN][dD]\>" endif -syn match vimAutoCmdGroup contained "\S\+" -syn match vimAugroupEnd contained "\c\<END\>" -syn match vimAugroupBang contained "\a\@1<=!" skipwhite nextgroup=vimAutoCmdGroup -syn keyword vimAugroupKey contained aug[roup] skipwhite nextgroup=vimAugroupBang,vimAutoCmdGroup,vimAugroupEnd +" TODO: Vim9 comment +syn match vimAugroupName contained "\%(\\["|[:space:]]\|[^"|[:space:]]\)\+" +syn match vimAugroupEnd contained "\c\<END\>" +syn match vimAugroupBang contained "\a\@1<=!" skipwhite nextgroup=vimAugroupName +" remove +syn match vimAugroup "\<aug\%[roup]!" skipwhite nextgroup=vimAugroupName contains=vimAugroupKey,vimAugroupBang +" list +VimL syn match vimAugroup "\<aug\%[roup]\>\ze\s*\%(["|]\|$\)" skipwhite nextgroup=vimCmdSep,vimComment contains=vimAugroupKey +Vim9 syn match vimAugroup "\<aug\%[roup]\>\ze\s*\%([#|]\|$\)" skipwhite nextgroup=vimCmdSep,vim9Comment contains=vimAugroupKey +" hi def link vimAugroupEnd Special " Operators: {{{2 " ========= syn cluster vimOperGroup contains=@vimContinue,@vimExprList,vim9Comment @@ -876,16 +892,83 @@ syn keyword vimAbb ab[breviate] ca[bbrev] cnorea[bbrev] cuna[bbrev] ia[bbrev] in " GEN_SYN_VIM: vimCommand abclear, START_STR='syn keyword vimAbb', END_STR='skipwhite nextgroup=vimMapMod' syn keyword vimAbb abc[lear] cabc[lear] iabc[lear] skipwhite nextgroup=vimMapMod -" ======= -syn match vimAutoCmdBang contained "\a\@1<=!" skipwhite nextgroup=vimAutoEventList -syn match vimAutoEventList contained "\%(\a\+,\)*\a\+" contains=vimAutoEvent,nvimAutoEvent nextgroup=vimAutoCmdSpace -syn match vimAutoCmdSpace contained "\s\+" nextgroup=vimAutoCmdSfxList -syn match vimAutoCmdSfxList contained "\S*" skipwhite nextgroup=vimAutoCmdMod,vimAutoCmdBlock -syn keyword vimAutoCmd au[tocmd] skipwhite nextgroup=vimAutoCmdBang,vimAutoEventList -syn keyword vimAutoCmd do[autocmd] doautoa[ll] skipwhite nextgroup=vimAutoEventList -syn region vimAutoCmdBlock contained matchgroup=vimSep start="{" end="^\s*\zs}" contains=@vimDefBodyList +" Filename Patterns: {{{2 +syn match vimWildcardQuestion contained "?" +syn match vimWildcardStar contained "*" +syn match vimWildcardBraceComma contained "," +syn region vimWildcardBrace contained + \ matchgroup=vimWildcard + \ start="{" + \ end="}" + \ contains=vimWildcardEscape,vimWildcardBrace,vimWildcardBraceComma,vimWildcardQuestion,vimWildcardStar,vimWildcardBracket + \ oneline +syn match vimWildcardIntervalNumber contained "\d\+" +syn match vimWildcardBracket contained "\[\%(\^\=]\=\%(\\.\|\[\([:.=]\)[^:.=]\+\1]\|[^][:space:]]\)*\)\@>]" +syn match vimWildcardBracketCharacter contained "." nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketHyphen,vimWildcardBracketEnd +syn match vimWildcardBracketRightBracket contained "]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketHyphen contained "-]\@!" nextgroup=@vimWildcardBracketCharacter +syn match vimWildcardBracketEscape contained "\\." nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketHyphen,vimWildcardBracketEnd +syn match vimWildcardBracketCharacterClass contained "\[:[^:]\+:]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketEquivalenceClass contained "\[=[^=]\+=]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketCollatingSymbol contained "\[\.[^.]\+\.]" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketEnd +syn match vimWildcardBracketStart contained "\[" nextgroup=vimWildcardBracketCaret,vimWildcardBracketRightBracket,@vimWildcardBracketCharacter +syn match vimWildcardBracketCaret contained "\^" nextgroup=@vimWildcardBracketCharacter,vimWildcardBracketRightBracket +syn cluster vimWildcardBracketCharacter contains=vimWildcardBracketCharacter,vimWildcardBracketEscape,vimWildcardBracketCharacterClass,vimWildcardBracketEquivalenceClass,vimWildcardBracketCollatingSymbol +syn cluster vimWildcard contains=vimWildcardQuestion,vimWildcardStar,vimWildcardBrace,vimWildcardBracket,vimWildcardInterval +" Autocmd and Doauto{cmd,all}: {{{2 +" =========================== +" TODO: explicitly match the {cmd} arg rather than bailing out to TOP +syn region vimAutocmdBlock contained matchgroup=vimSep start="{" end="^\s*\zs}" contains=@vimDefBodyList +syn match vimAutocmdGroup contained "\%(\\["|[:space:]]\|[^"|[:space:]]\)\+" skipwhite nextgroup=vimAutoEvent,nvimAutoEvent,vimAutoEventGlob +syn match vimAutocmdBang contained "\a\@1<=!" skipwhite nextgroup=vimAutocmdGroup,vimAutoEvent,nvimAutoEvent,vimAutoEventGlob +" TODO: cleaner handling of | in pattern position +" : match pattern items in addition to wildcards + \ start="|\@!\S" + \ skip="\\\\\|\\[,[:space:]]" + \ end="\ze[,[:space:]]" + \ end="$" + \ skipwhite nextgroup=vimAutocmdPatternSep,vimAutocmdMod,vimAutocmdBlock + \ contains=vimEnvvar,@vimWildcard,vimAutocmdPatternEscape +" trailing pattern separator comma allowed +syn match vimAutocmdPatternSep contained "," skipwhite nextgroup=@vimAutocmdPattern,vimAutocmdMod,vimAutocmdBlock +syn match vimAutocmdPatternEscape contained "\\." +syn cluster vimAutocmdPattern contains=vimAutocmdPattern,vimAutocmdBufferPattern +" TODO: Vim9 requires '++' prefix +syn match vimAutocmdMod contained "++once\>" skipwhite nextgroup=vimAutocmdMod,vimAutocmdBlock +" higher priority than vimAutocmdGroup, assume no group is so named +syn match vimAutoEventGlob contained "*" skipwhite nextgroup=@vimAutocmdPattern +syn match vimAutoEventSep contained "\a\@1<=," nextgroup=vimAutoEvent,nvimAutoEvent +syn match vimAutocmd "\<au\%[tocmd]\>" skipwhite nextgroup=vimAutocmdBang,vimAutocmdGroup,vimAutoEvent,nvimAutoEvent,vimAutoEventGlob +syn match vimDoautocmdMod contained "<nomodeline>" skipwhite nextgroup=vimAutocmdGroup,vimAutoEvent,nvimAutoEvent +syn match vimDoautocmd "\<do\%[autocmd]\>" skipwhite nextgroup=vimDoautocmdMod,vimAutocmdGroup,vimAutoEvent,nvimAutoEvent +syn match vimDoautocmd "\<doautoa\%[ll]\>" skipwhite nextgroup=vimDoautocmdMod,vimAutocmdGroup,vimAutoEvent,nvimAutoEvent " Echo And Execute: -- prefer strings! {{{2 " ================ @@ -1645,10 +1728,14 @@ if !exists("skip_vim_syntax_inits") hi def link vimAugroupBang vimBang hi def link vimAugroupError vimError hi def link vimAugroupKey vimCommand - hi def link vimAutoCmd vimCommand - hi def link vimAutoCmdBang vimBang + hi def link vimAutocmd vimCommand + hi def link vimAutocmdBang vimBang + hi def link vimAutocmdPatternEscape Special hi def link vimAutoEvent Type - hi def link vimAutoCmdMod Special + hi def link vimAutoEventGlob Type + hi def link vimAutocmdBufferPattern Special + hi def link vimAutocmdMod Special + hi def link vimAutocmdPatternSep vimSep hi def link vimBang vimOper hi def link vimBehaveBang vimBang hi def link vimBehaveModel vimBehave @@ -1674,6 +1761,8 @@ if !exists("skip_vim_syntax_inits") hi def link vimDefParam vimVar hi def link vimDelcommand vimCommand hi def link vimDelcommandAttr vimUserCmdAttr + hi def link vimDoautocmd vimCommand hi def link vimEcho vimCommand hi def link vimEchohlNone vimGroup hi def link vimEchohl vimCommand @@ -1890,6 +1979,24 @@ if !exists("skip_vim_syntax_inits") hi def link vimVimVar Identifier hi def link vimVimVarName Identifier hi def link vimWarn WarningMsg + hi def link vimWildcard Special + hi def link vimWildcardBraceComma vimWildcard + hi def link vimWildcardBracket vimWildcard + hi def link vimWildcardBracketCaret vimWildcard + hi def link vimWildcardBracketCollatingSymbol vimWildCard + hi def link vimWildcardBracketEnd vimWildcard + hi def link vimWildcardBracketEquivalenceClass vimWildCard + hi def link vimWildcardBracketEscape vimWildcard + hi def link vimWildcardBracketHyphen vimWildcard + hi def link vimWildcardBracketRightBracket vimWildcardBracketCharacter + hi def link vimWildcardBracketStart vimWildcard + hi def link vimWildcardInterval vimWildcard + hi def link vimWildcardQuestion vimWildcard + hi def link vimWildcardStar vimWildcard hi def link vim9Abstract vimCommand hi def link vim9Boolean Boolean diff --git a/src/gen/gen_vimvim.lua b/src/gen/gen_vimvim.lua index 3de09425134d7b..4cd88f0188489c 100644 --- a/src/gen/gen_vimvim.lua +++ b/src/gen/gen_vimvim.lua @@ -40,7 +40,7 @@ local function cmd_kw(prev_cmd, cmd) -- Exclude these from the vimCommand keyword list, they are handled specially --- in syntax/vim.vim (vimAugroupKey, vimAutoCmd, vimGlobal, vimSubst). #9327 +-- in syntax/vim.vim (vimAugroupKey, vimAutocmd, vimGlobal, vimSubst). #9327 local function is_special_cased_cmd(cmd) return ( cmd == 'augroup' @@ -122,26 +122,32 @@ end w('\n\nsyn case ignore') local vimau_start = 'syn keyword vimAutoEvent contained ' +local vimau_end = ' skipwhite nextgroup=vimAutoEventSep,@vimAutocmdPattern' w('\n\n' .. vimau_start) for au, _ in vim.spairs(vim.tbl_extend('error', auevents.events, auevents.aliases)) do - if not auevents.nvim_specific[au] then + -- "User" requires a user defined argument event. + if au ~= 'User' and not auevents.nvim_specific[au] then if lld.line_length > 850 then - w('\n' .. vimau_start) + w(vimau_end .. '\n' .. vimau_start) end w(' ' .. au) +w(vimau_end .. '\n') local nvimau_start = 'syn keyword nvimAutoEvent contained ' -w('\n\n' .. nvimau_start) +local nvimau_end = vimau_end +w('\n' .. nvimau_start) for au, _ in vim.spairs(auevents.nvim_specific) do if lld.line_length > 850 then - w('\n' .. nvimau_start) + w(nvimau_end .. '\n' .. nvimau_start) w(' ' .. au) +w(nvimau_end .. '\n') -w('\n\nsyn case match') +w('\nsyn case match') local vimfun_start = 'syn keyword vimFuncName contained ' w('\n\n' .. vimfun_start) local funcs = mpack.decode(io.open(funcs_file, 'rb'):read('*all'))
[ "-else", "- syn region vimAugroup\tstart=\"\\<aug\\%[roup]\\>\\ze\\s\\+\\%([eE][nN][dD]\\)\\@!\\S\\+\" matchgroup=vimAugroupKey end=\"\\<aug\\%[roup]\\>\\ze\\s\\+[eE][nN][dD]\\>\" contains=vimAutoCmd,@vimAugroupList,vimAugroupkey skipwhite nextgroup=vimAugroupEnd", "+ \\ end=\"\\<aug\\%[roup]\\>\\ze\\s\\+[eE][nN][dD]\\>\"", "- syn match vimAugroupError\t\"\\<aug\\%[roup]\\>\\s\\+[eE][nN][dD]\\>\"", "+syn keyword\tvimAugroupKey\tcontained\taug[roup] \tskipwhite nextgroup=vimAugroupBang,vimAugroupName,vimAugroupEnd", "-\" Autocmd: {{{2", "-syn match\tvimAutoCmdMod\t\"\\(++\\)\\=\\(once\\|nested\\)\"\tskipwhite nextgroup=vimAutoCmdBlock", "+\" =================", "+syn match\tvimWildcardInterval\tcontained\t\"\\\\\\\\\\\\{\\d\\+\\%(,\\d\\+\\)\\=\\\\}\" contains=vimWildcardIntervalNumber", "+ \\ contains=vimWildcardBracketStart,vimWildcardEscape", "+syn match\tvimWildcardBracketEnd\tcontained\t\"]\"", "+syn match\tvimWildcardEscape\tcontained\t\"\\\\.\"", "+syn region\tvimAutocmdPattern\tcontained", "+syn match\tvimAutocmdBufferPattern\tcontained\t\"<buffer\\%(=\\%(\\d\\+\\|abuf\\)\\)\\=>\" skipwhite nextgroup=vimAutocmdPatternSep,vimAutocmdMod,vimAutocmdBlock", "+syn match\tvimAutocmdMod\tcontained\t\"\\%(++\\)\\=\\<nested\\>\" skipwhite nextgroup=vimAutocmdMod,vimAutocmdBlock", "+ hi def link vimDoautocmdMod\tSpecial", "+ hi def link vimWildcardBracketCharacterClass\tvimWildCard", "+ hi def link vimWildcardEscape\tvimWildcard", "+ -- (Separately specified in vim.vim)." ]
[ 35, 36, 43, 47, 59, 76, 84, 87, 101, 105, 117, 121, 136, 143, 150, 189, 203, 211, 240 ]
{ "additions": 145, "author": "zeertzjq", "deletions": 31, "html_url": "https://github.com/neovim/neovim/pull/33586", "issue_id": 33586, "merged_at": "2025-04-23T01:31:09Z", "omission_probability": 0.1, "pr_number": 33586, "repo": "neovim/neovim", "title": "vim-patch:fa3b104: runtime(vim): Update base-syntax, improve :autocmd highlighting", "total_changes": 176 }
366
diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index 1f73f2d135c738..14a6f452bcbfe6 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -642,24 +642,17 @@ static void handle_unknown_csi(TermInput *input, const TermKeyKey *key) switch (initial) { case '?': // Kitty keyboard protocol query response. - if (input->waiting_for_kkp_response) { - input->waiting_for_kkp_response = false; - input->key_encoding = kKeyEncodingKitty; - tui_set_key_encoding(input->tui_data); - } - + input->key_encoding = kKeyEncodingKitty; break; } break; case 'c': switch (initial) { case '?': - // Primary Device Attributes response - if (input->waiting_for_kkp_response) { - input->waiting_for_kkp_response = false; - - // Enable the fallback key encoding (if any) - tui_set_key_encoding(input->tui_data); + // Primary Device Attributes (DA1) response + if (input->callbacks.primary_device_attr) { + input->callbacks.primary_device_attr(input->tui_data); + input->callbacks.primary_device_attr = NULL; } break; diff --git a/src/nvim/tui/input.h b/src/nvim/tui/input.h index e48982f9a4b5bc..4c5a64df9d66ab 100644 --- a/src/nvim/tui/input.h +++ b/src/nvim/tui/input.h @@ -17,6 +17,10 @@ typedef enum { kKeyEncodingXterm, ///< Xterm's modifyOtherKeys encoding (XTMODKEYS) } KeyEncoding; +typedef struct { + void (*primary_device_attr)(TUIData *tui); +} TermInputCallbacks; + #define KEY_BUFFER_SIZE 0x1000 typedef struct { int in_fd; @@ -24,8 +28,7 @@ typedef struct { int8_t paste; bool ttimeout; - bool waiting_for_kkp_response; ///< True if we are expecting to receive a response to a query for - ///< Kitty keyboard protocol support + TermInputCallbacks callbacks; KeyEncoding key_encoding; ///< The key encoding used by the terminal emulator diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 440747be7652de..2b25fb47387917 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -18,6 +18,7 @@ #include "nvim/cursor_shape.h" #include "nvim/event/defs.h" #include "nvim/event/loop.h" +#include "nvim/event/multiqueue.h" #include "nvim/event/signal.h" #include "nvim/event/stream.h" #include "nvim/globals.h" @@ -46,6 +47,10 @@ # include "nvim/os/os_win_console.h" #endif +// Maximum amount of time (in ms) to wait to receive a Device Attributes +// response before exiting. +#define EXIT_TIMEOUT_MS 1000 + #define OUTBUF_SIZE 0xffff #define TOO_MANY_EVENTS 1000000 @@ -100,6 +105,7 @@ struct TUIData { bool bce; bool mouse_enabled; bool mouse_move_enabled; + bool mouse_enabled_save; bool title_enabled; bool sync_output; bool busy, is_invisible, want_invisible; @@ -287,7 +293,8 @@ void tui_enable_extended_underline(TUIData *tui) static void tui_query_kitty_keyboard(TUIData *tui) FUNC_ATTR_NONNULL_ALL { - tui->input.waiting_for_kkp_response = true; + // Set the key encoding whenever the Device Attributes (DA1) response is received. + tui->input.callbacks.primary_device_attr = tui_set_key_encoding; out(tui, S_LEN("\x1b[?u\x1b[c")); } @@ -505,8 +512,8 @@ static void terminfo_start(TUIData *tui) flush_buf(tui); } -/// Disable the alternate screen and prepare for the TUI to close. -static void terminfo_stop(TUIData *tui) +/// Disable various terminal modes and other features. +static void terminfo_disable(TUIData *tui) { // Disable theme update notifications. We do this first to avoid getting any // more notifications after we reset the cursor and any color palette changes. @@ -531,9 +538,29 @@ static void terminfo_stop(TUIData *tui) // May restore old title before exiting alternate screen. tui_set_title(tui, NULL_STRING); + if (tui->cursor_has_color) { + unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); + } + // Disable bracketed paste + unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); + // Disable focus reporting + unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); + + // Send a DA1 request. When the terminal responds we know that it has + // processed all of our requests and won't be emitting anymore sequences. + out(tui, S_LEN("\x1b[c")); + + // Immediately flush the buffer and wait for the DA1 response. + flush_buf(tui); +} + +/// Disable the alternate screen and prepare for the TUI to close. +static void terminfo_stop(TUIData *tui) +{ if (ui_client_exit_status == 0) { ui_client_exit_status = tui->seen_error_exit; } + // if nvim exited with nonzero status, without indicated this was an // intentional exit (like `:1cquit`), it likely was an internal failure. // Don't clobber the stderr error message in this case. @@ -541,13 +568,6 @@ static void terminfo_stop(TUIData *tui) // Exit alternate screen. unibi_out(tui, unibi_exit_ca_mode); } - if (tui->cursor_has_color) { - unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); - } - // Disable bracketed paste - unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); - // Disable focus reporting - unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); flush_buf(tui); uv_tty_reset_mode(); @@ -583,8 +603,14 @@ static void tui_terminal_after_startup(TUIData *tui) flush_buf(tui); } -/// Stop the terminal but allow it to restart later (like after suspend) -static void tui_terminal_stop(TUIData *tui) +void tui_error_exit(TUIData *tui, Integer status) + FUNC_ATTR_NONNULL_ALL +{ + tui->seen_error_exit = (int)status; +} + +void tui_stop(TUIData *tui) + FUNC_ATTR_NONNULL_ALL { if (uv_is_closing((uv_handle_t *)&tui->output_handle)) { // Race between SIGCONT (tui.c) and SIGHUP (os/signal.c)? #8075 @@ -592,28 +618,42 @@ static void tui_terminal_stop(TUIData *tui) tui->stopped = true; return; } - tinput_stop(&tui->input); - // Position the cursor on the last screen line, below all the text - cursor_goto(tui, tui->height - 1, 0); - terminfo_stop(tui); -} -void tui_error_exit(TUIData *tui, Integer status) -{ - tui->seen_error_exit = (int)status; -} + tui->input.callbacks.primary_device_attr = tui_stop_cb; + terminfo_disable(tui); + + // Wait until DA1 response is received + LOOP_PROCESS_EVENTS_UNTIL(tui->loop, tui->loop->events, EXIT_TIMEOUT_MS, tui->stopped); -void tui_stop(TUIData *tui) -{ tui_terminal_stop(tui); stream_set_blocking(tui->input.in_fd, true); // normalize stream (#2598) tinput_destroy(&tui->input); - tui->stopped = true; signal_watcher_stop(&tui->winch_handle); signal_watcher_close(&tui->winch_handle, NULL); uv_close((uv_handle_t *)&tui->startup_delay_timer, NULL); } +/// Callback function called when the response to the Device Attributes (DA1) +/// request is sent during shutdown. +static void tui_stop_cb(TUIData *tui) + FUNC_ATTR_NONNULL_ALL +{ + tui->stopped = true; +} + +/// Stop the terminal but allow it to restart later (like after suspend) +/// +/// This is called after we receive the response to the DA1 request sent from +/// terminfo_disable. +static void tui_terminal_stop(TUIData *tui) + FUNC_ATTR_NONNULL_ALL +{ + tinput_stop(&tui->input); + // Position the cursor on the last screen line, below all the text + cursor_goto(tui, tui->height - 1, 0); + terminfo_stop(tui); +} + /// Returns true if UI `ui` is stopped. bool tui_is_stopped(TUIData *tui) { @@ -1572,7 +1612,16 @@ void tui_suspend(TUIData *tui) // on a non-UNIX system, this is a no-op #ifdef UNIX ui_client_detach(); - bool enable_mouse = tui->mouse_enabled; + tui->mouse_enabled_save = tui->mouse_enabled; + tui->input.callbacks.primary_device_attr = tui_suspend_cb; + terminfo_disable(tui); +#endif +} + +#ifdef UNIX +static void tui_suspend_cb(TUIData *tui) + FUNC_ATTR_NONNULL_ALL +{ tui_terminal_stop(tui); stream_set_blocking(tui->input.in_fd, true); // normalize stream (#2598) @@ -1580,13 +1629,13 @@ void tui_suspend(TUIData *tui) tui_terminal_start(tui); tui_terminal_after_startup(tui); - if (enable_mouse) { + if (tui->mouse_enabled_save) { tui_mouse_on(tui); } stream_set_blocking(tui->input.in_fd, false); // libuv expects this ui_client_attach(tui->width, tui->height, tui->term, tui->rgb); -#endif } +#endif void tui_set_title(TUIData *tui, String title) { @@ -2464,7 +2513,9 @@ static void augment_terminfo(TUIData *tui, const char *term, int vte_version, in if (!kitty && (vte_version == 0 || vte_version >= 5400)) { // Fallback to Xterm's modifyOtherKeys if terminal does not support the - // Kitty keyboard protocol + // Kitty keyboard protocol. We don't actually enable the key encoding here + // though: it won't be enabled until the terminal responds to our query for + // kitty keyboard support. tui->input.key_encoding = kKeyEncodingXterm; } }
diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c index 1f73f2d135c738..14a6f452bcbfe6 100644 --- a/src/nvim/tui/input.c +++ b/src/nvim/tui/input.c @@ -642,24 +642,17 @@ static void handle_unknown_csi(TermInput *input, const TermKeyKey *key) // Kitty keyboard protocol query response. - input->key_encoding = kKeyEncodingKitty; - } + input->key_encoding = kKeyEncodingKitty; } break; case 'c': - // Primary Device Attributes response - // Enable the fallback key encoding (if any) + // Primary Device Attributes (DA1) response + if (input->callbacks.primary_device_attr) { + input->callbacks.primary_device_attr(input->tui_data); + input->callbacks.primary_device_attr = NULL; } diff --git a/src/nvim/tui/input.h b/src/nvim/tui/input.h index e48982f9a4b5bc..4c5a64df9d66ab 100644 --- a/src/nvim/tui/input.h +++ b/src/nvim/tui/input.h @@ -17,6 +17,10 @@ typedef enum { kKeyEncodingXterm, ///< Xterm's modifyOtherKeys encoding (XTMODKEYS) } KeyEncoding; +typedef struct { + void (*primary_device_attr)(TUIData *tui); +} TermInputCallbacks; #define KEY_BUFFER_SIZE 0x1000 typedef struct { int in_fd; @@ -24,8 +28,7 @@ typedef struct { int8_t paste; bool ttimeout; - bool waiting_for_kkp_response; ///< True if we are expecting to receive a response to a query for - ///< Kitty keyboard protocol support + TermInputCallbacks callbacks; KeyEncoding key_encoding; ///< The key encoding used by the terminal emulator diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c index 440747be7652de..2b25fb47387917 100644 --- a/src/nvim/tui/tui.c +++ b/src/nvim/tui/tui.c @@ -18,6 +18,7 @@ #include "nvim/cursor_shape.h" #include "nvim/event/defs.h" #include "nvim/event/loop.h" +#include "nvim/event/multiqueue.h" #include "nvim/event/signal.h" #include "nvim/event/stream.h" #include "nvim/globals.h" @@ -46,6 +47,10 @@ # include "nvim/os/os_win_console.h" #endif +// Maximum amount of time (in ms) to wait to receive a Device Attributes +// response before exiting. +#define EXIT_TIMEOUT_MS 1000 #define OUTBUF_SIZE 0xffff #define TOO_MANY_EVENTS 1000000 @@ -100,6 +105,7 @@ struct TUIData { bool bce; bool mouse_enabled; bool mouse_move_enabled; + bool mouse_enabled_save; bool title_enabled; bool sync_output; bool busy, is_invisible, want_invisible; @@ -287,7 +293,8 @@ void tui_enable_extended_underline(TUIData *tui) static void tui_query_kitty_keyboard(TUIData *tui) FUNC_ATTR_NONNULL_ALL - tui->input.waiting_for_kkp_response = true; + // Set the key encoding whenever the Device Attributes (DA1) response is received. + tui->input.callbacks.primary_device_attr = tui_set_key_encoding; out(tui, S_LEN("\x1b[?u\x1b[c")); @@ -505,8 +512,8 @@ static void terminfo_start(TUIData *tui) -/// Disable the alternate screen and prepare for the TUI to close. -static void terminfo_stop(TUIData *tui) +static void terminfo_disable(TUIData *tui) // Disable theme update notifications. We do this first to avoid getting any // more notifications after we reset the cursor and any color palette changes. @@ -531,9 +538,29 @@ static void terminfo_stop(TUIData *tui) // May restore old title before exiting alternate screen. tui_set_title(tui, NULL_STRING); + if (tui->cursor_has_color) { + unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); + } + // Disable bracketed paste + unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); + // Disable focus reporting + unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); + // Send a DA1 request. When the terminal responds we know that it has + // processed all of our requests and won't be emitting anymore sequences. + out(tui, S_LEN("\x1b[c")); + // Immediately flush the buffer and wait for the DA1 response. +static void terminfo_stop(TUIData *tui) if (ui_client_exit_status == 0) { ui_client_exit_status = tui->seen_error_exit; // if nvim exited with nonzero status, without indicated this was an // intentional exit (like `:1cquit`), it likely was an internal failure. // Don't clobber the stderr error message in this case. @@ -541,13 +568,6 @@ static void terminfo_stop(TUIData *tui) // Exit alternate screen. unibi_out(tui, unibi_exit_ca_mode); - if (tui->cursor_has_color) { - unibi_out_ext(tui, tui->unibi_ext.reset_cursor_color); - } - // Disable bracketed paste - unibi_out_ext(tui, tui->unibi_ext.disable_bracketed_paste); - // Disable focus reporting - unibi_out_ext(tui, tui->unibi_ext.disable_focus_reporting); uv_tty_reset_mode(); @@ -583,8 +603,14 @@ static void tui_terminal_after_startup(TUIData *tui) +void tui_error_exit(TUIData *tui, Integer status) + tui->seen_error_exit = (int)status; +void tui_stop(TUIData *tui) if (uv_is_closing((uv_handle_t *)&tui->output_handle)) { // Race between SIGCONT (tui.c) and SIGHUP (os/signal.c)? #8075 @@ -592,28 +618,42 @@ static void tui_terminal_stop(TUIData *tui) tui->stopped = true; return; - tinput_stop(&tui->input); - // Position the cursor on the last screen line, below all the text - cursor_goto(tui, tui->height - 1, 0); - terminfo_stop(tui); -void tui_error_exit(TUIData *tui, Integer status) - tui->seen_error_exit = (int)status; + tui->input.callbacks.primary_device_attr = tui_stop_cb; + // Wait until DA1 response is received + LOOP_PROCESS_EVENTS_UNTIL(tui->loop, tui->loop->events, EXIT_TIMEOUT_MS, tui->stopped); -void tui_stop(TUIData *tui) tinput_destroy(&tui->input); - tui->stopped = true; signal_watcher_stop(&tui->winch_handle); signal_watcher_close(&tui->winch_handle, NULL); uv_close((uv_handle_t *)&tui->startup_delay_timer, NULL); +/// Callback function called when the response to the Device Attributes (DA1) +/// request is sent during shutdown. +static void tui_stop_cb(TUIData *tui) + tui->stopped = true; +/// Stop the terminal but allow it to restart later (like after suspend) +/// +/// This is called after we receive the response to the DA1 request sent from +static void tui_terminal_stop(TUIData *tui) + tinput_stop(&tui->input); + // Position the cursor on the last screen line, below all the text + cursor_goto(tui, tui->height - 1, 0); /// Returns true if UI `ui` is stopped. bool tui_is_stopped(TUIData *tui) @@ -1572,7 +1612,16 @@ void tui_suspend(TUIData *tui) // on a non-UNIX system, this is a no-op #ifdef UNIX ui_client_detach(); - bool enable_mouse = tui->mouse_enabled; + tui->mouse_enabled_save = tui->mouse_enabled; + tui->input.callbacks.primary_device_attr = tui_suspend_cb; +#ifdef UNIX +static void tui_suspend_cb(TUIData *tui) @@ -1580,13 +1629,13 @@ void tui_suspend(TUIData *tui) tui_terminal_start(tui); tui_terminal_after_startup(tui); - if (enable_mouse) { + if (tui->mouse_enabled_save) { tui_mouse_on(tui); stream_set_blocking(tui->input.in_fd, false); // libuv expects this ui_client_attach(tui->width, tui->height, tui->term, tui->rgb); -#endif void tui_set_title(TUIData *tui, String title) @@ -2464,7 +2513,9 @@ static void augment_terminfo(TUIData *tui, const char *term, int vte_version, in if (!kitty && (vte_version == 0 || vte_version >= 5400)) { // Fallback to Xterm's modifyOtherKeys if terminal does not support the - // Kitty keyboard protocol + // though: it won't be enabled until the terminal responds to our query for + // kitty keyboard support. tui->input.key_encoding = kKeyEncodingXterm;
[ "+/// Disable various terminal modes and other features.", "+ flush_buf(tui);", "+/// Disable the alternate screen and prepare for the TUI to close.", "-/// Stop the terminal but allow it to restart later (like after suspend)", "-static void tui_terminal_stop(TUIData *tui)", "+/// terminfo_disable.", "+ terminfo_stop(tui);", "+ // Kitty keyboard protocol. We don't actually enable the key encoding here" ]
[ 106, 128, 131, 159, 160, 214, 221, 266 ]
{ "additions": 89, "author": "neovim-backports[bot]", "deletions": 42, "html_url": "https://github.com/neovim/neovim/pull/33574", "issue_id": 33574, "merged_at": "2025-04-22T12:51:47Z", "omission_probability": 0.1, "pr_number": 33574, "repo": "neovim/neovim", "title": "fix(tui): ensure all pending escape sequences are processed before exiting", "total_changes": 131 }
367
diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index ad1481e304cdc3..47b636f2845368 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -133,6 +133,7 @@ OPTIONS • 'completefuzzycollect' enables fuzzy collection of candidates for (some) |ins-completion| modes. +• 'autowriteall' write all buffers upon receiving `SIGHUP`, `SIGQUIT` or `SIGTSTP`. PERFORMANCE diff --git a/src/nvim/os/signal.c b/src/nvim/os/signal.c index 11f99d0a0f49ac..55efce03379e17 100644 --- a/src/nvim/os/signal.c +++ b/src/nvim/os/signal.c @@ -12,16 +12,18 @@ #include "nvim/eval.h" #include "nvim/event/defs.h" #include "nvim/event/signal.h" +#include "nvim/ex_cmds2.h" #include "nvim/globals.h" #include "nvim/log.h" #include "nvim/main.h" +#include "nvim/option_vars.h" #include "nvim/os/signal.h" #ifdef SIGPWR # include "nvim/memline.h" #endif -static SignalWatcher spipe, shup, squit, sterm, susr1, swinch; +static SignalWatcher spipe, shup, squit, sterm, susr1, swinch, ststp; #ifdef SIGPWR static SignalWatcher spwr; #endif @@ -48,6 +50,7 @@ void signal_init(void) signal_watcher_init(&main_loop, &shup, NULL); signal_watcher_init(&main_loop, &squit, NULL); signal_watcher_init(&main_loop, &sterm, NULL); + signal_watcher_init(&main_loop, &ststp, NULL); #ifdef SIGPWR signal_watcher_init(&main_loop, &spwr, NULL); #endif @@ -67,6 +70,7 @@ void signal_teardown(void) signal_watcher_close(&shup, NULL); signal_watcher_close(&squit, NULL); signal_watcher_close(&sterm, NULL); + signal_watcher_close(&ststp, NULL); #ifdef SIGPWR signal_watcher_close(&spwr, NULL); #endif @@ -88,6 +92,9 @@ void signal_start(void) signal_watcher_start(&squit, on_signal, SIGQUIT); #endif signal_watcher_start(&sterm, on_signal, SIGTERM); +#ifdef SIGTSTP + signal_watcher_start(&ststp, on_signal, SIGTSTP); +#endif #ifdef SIGPWR signal_watcher_start(&spwr, on_signal, SIGPWR); #endif @@ -109,6 +116,7 @@ void signal_stop(void) signal_watcher_stop(&squit); #endif signal_watcher_stop(&sterm); + signal_watcher_stop(&ststp); #ifdef SIGPWR signal_watcher_stop(&spwr); #endif @@ -143,6 +151,10 @@ static char *signal_name(int signum) #endif case SIGTERM: return "SIGTERM"; +#ifdef SIGTSTP + case SIGTSTP: + return "SIGTSTP"; +#endif #ifdef SIGQUIT case SIGQUIT: return "SIGQUIT"; @@ -177,6 +189,10 @@ static void deadly_signal(int signum) snprintf(IObuff, IOSIZE, "Nvim: Caught deadly signal '%s'\n", signal_name(signum)); + if (p_awa && signum != SIGTERM) { + autowrite_all(); + } + // Preserve files and exit. preserve_exit(IObuff); } @@ -197,6 +213,9 @@ static void on_signal(SignalWatcher *handle, int signum, void *data) break; #endif case SIGTERM: +#ifdef SIGTSTP + case SIGTSTP: +#endif #ifdef SIGQUIT case SIGQUIT: #endif diff --git a/test/functional/autocmd/signal_spec.lua b/test/functional/autocmd/signal_spec.lua index 4416afb3ba1944..03e991f21c8ccc 100644 --- a/test/functional/autocmd/signal_spec.lua +++ b/test/functional/autocmd/signal_spec.lua @@ -8,39 +8,90 @@ local fn = n.fn local next_msg = n.next_msg local is_os = t.is_os local skip = t.skip +local read_file = t.read_file +local feed = n.feed +local retry = t.retry if skip(is_os('win'), 'Only applies to POSIX systems') then return end -local function posix_kill(signame, pid) - os.execute('kill -s ' .. signame .. ' -- ' .. pid .. ' >/dev/null') -end +describe("'autowriteall' on signal exit", function() + before_each(clear) + + local function test_deadly_sig(signame, awa, should_write) + local testfile = 'Xtest_SIG' .. signame .. (awa and '_awa' or '_noawa') + local teststr = 'Testaaaaaaa' + finally(function() + os.remove(testfile) + end) + + if awa then + command('set autowriteall') + end + + command('edit ' .. testfile) + feed('i' .. teststr) + vim.uv.kill(fn.getpid(), signame) + + retry(nil, 5000, function() + eq((should_write and (teststr .. '\n') or nil), read_file(testfile)) + end) + end + + it('dont write if SIGTERM & awa on', function() + test_deadly_sig('sigterm', true, false) + end) + it('dont write if SIGTERM & awa off', function() + test_deadly_sig('sigterm', false, false) + end) + + it('write if SIGHUP & awa on', function() + test_deadly_sig('sighup', true, true) + end) + it('dont write if SIGHUP & awa off', function() + test_deadly_sig('sighup', false, false) + end) + + it('write if SIGTSTP & awa on', function() + test_deadly_sig('sigtstp', true, true) + end) + it('dont write if SIGTSTP & awa off', function() + test_deadly_sig('sigtstp', false, false) + end) + + it('write if SIGQUIT & awa on', function() + test_deadly_sig('sigquit', true, true) + end) + it('dont write if SIGQUIT & awa off', function() + test_deadly_sig('sigquit', false, false) + end) +end) describe('autocmd Signal', function() before_each(clear) it('matches *', function() command('autocmd Signal * call rpcnotify(1, "foo")') - posix_kill('USR1', fn.getpid()) + vim.uv.kill(fn.getpid(), 'sigusr1') eq({ 'notification', 'foo', {} }, next_msg()) end) it('matches SIGUSR1', function() command('autocmd Signal SIGUSR1 call rpcnotify(1, "foo")') - posix_kill('USR1', fn.getpid()) + vim.uv.kill(fn.getpid(), 'sigusr1') eq({ 'notification', 'foo', {} }, next_msg()) end) it('matches SIGWINCH', function() command('autocmd Signal SIGWINCH call rpcnotify(1, "foo")') - posix_kill('WINCH', fn.getpid()) + vim.uv.kill(fn.getpid(), 'sigwinch') eq({ 'notification', 'foo', {} }, next_msg()) end) it('does not match unknown patterns', function() command('autocmd Signal SIGUSR2 call rpcnotify(1, "foo")') - posix_kill('USR1', fn.getpid()) + vim.uv.kill(fn.getpid(), 'sigusr2') eq(nil, next_msg(500)) end) end)
diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index ad1481e304cdc3..47b636f2845368 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -133,6 +133,7 @@ OPTIONS • 'completefuzzycollect' enables fuzzy collection of candidates for (some) |ins-completion| modes. PERFORMANCE diff --git a/src/nvim/os/signal.c b/src/nvim/os/signal.c index 11f99d0a0f49ac..55efce03379e17 100644 --- a/src/nvim/os/signal.c +++ b/src/nvim/os/signal.c @@ -12,16 +12,18 @@ #include "nvim/eval.h" #include "nvim/event/defs.h" #include "nvim/event/signal.h" #include "nvim/globals.h" #include "nvim/log.h" #include "nvim/main.h" +#include "nvim/option_vars.h" #include "nvim/os/signal.h" # include "nvim/memline.h" -static SignalWatcher spipe, shup, squit, sterm, susr1, swinch; +static SignalWatcher spipe, shup, squit, sterm, susr1, swinch, ststp; static SignalWatcher spwr; @@ -48,6 +50,7 @@ void signal_init(void) signal_watcher_init(&main_loop, &shup, NULL); signal_watcher_init(&main_loop, &squit, NULL); signal_watcher_init(&main_loop, &sterm, NULL); + signal_watcher_init(&main_loop, &ststp, NULL); signal_watcher_init(&main_loop, &spwr, NULL); @@ -67,6 +70,7 @@ void signal_teardown(void) signal_watcher_close(&shup, NULL); signal_watcher_close(&squit, NULL); signal_watcher_close(&sterm, NULL); + signal_watcher_close(&ststp, NULL); signal_watcher_close(&spwr, NULL); @@ -88,6 +92,9 @@ void signal_start(void) signal_watcher_start(&squit, on_signal, SIGQUIT); signal_watcher_start(&sterm, on_signal, SIGTERM); + signal_watcher_start(&ststp, on_signal, SIGTSTP); signal_watcher_start(&spwr, on_signal, SIGPWR); @@ -109,6 +116,7 @@ void signal_stop(void) signal_watcher_stop(&squit); signal_watcher_stop(&sterm); + signal_watcher_stop(&ststp); signal_watcher_stop(&spwr); @@ -143,6 +151,10 @@ static char *signal_name(int signum) return "SIGTERM"; + return "SIGTSTP"; return "SIGQUIT"; @@ -177,6 +189,10 @@ static void deadly_signal(int signum) snprintf(IObuff, IOSIZE, "Nvim: Caught deadly signal '%s'\n", signal_name(signum)); + autowrite_all(); + } // Preserve files and exit. preserve_exit(IObuff); } @@ -197,6 +213,9 @@ static void on_signal(SignalWatcher *handle, int signum, void *data) break; diff --git a/test/functional/autocmd/signal_spec.lua b/test/functional/autocmd/signal_spec.lua index 4416afb3ba1944..03e991f21c8ccc 100644 --- a/test/functional/autocmd/signal_spec.lua +++ b/test/functional/autocmd/signal_spec.lua @@ -8,39 +8,90 @@ local fn = n.fn local next_msg = n.next_msg local is_os = t.is_os local skip = t.skip +local read_file = t.read_file +local feed = n.feed +local retry = t.retry if skip(is_os('win'), 'Only applies to POSIX systems') then return end -local function posix_kill(signame, pid) - os.execute('kill -s ' .. signame .. ' -- ' .. pid .. ' >/dev/null') -end +describe("'autowriteall' on signal exit", function() + before_each(clear) + local teststr = 'Testaaaaaaa' + finally(function() + os.remove(testfile) + if awa then + end + feed('i' .. teststr) + retry(nil, 5000, function() + eq((should_write and (teststr .. '\n') or nil), read_file(testfile)) + end + it('dont write if SIGTERM & awa on', function() + test_deadly_sig('sigterm', true, false) + it('dont write if SIGTERM & awa off', function() + test_deadly_sig('sigterm', false, false) + it('write if SIGHUP & awa on', function() + test_deadly_sig('sighup', true, true) + it('dont write if SIGHUP & awa off', function() + test_deadly_sig('sighup', false, false) + it('write if SIGTSTP & awa on', function() + test_deadly_sig('sigtstp', true, true) + it('dont write if SIGTSTP & awa off', function() + test_deadly_sig('sigtstp', false, false) + it('write if SIGQUIT & awa on', function() + test_deadly_sig('sigquit', true, true) + it('dont write if SIGQUIT & awa off', function() + test_deadly_sig('sigquit', false, false) +end) describe('autocmd Signal', function() before_each(clear) it('matches *', function() command('autocmd Signal * call rpcnotify(1, "foo")') it('matches SIGUSR1', function() command('autocmd Signal SIGUSR1 call rpcnotify(1, "foo")') it('matches SIGWINCH', function() command('autocmd Signal SIGWINCH call rpcnotify(1, "foo")') - posix_kill('WINCH', fn.getpid()) it('does not match unknown patterns', function() command('autocmd Signal SIGUSR2 call rpcnotify(1, "foo")') + vim.uv.kill(fn.getpid(), 'sigusr2') eq(nil, next_msg(500)) end)
[ "+• 'autowriteall' write all buffers upon receiving `SIGHUP`, `SIGQUIT` or `SIGTSTP`.", "+#include \"nvim/ex_cmds2.h\"", "+ if (p_awa && signum != SIGTERM) {", "+ local function test_deadly_sig(signame, awa, should_write)", "+ local testfile = 'Xtest_SIG' .. signame .. (awa and '_awa' or '_noawa')", "+ command('set autowriteall')", "+ command('edit ' .. testfile)", "+ vim.uv.kill(fn.getpid(), signame)", "+ vim.uv.kill(fn.getpid(), 'sigwinch')" ]
[ 8, 20, 85, 124, 125, 132, 135, 137, 193 ]
{ "additions": 79, "author": "SkohTV", "deletions": 8, "html_url": "https://github.com/neovim/neovim/pull/32843", "issue_id": 32843, "merged_at": "2025-03-31T13:14:45Z", "omission_probability": 0.1, "pr_number": 32843, "repo": "neovim/neovim", "title": "feat(editor): 'autowriteall' on SIGHUP/SIGQUIT", "total_changes": 87 }
368
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index da438622d998cb..eecf558c516cf5 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -2777,8 +2777,11 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) < - If `end` is less than `start`, traversal works backwards. (Useful with - `limit`, to get the first marks prior to a given position.) + If `end` is less than `start`, marks are returned in reverse order. + (Useful with `limit`, to get the first marks prior to a given position.) + + Note: For a reverse range, `limit` does not actually affect the traversed + range, just how many marks are returned Note: when using extmark ranges (marks with a end_row/end_col position) the `overlap` option might be useful. Otherwise only the start position of diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index 5e684ab4084dad..55ab2d6e72c51a 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -369,8 +369,11 @@ function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end --- vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) --- ``` --- ---- If `end` is less than `start`, traversal works backwards. (Useful ---- with `limit`, to get the first marks prior to a given position.) +--- If `end` is less than `start`, marks are returned in reverse order. +--- (Useful with `limit`, to get the first marks prior to a given position.) +--- +--- Note: For a reverse range, `limit` does not actually affect the traversed +--- range, just how many marks are returned --- --- Note: when using extmark ranges (marks with a end_row/end_col position) --- the `overlap` option might be useful. Otherwise only the start position diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index 95f2167c03f8a0..ee9d5d80678b0a 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -241,8 +241,11 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id, /// vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) /// ``` /// -/// If `end` is less than `start`, traversal works backwards. (Useful -/// with `limit`, to get the first marks prior to a given position.) +/// If `end` is less than `start`, marks are returned in reverse order. +/// (Useful with `limit`, to get the first marks prior to a given position.) +/// +/// Note: For a reverse range, `limit` does not actually affect the traversed +/// range, just how many marks are returned /// /// Note: when using extmark ranges (marks with a end_row/end_col position) /// the `overlap` option might be useful. Otherwise only the start position @@ -327,8 +330,6 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e limit = INT64_MAX; } - bool reverse = false; - int l_row; colnr_T l_col; if (!extmark_get_index_from_obj(buf, ns_id, start, &l_row, &l_col, err)) { @@ -341,17 +342,31 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e return rv; } - if (l_row > u_row || (l_row == u_row && l_col > u_col)) { - reverse = true; + size_t rv_limit = (size_t)limit; + bool reverse = l_row > u_row || (l_row == u_row && l_col > u_col); + if (reverse) { + limit = INT64_MAX; // limit the return value instead + int row = l_row; + l_row = u_row; + u_row = row; + colnr_T col = l_col; + l_col = u_col; + u_col = col; } // note: ns_id=-1 allowed, represented as UINT32_MAX ExtmarkInfoArray marks = extmark_get(buf, (uint32_t)ns_id, l_row, l_col, u_row, - u_col, (int64_t)limit, reverse, type, opts->overlap); + u_col, (int64_t)limit, type, opts->overlap); - rv = arena_array(arena, kv_size(marks)); - for (size_t i = 0; i < kv_size(marks); i++) { - ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + rv = arena_array(arena, MIN(kv_size(marks), rv_limit)); + if (reverse) { + for (int i = (int)kv_size(marks) - 1; i >= 0 && kv_size(rv) < rv_limit; i--) { + ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + } + } else { + for (size_t i = 0; i < kv_size(marks); i++) { + ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + } } kv_destroy(marks); diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index 051e47b0acb202..cbca6e0039fcea 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -259,11 +259,9 @@ bool extmark_clear(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_r /// /// if upper_lnum or upper_col are negative the buffer /// will be searched to the start, or end -/// reverse can be set to control the order of the array /// amount = amount of marks to find or INT64_MAX for all ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row, - colnr_T u_col, int64_t amount, bool reverse, ExtmarkType type_filter, - bool overlap) + colnr_T u_col, int64_t amount, ExtmarkType type_filter, bool overlap) { ExtmarkInfoArray array = KV_INITIAL_VALUE; MarkTreeIter itr[1]; @@ -281,29 +279,21 @@ ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_co } else { // Find all the marks beginning with the start position marktree_itr_get_ext(buf->b_marktree, MTPos(l_row, l_col), - itr, reverse, false, NULL, NULL); + itr, false, false, NULL, NULL); } - int order = reverse ? -1 : 1; while ((int64_t)kv_size(array) < amount) { MTKey mark = marktree_itr_current(itr); if (mark.pos.row < 0 - || (mark.pos.row - u_row) * order > 0 - || (mark.pos.row == u_row && (mark.pos.col - u_col) * order > 0)) { + || (mark.pos.row > u_row) + || (mark.pos.row == u_row && mark.pos.col > u_col)) { break; } - if (mt_end(mark)) { - goto next_mark; - } - - MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); - push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); -next_mark: - if (reverse) { - marktree_itr_prev(buf->b_marktree, itr); - } else { - marktree_itr_next(buf->b_marktree, itr); + if (!mt_end(mark)) { + MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); + push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); } + marktree_itr_next(buf->b_marktree, itr); } return array; } diff --git a/test/functional/api/extmark_spec.lua b/test/functional/api/extmark_spec.lua index 31bb9841dcb403..1d030a2ee3e3c4 100644 --- a/test/functional/api/extmark_spec.lua +++ b/test/functional/api/extmark_spec.lua @@ -331,30 +331,30 @@ describe('API/extmarks', function() rv = get_extmarks(ns, lower, upper) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) - -- prev with mark id + -- reverse with mark id rv = get_extmarks(ns, marks[3], { 0, 0 }, { limit = 1 }) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) rv = get_extmarks(ns, marks[2], { 0, 0 }, { limit = 1 }) eq({ { marks[2], positions[2][1], positions[2][2] } }, rv) - -- prev with positional when mark exists at position + -- reverse with positional when mark exists at position rv = get_extmarks(ns, positions[3], { 0, 0 }, { limit = 1 }) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) - -- prev with positional index (no mark at position) + -- reverse with positional index (no mark at position) rv = get_extmarks(ns, { positions[1][1], positions[1][2] + 1 }, { 0, 0 }, { limit = 1 }) eq({ { marks[1], positions[1][1], positions[1][2] } }, rv) - -- prev with Extremity index + -- reverse with Extremity index rv = get_extmarks(ns, { -1, -1 }, { 0, 0 }, { limit = 1 }) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) - -- prevrange with mark id + -- reverse with mark id rv = get_extmarks(ns, marks[3], marks[1]) eq({ marks[3], positions[3][1], positions[3][2] }, rv[1]) eq({ marks[2], positions[2][1], positions[2][2] }, rv[2]) eq({ marks[1], positions[1][1], positions[1][2] }, rv[3]) - -- prevrange with limit + -- reverse with limit rv = get_extmarks(ns, marks[3], marks[1], { limit = 2 }) eq(2, #rv) - -- prevrange with positional when mark exists at position + -- reverse with positional when mark exists at position rv = get_extmarks(ns, positions[3], positions[1]) eq({ { marks[3], positions[3][1], positions[3][2] }, @@ -363,7 +363,7 @@ describe('API/extmarks', function() }, rv) rv = get_extmarks(ns, positions[2], positions[1]) eq(2, #rv) - -- prevrange with positional index (no mark at position) + -- reverse with positional index (no mark at position) lower = { positions[2][1], positions[2][2] + 1 } upper = { positions[3][1], positions[3][2] + 1 } rv = get_extmarks(ns, upper, lower) @@ -372,7 +372,7 @@ describe('API/extmarks', function() upper = { positions[3][1], positions[3][2] + 2 } rv = get_extmarks(ns, upper, lower) eq({}, rv) - -- prevrange with extremity index + -- reverse with extremity index lower = { 0, 0 } upper = { positions[2][1], positions[2][2] - 1 } rv = get_extmarks(ns, upper, lower) @@ -428,6 +428,14 @@ describe('API/extmarks', function() set_extmark(ns, marks[3], 0, 2) -- check is inclusive local rv = get_extmarks(ns, { 2, 3 }, { 0, 2 }) eq({ { marks[1], 2, 1 }, { marks[2], 1, 4 }, { marks[3], 0, 2 } }, rv) + -- doesn't include paired marks whose start pos > lower bound twice + -- and returns mark overlapping start pos but not end pos + local m1 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 4 }) + local m2 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 2 }) + local m3 = set_extmark(ns, nil, 1, 0, { end_row = 1, end_col = 4 }) + local m4 = set_extmark(ns, nil, 1, 2, { end_row = 1, end_col = 4 }) + rv = get_extmarks(ns, { 1, 3 }, { 1, 2 }, { overlap = true }) + eq({ { m4, 1, 2 }, { m3, 1, 0 }, { m2, 0, 0 }, { m1, 0, 0 } }, rv) end) it('get_marks limit=0 returns nothing', function() @@ -973,7 +981,7 @@ describe('API/extmarks', function() eq(1, #rv) rv = get_extmarks(ns2, { 0, 0 }, positions[2], { limit = 1 }) eq(1, #rv) - -- get_prev (limit set) + -- reverse (limit set) rv = get_extmarks(ns, positions[1], { 0, 0 }, { limit = 1 }) eq(1, #rv) rv = get_extmarks(ns2, positions[1], { 0, 0 }, { limit = 1 }) @@ -984,7 +992,7 @@ describe('API/extmarks', function() eq(2, #rv) rv = get_extmarks(ns2, positions[1], positions[2]) eq(2, #rv) - -- get_prev (no limit) + -- reverse (no limit) rv = get_extmarks(ns, positions[2], positions[1]) eq(2, #rv) rv = get_extmarks(ns2, positions[2], positions[1])
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index da438622d998cb..eecf558c516cf5 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -2777,8 +2777,11 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) < - If `end` is less than `start`, traversal works backwards. (Useful with - `limit`, to get the first marks prior to a given position.) + If `end` is less than `start`, marks are returned in reverse order. + (Useful with `limit`, to get the first marks prior to a given position.) + + Note: For a reverse range, `limit` does not actually affect the traversed + range, just how many marks are returned Note: when using extmark ranges (marks with a end_row/end_col position) the `overlap` option might be useful. Otherwise only the start position of diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index 5e684ab4084dad..55ab2d6e72c51a 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -369,8 +369,11 @@ function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end --- vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) --- ``` ---- If `end` is less than `start`, traversal works backwards. (Useful ---- with `limit`, to get the first marks prior to a given position.) +--- If `end` is less than `start`, marks are returned in reverse order. +--- (Useful with `limit`, to get the first marks prior to a given position.) +--- +--- Note: For a reverse range, `limit` does not actually affect the traversed +--- range, just how many marks are returned --- Note: when using extmark ranges (marks with a end_row/end_col position) --- the `overlap` option might be useful. Otherwise only the start position diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index 95f2167c03f8a0..ee9d5d80678b0a 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -241,8 +241,11 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id, /// vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) /// ``` -/// If `end` is less than `start`, traversal works backwards. (Useful -/// with `limit`, to get the first marks prior to a given position.) +/// (Useful with `limit`, to get the first marks prior to a given position.) +/// Note: For a reverse range, `limit` does not actually affect the traversed +/// range, just how many marks are returned /// Note: when using extmark ranges (marks with a end_row/end_col position) /// the `overlap` option might be useful. Otherwise only the start position @@ -327,8 +330,6 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e limit = INT64_MAX; - bool reverse = false; int l_row; colnr_T l_col; if (!extmark_get_index_from_obj(buf, ns_id, start, &l_row, &l_col, err)) { @@ -341,17 +342,31 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e return rv; - if (l_row > u_row || (l_row == u_row && l_col > u_col)) { - reverse = true; + bool reverse = l_row > u_row || (l_row == u_row && l_col > u_col); + limit = INT64_MAX; // limit the return value instead + int row = l_row; + l_row = u_row; + u_row = row; + colnr_T col = l_col; + l_col = u_col; + u_col = col; // note: ns_id=-1 allowed, represented as UINT32_MAX ExtmarkInfoArray marks = extmark_get(buf, (uint32_t)ns_id, l_row, l_col, u_row, - u_col, (int64_t)limit, reverse, type, opts->overlap); + u_col, (int64_t)limit, type, opts->overlap); - rv = arena_array(arena, kv_size(marks)); - ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + rv = arena_array(arena, MIN(kv_size(marks), rv_limit)); + for (int i = (int)kv_size(marks) - 1; i >= 0 && kv_size(rv) < rv_limit; i--) { + } else { + for (size_t i = 0; i < kv_size(marks); i++) { kv_destroy(marks); diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index 051e47b0acb202..cbca6e0039fcea 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -259,11 +259,9 @@ bool extmark_clear(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_r /// if upper_lnum or upper_col are negative the buffer /// will be searched to the start, or end /// amount = amount of marks to find or INT64_MAX for all ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row, - colnr_T u_col, int64_t amount, bool reverse, ExtmarkType type_filter, - bool overlap) + colnr_T u_col, int64_t amount, ExtmarkType type_filter, bool overlap) { ExtmarkInfoArray array = KV_INITIAL_VALUE; MarkTreeIter itr[1]; @@ -281,29 +279,21 @@ ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_co } else { // Find all the marks beginning with the start position marktree_itr_get_ext(buf->b_marktree, MTPos(l_row, l_col), - itr, reverse, false, NULL, NULL); + itr, false, false, NULL, NULL); - int order = reverse ? -1 : 1; while ((int64_t)kv_size(array) < amount) { MTKey mark = marktree_itr_current(itr); if (mark.pos.row < 0 - || (mark.pos.row - u_row) * order > 0 - || (mark.pos.row == u_row && (mark.pos.col - u_col) * order > 0)) { + || (mark.pos.row > u_row) + || (mark.pos.row == u_row && mark.pos.col > u_col)) { break; - if (mt_end(mark)) { - goto next_mark; - } - MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); - push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); -next_mark: - marktree_itr_prev(buf->b_marktree, itr); - } else { - marktree_itr_next(buf->b_marktree, itr); + if (!mt_end(mark)) { + MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); + push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); + marktree_itr_next(buf->b_marktree, itr); return array; } diff --git a/test/functional/api/extmark_spec.lua b/test/functional/api/extmark_spec.lua index 31bb9841dcb403..1d030a2ee3e3c4 100644 --- a/test/functional/api/extmark_spec.lua +++ b/test/functional/api/extmark_spec.lua @@ -331,30 +331,30 @@ describe('API/extmarks', function() rv = get_extmarks(ns, lower, upper) - -- prev with mark id rv = get_extmarks(ns, marks[3], { 0, 0 }, { limit = 1 }) rv = get_extmarks(ns, marks[2], { 0, 0 }, { limit = 1 }) eq({ { marks[2], positions[2][1], positions[2][2] } }, rv) - -- prev with positional when mark exists at position rv = get_extmarks(ns, positions[3], { 0, 0 }, { limit = 1 }) - -- prev with positional index (no mark at position) rv = get_extmarks(ns, { positions[1][1], positions[1][2] + 1 }, { 0, 0 }, { limit = 1 }) eq({ { marks[1], positions[1][1], positions[1][2] } }, rv) - -- prev with Extremity index + -- reverse with Extremity index rv = get_extmarks(ns, { -1, -1 }, { 0, 0 }, { limit = 1 }) - -- prevrange with mark id rv = get_extmarks(ns, marks[3], marks[1]) eq({ marks[3], positions[3][1], positions[3][2] }, rv[1]) eq({ marks[2], positions[2][1], positions[2][2] }, rv[2]) eq({ marks[1], positions[1][1], positions[1][2] }, rv[3]) rv = get_extmarks(ns, marks[3], marks[1], { limit = 2 }) - -- prevrange with positional when mark exists at position rv = get_extmarks(ns, positions[3], positions[1]) eq({ { marks[3], positions[3][1], positions[3][2] }, @@ -363,7 +363,7 @@ describe('API/extmarks', function() }, rv) - -- prevrange with positional index (no mark at position) lower = { positions[2][1], positions[2][2] + 1 } upper = { positions[3][1], positions[3][2] + 1 } @@ -372,7 +372,7 @@ describe('API/extmarks', function() upper = { positions[3][1], positions[3][2] + 2 } eq({}, rv) - -- prevrange with extremity index + -- reverse with extremity index lower = { 0, 0 } upper = { positions[2][1], positions[2][2] - 1 } @@ -428,6 +428,14 @@ describe('API/extmarks', function() set_extmark(ns, marks[3], 0, 2) -- check is inclusive local rv = get_extmarks(ns, { 2, 3 }, { 0, 2 }) eq({ { marks[1], 2, 1 }, { marks[2], 1, 4 }, { marks[3], 0, 2 } }, rv) + -- doesn't include paired marks whose start pos > lower bound twice + -- and returns mark overlapping start pos but not end pos + local m1 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 4 }) + local m2 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 2 }) + local m3 = set_extmark(ns, nil, 1, 0, { end_row = 1, end_col = 4 }) + local m4 = set_extmark(ns, nil, 1, 2, { end_row = 1, end_col = 4 }) + rv = get_extmarks(ns, { 1, 3 }, { 1, 2 }, { overlap = true }) + eq({ { m4, 1, 2 }, { m3, 1, 0 }, { m2, 0, 0 }, { m1, 0, 0 } }, rv) end) it('get_marks limit=0 returns nothing', function() @@ -973,7 +981,7 @@ describe('API/extmarks', function() rv = get_extmarks(ns2, { 0, 0 }, positions[2], { limit = 1 }) - -- get_prev (limit set) + -- reverse (limit set) rv = get_extmarks(ns, positions[1], { 0, 0 }, { limit = 1 }) rv = get_extmarks(ns2, positions[1], { 0, 0 }, { limit = 1 }) @@ -984,7 +992,7 @@ describe('API/extmarks', function() rv = get_extmarks(ns2, positions[1], positions[2]) - -- get_prev (no limit) + -- reverse (no limit) rv = get_extmarks(ns2, positions[2], positions[1])
[ "+/// If `end` is less than `start`, marks are returned in reverse order.", "+///", "+ size_t rv_limit = (size_t)limit;", "- for (size_t i = 0; i < kv_size(marks); i++) {", "-/// reverse can be set to control the order of the array", "- if (reverse) {", "- -- prevrange with limit", "+ -- reverse with limit" ]
[ 46, 48, 69, 87, 109, 143, 188, 189 ]
{ "additions": 62, "author": "neovim-backports[bot]", "deletions": 41, "html_url": "https://github.com/neovim/neovim/pull/33569", "issue_id": 33569, "merged_at": "2025-04-21T23:49:27Z", "omission_probability": 0.1, "pr_number": 33569, "repo": "neovim/neovim", "title": "fix(api): wrong return value with reverse range and overlap", "total_changes": 103 }
369
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 4d368c64266ed4..5f4fdf54c2e89e 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -2777,8 +2777,11 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) < - If `end` is less than `start`, traversal works backwards. (Useful with - `limit`, to get the first marks prior to a given position.) + If `end` is less than `start`, marks are returned in reverse order. + (Useful with `limit`, to get the first marks prior to a given position.) + + Note: For a reverse range, `limit` does not actually affect the traversed + range, just how many marks are returned Note: when using extmark ranges (marks with a end_row/end_col position) the `overlap` option might be useful. Otherwise only the start position of diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index ece3c1854b36ad..27b306066da9dc 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -369,8 +369,11 @@ function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end --- vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) --- ``` --- ---- If `end` is less than `start`, traversal works backwards. (Useful ---- with `limit`, to get the first marks prior to a given position.) +--- If `end` is less than `start`, marks are returned in reverse order. +--- (Useful with `limit`, to get the first marks prior to a given position.) +--- +--- Note: For a reverse range, `limit` does not actually affect the traversed +--- range, just how many marks are returned --- --- Note: when using extmark ranges (marks with a end_row/end_col position) --- the `overlap` option might be useful. Otherwise only the start position diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index 95f2167c03f8a0..ee9d5d80678b0a 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -241,8 +241,11 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id, /// vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) /// ``` /// -/// If `end` is less than `start`, traversal works backwards. (Useful -/// with `limit`, to get the first marks prior to a given position.) +/// If `end` is less than `start`, marks are returned in reverse order. +/// (Useful with `limit`, to get the first marks prior to a given position.) +/// +/// Note: For a reverse range, `limit` does not actually affect the traversed +/// range, just how many marks are returned /// /// Note: when using extmark ranges (marks with a end_row/end_col position) /// the `overlap` option might be useful. Otherwise only the start position @@ -327,8 +330,6 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e limit = INT64_MAX; } - bool reverse = false; - int l_row; colnr_T l_col; if (!extmark_get_index_from_obj(buf, ns_id, start, &l_row, &l_col, err)) { @@ -341,17 +342,31 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e return rv; } - if (l_row > u_row || (l_row == u_row && l_col > u_col)) { - reverse = true; + size_t rv_limit = (size_t)limit; + bool reverse = l_row > u_row || (l_row == u_row && l_col > u_col); + if (reverse) { + limit = INT64_MAX; // limit the return value instead + int row = l_row; + l_row = u_row; + u_row = row; + colnr_T col = l_col; + l_col = u_col; + u_col = col; } // note: ns_id=-1 allowed, represented as UINT32_MAX ExtmarkInfoArray marks = extmark_get(buf, (uint32_t)ns_id, l_row, l_col, u_row, - u_col, (int64_t)limit, reverse, type, opts->overlap); + u_col, (int64_t)limit, type, opts->overlap); - rv = arena_array(arena, kv_size(marks)); - for (size_t i = 0; i < kv_size(marks); i++) { - ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + rv = arena_array(arena, MIN(kv_size(marks), rv_limit)); + if (reverse) { + for (int i = (int)kv_size(marks) - 1; i >= 0 && kv_size(rv) < rv_limit; i--) { + ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + } + } else { + for (size_t i = 0; i < kv_size(marks); i++) { + ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena))); + } } kv_destroy(marks); diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index cad0f71941074e..8302c3a0b2ac22 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -256,11 +256,9 @@ bool extmark_clear(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_r /// /// if upper_lnum or upper_col are negative the buffer /// will be searched to the start, or end -/// reverse can be set to control the order of the array /// amount = amount of marks to find or INT64_MAX for all ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row, - colnr_T u_col, int64_t amount, bool reverse, ExtmarkType type_filter, - bool overlap) + colnr_T u_col, int64_t amount, ExtmarkType type_filter, bool overlap) { ExtmarkInfoArray array = KV_INITIAL_VALUE; MarkTreeIter itr[1]; @@ -278,29 +276,21 @@ ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_co } else { // Find all the marks beginning with the start position marktree_itr_get_ext(buf->b_marktree, MTPos(l_row, l_col), - itr, reverse, false, NULL, NULL); + itr, false, false, NULL, NULL); } - int order = reverse ? -1 : 1; while ((int64_t)kv_size(array) < amount) { MTKey mark = marktree_itr_current(itr); if (mark.pos.row < 0 - || (mark.pos.row - u_row) * order > 0 - || (mark.pos.row == u_row && (mark.pos.col - u_col) * order > 0)) { + || (mark.pos.row > u_row) + || (mark.pos.row == u_row && mark.pos.col > u_col)) { break; } - if (mt_end(mark)) { - goto next_mark; - } - - MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); - push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); -next_mark: - if (reverse) { - marktree_itr_prev(buf->b_marktree, itr); - } else { - marktree_itr_next(buf->b_marktree, itr); + if (!mt_end(mark)) { + MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); + push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); } + marktree_itr_next(buf->b_marktree, itr); } return array; } diff --git a/test/functional/api/extmark_spec.lua b/test/functional/api/extmark_spec.lua index 31bb9841dcb403..1d030a2ee3e3c4 100644 --- a/test/functional/api/extmark_spec.lua +++ b/test/functional/api/extmark_spec.lua @@ -331,30 +331,30 @@ describe('API/extmarks', function() rv = get_extmarks(ns, lower, upper) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) - -- prev with mark id + -- reverse with mark id rv = get_extmarks(ns, marks[3], { 0, 0 }, { limit = 1 }) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) rv = get_extmarks(ns, marks[2], { 0, 0 }, { limit = 1 }) eq({ { marks[2], positions[2][1], positions[2][2] } }, rv) - -- prev with positional when mark exists at position + -- reverse with positional when mark exists at position rv = get_extmarks(ns, positions[3], { 0, 0 }, { limit = 1 }) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) - -- prev with positional index (no mark at position) + -- reverse with positional index (no mark at position) rv = get_extmarks(ns, { positions[1][1], positions[1][2] + 1 }, { 0, 0 }, { limit = 1 }) eq({ { marks[1], positions[1][1], positions[1][2] } }, rv) - -- prev with Extremity index + -- reverse with Extremity index rv = get_extmarks(ns, { -1, -1 }, { 0, 0 }, { limit = 1 }) eq({ { marks[3], positions[3][1], positions[3][2] } }, rv) - -- prevrange with mark id + -- reverse with mark id rv = get_extmarks(ns, marks[3], marks[1]) eq({ marks[3], positions[3][1], positions[3][2] }, rv[1]) eq({ marks[2], positions[2][1], positions[2][2] }, rv[2]) eq({ marks[1], positions[1][1], positions[1][2] }, rv[3]) - -- prevrange with limit + -- reverse with limit rv = get_extmarks(ns, marks[3], marks[1], { limit = 2 }) eq(2, #rv) - -- prevrange with positional when mark exists at position + -- reverse with positional when mark exists at position rv = get_extmarks(ns, positions[3], positions[1]) eq({ { marks[3], positions[3][1], positions[3][2] }, @@ -363,7 +363,7 @@ describe('API/extmarks', function() }, rv) rv = get_extmarks(ns, positions[2], positions[1]) eq(2, #rv) - -- prevrange with positional index (no mark at position) + -- reverse with positional index (no mark at position) lower = { positions[2][1], positions[2][2] + 1 } upper = { positions[3][1], positions[3][2] + 1 } rv = get_extmarks(ns, upper, lower) @@ -372,7 +372,7 @@ describe('API/extmarks', function() upper = { positions[3][1], positions[3][2] + 2 } rv = get_extmarks(ns, upper, lower) eq({}, rv) - -- prevrange with extremity index + -- reverse with extremity index lower = { 0, 0 } upper = { positions[2][1], positions[2][2] - 1 } rv = get_extmarks(ns, upper, lower) @@ -428,6 +428,14 @@ describe('API/extmarks', function() set_extmark(ns, marks[3], 0, 2) -- check is inclusive local rv = get_extmarks(ns, { 2, 3 }, { 0, 2 }) eq({ { marks[1], 2, 1 }, { marks[2], 1, 4 }, { marks[3], 0, 2 } }, rv) + -- doesn't include paired marks whose start pos > lower bound twice + -- and returns mark overlapping start pos but not end pos + local m1 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 4 }) + local m2 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 2 }) + local m3 = set_extmark(ns, nil, 1, 0, { end_row = 1, end_col = 4 }) + local m4 = set_extmark(ns, nil, 1, 2, { end_row = 1, end_col = 4 }) + rv = get_extmarks(ns, { 1, 3 }, { 1, 2 }, { overlap = true }) + eq({ { m4, 1, 2 }, { m3, 1, 0 }, { m2, 0, 0 }, { m1, 0, 0 } }, rv) end) it('get_marks limit=0 returns nothing', function() @@ -973,7 +981,7 @@ describe('API/extmarks', function() eq(1, #rv) rv = get_extmarks(ns2, { 0, 0 }, positions[2], { limit = 1 }) eq(1, #rv) - -- get_prev (limit set) + -- reverse (limit set) rv = get_extmarks(ns, positions[1], { 0, 0 }, { limit = 1 }) eq(1, #rv) rv = get_extmarks(ns2, positions[1], { 0, 0 }, { limit = 1 }) @@ -984,7 +992,7 @@ describe('API/extmarks', function() eq(2, #rv) rv = get_extmarks(ns2, positions[1], positions[2]) eq(2, #rv) - -- get_prev (no limit) + -- reverse (no limit) rv = get_extmarks(ns, positions[2], positions[1]) eq(2, #rv) rv = get_extmarks(ns2, positions[2], positions[1])
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt index 4d368c64266ed4..5f4fdf54c2e89e 100644 --- a/runtime/doc/api.txt +++ b/runtime/doc/api.txt @@ -2777,8 +2777,11 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts}) vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) < - If `end` is less than `start`, traversal works backwards. (Useful with - `limit`, to get the first marks prior to a given position.) + If `end` is less than `start`, marks are returned in reverse order. + (Useful with `limit`, to get the first marks prior to a given position.) + + Note: For a reverse range, `limit` does not actually affect the traversed + range, just how many marks are returned Note: when using extmark ranges (marks with a end_row/end_col position) the `overlap` option might be useful. Otherwise only the start position of diff --git a/runtime/lua/vim/_meta/api.lua b/runtime/lua/vim/_meta/api.lua index ece3c1854b36ad..27b306066da9dc 100644 --- a/runtime/lua/vim/_meta/api.lua +++ b/runtime/lua/vim/_meta/api.lua @@ -369,8 +369,11 @@ function vim.api.nvim_buf_get_extmark_by_id(buffer, ns_id, id, opts) end --- vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) --- ``` ---- If `end` is less than `start`, traversal works backwards. (Useful ---- with `limit`, to get the first marks prior to a given position.) +--- If `end` is less than `start`, marks are returned in reverse order. +--- (Useful with `limit`, to get the first marks prior to a given position.) +--- +--- Note: For a reverse range, `limit` does not actually affect the traversed +--- range, just how many marks are returned --- Note: when using extmark ranges (marks with a end_row/end_col position) --- the `overlap` option might be useful. Otherwise only the start position diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c index 95f2167c03f8a0..ee9d5d80678b0a 100644 --- a/src/nvim/api/extmark.c +++ b/src/nvim/api/extmark.c @@ -241,8 +241,11 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id, /// vim.api.nvim_buf_get_extmarks(0, my_ns, {0,0}, {-1,-1}, {}) /// ``` -/// If `end` is less than `start`, traversal works backwards. (Useful -/// with `limit`, to get the first marks prior to a given position.) +/// If `end` is less than `start`, marks are returned in reverse order. +/// (Useful with `limit`, to get the first marks prior to a given position.) +/// +/// range, just how many marks are returned /// Note: when using extmark ranges (marks with a end_row/end_col position) /// the `overlap` option might be useful. Otherwise only the start position @@ -327,8 +330,6 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e limit = INT64_MAX; - bool reverse = false; int l_row; colnr_T l_col; if (!extmark_get_index_from_obj(buf, ns_id, start, &l_row, &l_col, err)) { @@ -341,17 +342,31 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e return rv; - if (l_row > u_row || (l_row == u_row && l_col > u_col)) { - reverse = true; + size_t rv_limit = (size_t)limit; + bool reverse = l_row > u_row || (l_row == u_row && l_col > u_col); + limit = INT64_MAX; // limit the return value instead + int row = l_row; + l_row = u_row; + u_row = row; + colnr_T col = l_col; + l_col = u_col; + u_col = col; // note: ns_id=-1 allowed, represented as UINT32_MAX ExtmarkInfoArray marks = extmark_get(buf, (uint32_t)ns_id, l_row, l_col, u_row, - u_col, (int64_t)limit, reverse, type, opts->overlap); + u_col, (int64_t)limit, type, opts->overlap); - rv = arena_array(arena, kv_size(marks)); - for (size_t i = 0; i < kv_size(marks); i++) { + rv = arena_array(arena, MIN(kv_size(marks), rv_limit)); + for (int i = (int)kv_size(marks) - 1; i >= 0 && kv_size(rv) < rv_limit; i--) { + } else { + for (size_t i = 0; i < kv_size(marks); i++) { kv_destroy(marks); diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c index cad0f71941074e..8302c3a0b2ac22 100644 --- a/src/nvim/extmark.c +++ b/src/nvim/extmark.c @@ -256,11 +256,9 @@ bool extmark_clear(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_r /// if upper_lnum or upper_col are negative the buffer /// will be searched to the start, or end -/// reverse can be set to control the order of the array /// amount = amount of marks to find or INT64_MAX for all ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row, - bool overlap) + colnr_T u_col, int64_t amount, ExtmarkType type_filter, bool overlap) { ExtmarkInfoArray array = KV_INITIAL_VALUE; MarkTreeIter itr[1]; @@ -278,29 +276,21 @@ ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_co } else { // Find all the marks beginning with the start position marktree_itr_get_ext(buf->b_marktree, MTPos(l_row, l_col), - itr, reverse, false, NULL, NULL); while ((int64_t)kv_size(array) < amount) { MTKey mark = marktree_itr_current(itr); if (mark.pos.row < 0 - || (mark.pos.row - u_row) * order > 0 - || (mark.pos.row == u_row && (mark.pos.col - u_col) * order > 0)) { + || (mark.pos.row > u_row) + || (mark.pos.row == u_row && mark.pos.col > u_col)) { break; - if (mt_end(mark)) { - goto next_mark; - } - MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); - push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); -next_mark: - marktree_itr_prev(buf->b_marktree, itr); - } else { - marktree_itr_next(buf->b_marktree, itr); + if (!mt_end(mark)) { + MTKey end = marktree_get_alt(buf->b_marktree, mark, NULL); + push_mark(&array, ns_id, type_filter, mtpair_from(mark, end)); + marktree_itr_next(buf->b_marktree, itr); return array; } diff --git a/test/functional/api/extmark_spec.lua b/test/functional/api/extmark_spec.lua index 31bb9841dcb403..1d030a2ee3e3c4 100644 --- a/test/functional/api/extmark_spec.lua +++ b/test/functional/api/extmark_spec.lua @@ -331,30 +331,30 @@ describe('API/extmarks', function() rv = get_extmarks(ns, lower, upper) - -- prev with mark id rv = get_extmarks(ns, marks[3], { 0, 0 }, { limit = 1 }) rv = get_extmarks(ns, marks[2], { 0, 0 }, { limit = 1 }) eq({ { marks[2], positions[2][1], positions[2][2] } }, rv) - -- prev with positional when mark exists at position rv = get_extmarks(ns, positions[3], { 0, 0 }, { limit = 1 }) - -- prev with positional index (no mark at position) rv = get_extmarks(ns, { positions[1][1], positions[1][2] + 1 }, { 0, 0 }, { limit = 1 }) eq({ { marks[1], positions[1][1], positions[1][2] } }, rv) + -- reverse with Extremity index rv = get_extmarks(ns, { -1, -1 }, { 0, 0 }, { limit = 1 }) - -- prevrange with mark id rv = get_extmarks(ns, marks[3], marks[1]) eq({ marks[3], positions[3][1], positions[3][2] }, rv[1]) eq({ marks[2], positions[2][1], positions[2][2] }, rv[2]) eq({ marks[1], positions[1][1], positions[1][2] }, rv[3]) - -- prevrange with limit + -- reverse with limit rv = get_extmarks(ns, marks[3], marks[1], { limit = 2 }) - -- prevrange with positional when mark exists at position rv = get_extmarks(ns, positions[3], positions[1]) eq({ { marks[3], positions[3][1], positions[3][2] }, @@ -363,7 +363,7 @@ describe('API/extmarks', function() }, rv) - -- prevrange with positional index (no mark at position) lower = { positions[2][1], positions[2][2] + 1 } upper = { positions[3][1], positions[3][2] + 1 } @@ -372,7 +372,7 @@ describe('API/extmarks', function() upper = { positions[3][1], positions[3][2] + 2 } eq({}, rv) - -- prevrange with extremity index + -- reverse with extremity index lower = { 0, 0 } upper = { positions[2][1], positions[2][2] - 1 } @@ -428,6 +428,14 @@ describe('API/extmarks', function() set_extmark(ns, marks[3], 0, 2) -- check is inclusive local rv = get_extmarks(ns, { 2, 3 }, { 0, 2 }) eq({ { marks[1], 2, 1 }, { marks[2], 1, 4 }, { marks[3], 0, 2 } }, rv) + -- doesn't include paired marks whose start pos > lower bound twice + -- and returns mark overlapping start pos but not end pos + local m1 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 4 }) + local m2 = set_extmark(ns, nil, 0, 0, { end_row = 1, end_col = 2 }) + local m3 = set_extmark(ns, nil, 1, 0, { end_row = 1, end_col = 4 }) + local m4 = set_extmark(ns, nil, 1, 2, { end_row = 1, end_col = 4 }) + rv = get_extmarks(ns, { 1, 3 }, { 1, 2 }, { overlap = true }) end) it('get_marks limit=0 returns nothing', function() @@ -973,7 +981,7 @@ describe('API/extmarks', function() rv = get_extmarks(ns2, { 0, 0 }, positions[2], { limit = 1 }) - -- get_prev (limit set) + -- reverse (limit set) rv = get_extmarks(ns, positions[1], { 0, 0 }, { limit = 1 }) rv = get_extmarks(ns2, positions[1], { 0, 0 }, { limit = 1 }) @@ -984,7 +992,7 @@ describe('API/extmarks', function() rv = get_extmarks(ns2, positions[1], positions[2]) + -- reverse (no limit) rv = get_extmarks(ns2, positions[2], positions[1])
[ "+/// Note: For a reverse range, `limit` does not actually affect the traversed", "- ADD_C(rv, ARRAY_OBJ(extmark_to_array(kv_A(marks, i), true, details, hl_name, arena)));", "- colnr_T u_col, int64_t amount, bool reverse, ExtmarkType type_filter,", "+ itr, false, false, NULL, NULL);", "- int order = reverse ? -1 : 1;", "- if (reverse) {", "- -- prev with Extremity index", "+ eq({ { m4, 1, 2 }, { m3, 1, 0 }, { m2, 0, 0 }, { m1, 0, 0 } }, rv)", "- -- get_prev (no limit)" ]
[ 49, 88, 112, 123, 126, 143, 177, 226, 243 ]
{ "additions": 62, "author": "luukvbaal", "deletions": 41, "html_url": "https://github.com/neovim/neovim/pull/32956", "issue_id": 32956, "merged_at": "2025-04-21T23:18:03Z", "omission_probability": 0.1, "pr_number": 32956, "repo": "neovim/neovim", "title": "fix(api): wrong return value with reverse range and overlap", "total_changes": 103 }
370
diff --git a/src/nvim/option.c b/src/nvim/option.c index 3d4c2e65f9b3fb..3a7a8bf16742c2 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1277,10 +1277,10 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * if (*did_show) { msg_putchar('\n'); // cursor below last one } else { + msg_ext_set_kind("list_cmd"); gotocmdline(true); // cursor at status line *did_show = true; // remember that we did a line } - msg_ext_set_kind("list_cmd"); showoneopt(&options[opt_idx], opt_flags); if (p_verbose > 0) { diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index a1f6e5549475d2..96e67982ac7b42 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -1605,12 +1605,11 @@ stack traceback: it('g< mapping shows recent messages', function() command('echo "foo" | echo "bar"') - local s1 = [[ - ^ | - {1:~ }|*4 - ]] screen:expect({ - grid = s1, + grid = [[ + ^ | + {1:~ }|*4 + ]], messages = { { content = { { 'bar' } }, @@ -1644,6 +1643,23 @@ stack traceback: }, }) end) + + it('single event for multiple :set options', function() + command('set sw ts sts') + screen:expect({ + grid = [[ + ^ | + {1:~ }|*4 + ]], + messages = { + { + content = { { ' shiftwidth=8\n tabstop=8\n softtabstop=0' } }, + history = false, + kind = 'list_cmd', + }, + }, + }) + end) end) describe('ui/builtin messages', function()
diff --git a/src/nvim/option.c b/src/nvim/option.c index 3d4c2e65f9b3fb..3a7a8bf16742c2 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1277,10 +1277,10 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * if (*did_show) { msg_putchar('\n'); // cursor below last one } else { + msg_ext_set_kind("list_cmd"); gotocmdline(true); // cursor at status line *did_show = true; // remember that we did a line } - msg_ext_set_kind("list_cmd"); showoneopt(&options[opt_idx], opt_flags); if (p_verbose > 0) { diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index a1f6e5549475d2..96e67982ac7b42 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -1605,12 +1605,11 @@ stack traceback: it('g< mapping shows recent messages', function() command('echo "foo" | echo "bar"') - local s1 = [[ - ^ | - {1:~ }|*4 - ]] screen:expect({ - grid = s1, messages = { { content = { { 'bar' } }, @@ -1644,6 +1643,23 @@ stack traceback: }, }) end) + + it('single event for multiple :set options', function() + command('set sw ts sts') + screen:expect({ + messages = { + { + content = { { ' shiftwidth=8\n tabstop=8\n softtabstop=0' } }, + history = false, + kind = 'list_cmd', + }, + }) + end) end) describe('ui/builtin messages', function()
[ "+ }," ]
[ 55 ]
{ "additions": 22, "author": "neovim-backports[bot]", "deletions": 6, "html_url": "https://github.com/neovim/neovim/pull/33568", "issue_id": 33568, "merged_at": "2025-04-21T16:23:38Z", "omission_probability": 0.1, "pr_number": 33568, "repo": "neovim/neovim", "title": "fix(messages): single msg_show event for multiple :set options", "total_changes": 28 }
371
diff --git a/src/nvim/option.c b/src/nvim/option.c index 643ac24e43c0fc..5299d2a237127b 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1282,10 +1282,10 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * if (*did_show) { msg_putchar('\n'); // cursor below last one } else { + msg_ext_set_kind("list_cmd"); gotocmdline(true); // cursor at status line *did_show = true; // remember that we did a line } - msg_ext_set_kind("list_cmd"); showoneopt(&options[opt_idx], opt_flags); if (p_verbose > 0) { diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index 5b40457df94280..fbd05cd9b8eccd 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -1605,12 +1605,11 @@ stack traceback: it('g< mapping shows recent messages', function() command('echo "foo" | echo "bar"') - local s1 = [[ - ^ | - {1:~ }|*4 - ]] screen:expect({ - grid = s1, + grid = [[ + ^ | + {1:~ }|*4 + ]], messages = { { content = { { 'bar' } }, @@ -1644,6 +1643,23 @@ stack traceback: }, }) end) + + it('single event for multiple :set options', function() + command('set sw ts sts') + screen:expect({ + grid = [[ + ^ | + {1:~ }|*4 + ]], + messages = { + { + content = { { ' shiftwidth=8\n tabstop=8\n softtabstop=0' } }, + history = false, + kind = 'list_cmd', + }, + }, + }) + end) end) describe('ui/builtin messages', function()
diff --git a/src/nvim/option.c b/src/nvim/option.c index 643ac24e43c0fc..5299d2a237127b 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1282,10 +1282,10 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * if (*did_show) { msg_putchar('\n'); // cursor below last one } else { + msg_ext_set_kind("list_cmd"); gotocmdline(true); // cursor at status line *did_show = true; // remember that we did a line } - msg_ext_set_kind("list_cmd"); showoneopt(&options[opt_idx], opt_flags); if (p_verbose > 0) { diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua index 5b40457df94280..fbd05cd9b8eccd 100644 --- a/test/functional/ui/messages_spec.lua +++ b/test/functional/ui/messages_spec.lua @@ -1605,12 +1605,11 @@ stack traceback: it('g< mapping shows recent messages', function() command('echo "foo" | echo "bar"') - local s1 = [[ - ^ | - {1:~ }|*4 - ]] screen:expect({ - grid = s1, messages = { { content = { { 'bar' } }, @@ -1644,6 +1643,23 @@ stack traceback: }, }) end) + it('single event for multiple :set options', function() + command('set sw ts sts') + screen:expect({ + messages = { + { + content = { { ' shiftwidth=8\n tabstop=8\n softtabstop=0' } }, + history = false, + kind = 'list_cmd', + }, + }, + }) + end) end) describe('ui/builtin messages', function()
[ "+" ]
[ 41 ]
{ "additions": 22, "author": "luukvbaal", "deletions": 6, "html_url": "https://github.com/neovim/neovim/pull/33555", "issue_id": 33555, "merged_at": "2025-04-21T14:51:47Z", "omission_probability": 0.1, "pr_number": 33555, "repo": "neovim/neovim", "title": "fix(messages): single msg_show event for multiple :set options", "total_changes": 28 }
372
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index c580c55a5e97a1..2dcf915428e84e 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -1031,16 +1031,13 @@ vim.stricmp({a}, {b}) *vim.stricmp()* (`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is lesser than {b}, respectively. -vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* +vim.ui_attach({ns}, {opts}, {callback}) *vim.ui_attach()* WARNING: This feature is experimental/unstable. Subscribe to |ui-events|, similar to |nvim_ui_attach()| but receive events in a Lua callback. Used to implement screen elements like popupmenu or message handling in Lua. - {options} is a dict with one or more `ext_…` |ui-option|s set to true to - enable events for the respective UI element. - {callback} receives event name plus additional parameters. See |ui-popupmenu| and the sections below for event format for respective events. @@ -1073,16 +1070,21 @@ vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* < Parameters: ~ - • {ns} (`integer`) - • {options} (`table<string, any>`) - • {callback} (`fun()`) + • {ns} (`integer`) Namespace ID + • {opts} (`table<string, any>`) Optional parameters. + • {ext_…}? (`boolean`) Any of |ui-ext-options|, if true + enable events for the respective UI element. + • {set_cmdheight}? (`boolean`) If false, avoid setting + 'cmdheight' to 0 when `ext_messages` is enabled. + • {callback} (`fun(event: string, ...)`) Function called for each UI + event vim.ui_detach({ns}) *vim.ui_detach()* Detach a callback previously attached with |vim.ui_attach()| for the given namespace {ns}. Parameters: ~ - • {ns} (`integer`) + • {ns} (`integer`) Namespace ID vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* Wait for {time} in milliseconds until {callback} returns `true`. diff --git a/runtime/lua/vim/_meta/builtin.lua b/runtime/lua/vim/_meta/builtin.lua index 2d5975b9770924..ef7ec0bee3a920 100644 --- a/runtime/lua/vim/_meta/builtin.lua +++ b/runtime/lua/vim/_meta/builtin.lua @@ -226,9 +226,6 @@ function vim.wait(time, callback, interval, fast_only) end --- Subscribe to |ui-events|, similar to |nvim_ui_attach()| but receive events in a Lua callback. --- Used to implement screen elements like popupmenu or message handling in Lua. --- ---- {options} is a dict with one or more `ext_…` |ui-option|s set to true to enable events for ---- the respective UI element. ---- --- {callback} receives event name plus additional parameters. See |ui-popupmenu| --- and the sections below for event format for respective events. --- @@ -263,12 +260,16 @@ function vim.wait(time, callback, interval, fast_only) end --- --- @since 0 --- ---- @param ns integer ---- @param options table<string, any> ---- @param callback fun() -function vim.ui_attach(ns, options, callback) end +--- @param ns integer Namespace ID +--- @param opts table<string, any> Optional parameters. +--- - {ext_…}? (`boolean`) Any of |ui-ext-options|, if true +--- enable events for the respective UI element. +--- - {set_cmdheight}? (`boolean`) If false, avoid setting +--- 'cmdheight' to 0 when `ext_messages` is enabled. +--- @param callback fun(event: string, ...) Function called for each UI event +function vim.ui_attach(ns, opts, callback) end --- Detach a callback previously attached with |vim.ui_attach()| for the --- given namespace {ns}. ---- @param ns integer +--- @param ns integer Namespace ID function vim.ui_detach(ns) end diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 5dac24fbc03964..8018d15bc88edb 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -682,7 +682,7 @@ static int nlua_ui_attach(lua_State *lstate) return luaL_error(lstate, "invalid ns_id"); } if (!lua_istable(lstate, 2)) { - return luaL_error(lstate, "ext_widgets must be a table"); + return luaL_error(lstate, "opts must be a table"); } if (!lua_isfunction(lstate, 3)) { return luaL_error(lstate, "callback must be a Lua function"); @@ -699,13 +699,18 @@ static int nlua_ui_attach(lua_State *lstate) const char *s = lua_tolstring(lstate, -2, &len); bool val = lua_toboolean(lstate, -1); - for (size_t i = 0; i < kUIGlobalCount; i++) { - if (strequal(s, ui_ext_names[i])) { - if (val) { - tbl_has_true_val = true; + if (strequal(s, "set_cmdheight")) { + ui_refresh_cmdheight = val; + goto ok; + } else { + for (size_t i = 0; i < kUIGlobalCount; i++) { + if (strequal(s, ui_ext_names[i])) { + if (val) { + tbl_has_true_val = true; + } + ext_widgets[i] = val; + goto ok; } - ext_widgets[i] = val; - goto ok; } } @@ -715,11 +720,12 @@ static int nlua_ui_attach(lua_State *lstate) } if (!tbl_has_true_val) { - return luaL_error(lstate, "ext_widgets table must contain at least one 'true' value"); + return luaL_error(lstate, "opts table must contain at least one 'true' ext_widget"); } LuaRef ui_event_cb = nlua_ref_global(lstate, 3); ui_add_cb(ns_id, ui_event_cb, ext_widgets); + ui_refresh_cmdheight = true; return 0; } diff --git a/src/nvim/ui.c b/src/nvim/ui.c index 9a36588b56c522..c2983430a044a5 100644 --- a/src/nvim/ui.c +++ b/src/nvim/ui.c @@ -223,9 +223,11 @@ void ui_refresh(void) // Reset 'cmdheight' for all tabpages when ext_messages toggles. if (had_message != ui_ext[kUIMessages]) { - set_option_value(kOptCmdheight, NUMBER_OPTVAL(had_message), 0); - FOR_ALL_TABS(tp) { - tp->tp_ch_used = had_message; + if (ui_refresh_cmdheight) { + set_option_value(kOptCmdheight, NUMBER_OPTVAL(had_message), 0); + FOR_ALL_TABS(tp) { + tp->tp_ch_used = had_message; + } } msg_scroll_flush(); } diff --git a/src/nvim/ui.h b/src/nvim/ui.h index 4aeb8ffda99d0f..c45b367c4ded2f 100644 --- a/src/nvim/ui.h +++ b/src/nvim/ui.h @@ -21,3 +21,4 @@ EXTERN Array noargs INIT(= ARRAY_DICT_INIT); // vim.ui_attach() namespace of currently executed callback. EXTERN uint32_t ui_event_ns_id INIT( = 0); EXTERN MultiQueue *resize_events INIT( = NULL); +EXTERN bool ui_refresh_cmdheight INIT( = true); diff --git a/test/functional/lua/ui_event_spec.lua b/test/functional/lua/ui_event_spec.lua index 096280f56399d1..853bee61c27728 100644 --- a/test/functional/lua/ui_event_spec.lua +++ b/test/functional/lua/ui_event_spec.lua @@ -162,6 +162,11 @@ describe('vim.ui_attach', function() eq(0, n.api.nvim_get_option_value('cmdheight', {})) end) + it("can attach ext_messages without changing 'cmdheight'", function() + exec_lua('vim.ui_attach(ns, { ext_messages = true, set_cmdheight = false }, on_event)') + eq(1, n.api.nvim_get_option_value('cmdheight', {})) + end) + it('avoids recursive flushing and invalid memory access with :redraw', function() exec_lua([[ _G.cmdline = 0
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt index c580c55a5e97a1..2dcf915428e84e 100644 --- a/runtime/doc/lua.txt +++ b/runtime/doc/lua.txt @@ -1031,16 +1031,13 @@ vim.stricmp({a}, {b}) *vim.stricmp()* (`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is lesser than {b}, respectively. -vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* +vim.ui_attach({ns}, {opts}, {callback}) *vim.ui_attach()* WARNING: This feature is experimental/unstable. Subscribe to |ui-events|, similar to |nvim_ui_attach()| but receive events in a Lua callback. Used to implement screen elements like popupmenu or message handling in Lua. - {options} is a dict with one or more `ext_…` |ui-option|s set to true to - enable events for the respective UI element. - {callback} receives event name plus additional parameters. See |ui-popupmenu| and the sections below for event format for respective events. @@ -1073,16 +1070,21 @@ vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()* < - • {ns} (`integer`) - • {options} (`table<string, any>`) - • {callback} (`fun()`) + • {ns} (`integer`) Namespace ID + • {opts} (`table<string, any>`) Optional parameters. + • {ext_…}? (`boolean`) Any of |ui-ext-options|, if true + enable events for the respective UI element. + • {set_cmdheight}? (`boolean`) If false, avoid setting + 'cmdheight' to 0 when `ext_messages` is enabled. + • {callback} (`fun(event: string, ...)`) Function called for each UI + event vim.ui_detach({ns}) *vim.ui_detach()* Detach a callback previously attached with |vim.ui_attach()| for the given namespace {ns}. - • {ns} (`integer`) + • {ns} (`integer`) Namespace ID vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()* Wait for {time} in milliseconds until {callback} returns `true`. diff --git a/runtime/lua/vim/_meta/builtin.lua b/runtime/lua/vim/_meta/builtin.lua index 2d5975b9770924..ef7ec0bee3a920 100644 --- a/runtime/lua/vim/_meta/builtin.lua +++ b/runtime/lua/vim/_meta/builtin.lua @@ -226,9 +226,6 @@ function vim.wait(time, callback, interval, fast_only) end --- Subscribe to |ui-events|, similar to |nvim_ui_attach()| but receive events in a Lua callback. --- Used to implement screen elements like popupmenu or message handling in Lua. ---- {options} is a dict with one or more `ext_…` |ui-option|s set to true to enable events for ---- the respective UI element. ---- --- {callback} receives event name plus additional parameters. See |ui-popupmenu| --- and the sections below for event format for respective events. @@ -263,12 +260,16 @@ function vim.wait(time, callback, interval, fast_only) end --- @since 0 ---- @param options table<string, any> ---- @param callback fun() -function vim.ui_attach(ns, options, callback) end +--- @param opts table<string, any> Optional parameters. +--- - {ext_…}? (`boolean`) Any of |ui-ext-options|, if true +--- - {set_cmdheight}? (`boolean`) If false, avoid setting +--- 'cmdheight' to 0 when `ext_messages` is enabled. +--- @param callback fun(event: string, ...) Function called for each UI event +function vim.ui_attach(ns, opts, callback) end --- Detach a callback previously attached with |vim.ui_attach()| for the --- given namespace {ns}. function vim.ui_detach(ns) end diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 5dac24fbc03964..8018d15bc88edb 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -682,7 +682,7 @@ static int nlua_ui_attach(lua_State *lstate) return luaL_error(lstate, "invalid ns_id"); if (!lua_istable(lstate, 2)) { - return luaL_error(lstate, "ext_widgets must be a table"); + return luaL_error(lstate, "opts must be a table"); if (!lua_isfunction(lstate, 3)) { return luaL_error(lstate, "callback must be a Lua function"); @@ -699,13 +699,18 @@ static int nlua_ui_attach(lua_State *lstate) const char *s = lua_tolstring(lstate, -2, &len); bool val = lua_toboolean(lstate, -1); - for (size_t i = 0; i < kUIGlobalCount; i++) { - if (strequal(s, ui_ext_names[i])) { - if (val) { - tbl_has_true_val = true; + if (strequal(s, "set_cmdheight")) { + ui_refresh_cmdheight = val; + goto ok; + for (size_t i = 0; i < kUIGlobalCount; i++) { + if (strequal(s, ui_ext_names[i])) { + if (val) { + tbl_has_true_val = true; + } + ext_widgets[i] = val; + goto ok; } } @@ -715,11 +720,12 @@ static int nlua_ui_attach(lua_State *lstate) if (!tbl_has_true_val) { - return luaL_error(lstate, "ext_widgets table must contain at least one 'true' value"); + return luaL_error(lstate, "opts table must contain at least one 'true' ext_widget"); LuaRef ui_event_cb = nlua_ref_global(lstate, 3); ui_add_cb(ns_id, ui_event_cb, ext_widgets); + ui_refresh_cmdheight = true; return 0; } diff --git a/src/nvim/ui.c b/src/nvim/ui.c index 9a36588b56c522..c2983430a044a5 100644 --- a/src/nvim/ui.c +++ b/src/nvim/ui.c @@ -223,9 +223,11 @@ void ui_refresh(void) // Reset 'cmdheight' for all tabpages when ext_messages toggles. if (had_message != ui_ext[kUIMessages]) { - set_option_value(kOptCmdheight, NUMBER_OPTVAL(had_message), 0); - FOR_ALL_TABS(tp) { - tp->tp_ch_used = had_message; + if (ui_refresh_cmdheight) { + FOR_ALL_TABS(tp) { + tp->tp_ch_used = had_message; + } msg_scroll_flush(); diff --git a/src/nvim/ui.h b/src/nvim/ui.h index 4aeb8ffda99d0f..c45b367c4ded2f 100644 --- a/src/nvim/ui.h +++ b/src/nvim/ui.h @@ -21,3 +21,4 @@ EXTERN Array noargs INIT(= ARRAY_DICT_INIT); // vim.ui_attach() namespace of currently executed callback. EXTERN uint32_t ui_event_ns_id INIT( = 0); EXTERN MultiQueue *resize_events INIT( = NULL); +EXTERN bool ui_refresh_cmdheight INIT( = true); diff --git a/test/functional/lua/ui_event_spec.lua b/test/functional/lua/ui_event_spec.lua index 096280f56399d1..853bee61c27728 100644 --- a/test/functional/lua/ui_event_spec.lua +++ b/test/functional/lua/ui_event_spec.lua @@ -162,6 +162,11 @@ describe('vim.ui_attach', function() eq(0, n.api.nvim_get_option_value('cmdheight', {})) end) + it("can attach ext_messages without changing 'cmdheight'", function() + exec_lua('vim.ui_attach(ns, { ext_messages = true, set_cmdheight = false }, on_event)') + eq(1, n.api.nvim_get_option_value('cmdheight', {})) + end) + it('avoids recursive flushing and invalid memory access with :redraw', function() exec_lua([[ _G.cmdline = 0
[ "+--- enable events for the respective UI element.", "+ } else {", "- ext_widgets[i] = val;", "- goto ok;", "+ set_option_value(kOptCmdheight, NUMBER_OPTVAL(had_message), 0);" ]
[ 73, 108, 117, 118, 148 ]
{ "additions": 44, "author": "luukvbaal", "deletions": 20, "html_url": "https://github.com/neovim/neovim/pull/33546", "issue_id": 33546, "merged_at": "2025-04-21T13:38:23Z", "omission_probability": 0.1, "pr_number": 33546, "repo": "neovim/neovim", "title": "feat(ui): avoid setting 'cmdheight' with vim.ui_attach()", "total_changes": 64 }
373
diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index e1165b6d31bdbb..82e9d0223e3fa1 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -78,10 +78,6 @@ LUA OPTIONS -• 'chistory' and 'lhistory' set size of the |quickfix-stack|. -• 'completeopt' flag "nearset" sorts completion results by distance to cursor. -• 'diffopt' `inline:` configures diff highlighting for changes within a line. -• 'pummaxwidth' sets maximum width for the completion popup menu. • 'shelltemp' defaults to "false". PLUGINS @@ -107,7 +103,6 @@ The following new features were added. API -• |vim.hl.range()| now allows multiple timed highlights • |nvim_win_text_height()| can limit the lines checked when a certain `max_height` is reached, and returns the `end_row` and `end_vcol` for which `max_height` or the calculated height is reached. @@ -140,12 +135,15 @@ LSP LUA • Lua type annotations for `vim.uv`. +• |vim.hl.range()| now allows multiple timed highlights. OPTIONS • 'autowriteall' writes all buffers upon receiving `SIGHUP`, `SIGQUIT` or `SIGTSTP`. +• 'chistory' and 'lhistory' set size of the |quickfix-stack|. • 'completefuzzycollect' enables fuzzy collection of candidates for (some) |ins-completion| modes. +• 'completeopt' flag "nearset" sorts completion results by distance to cursor. • 'diffopt' `inline:` configures diff highlighting for changes within a line. • 'pummaxwidth' sets maximum width for the completion popup menu. • 'winborder' "bold" style. @@ -189,8 +187,8 @@ CHANGED FEATURES *news-changed* These existing features changed their behavior. -• 'spellfile' location defaults to `stdpath("data").."/site/spell/"` instead of the - first writable directoy in 'runtimepath'. +• 'spellfile' location defaults to `stdpath("data").."/site/spell/"` instead of + the first writable directory in 'runtimepath'. • |vim.version.range()| doesn't exclude `to` if it is equal to `from`. ==============================================================================
diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index e1165b6d31bdbb..82e9d0223e3fa1 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -78,10 +78,6 @@ LUA -• 'chistory' and 'lhistory' set size of the |quickfix-stack|. -• 'completeopt' flag "nearset" sorts completion results by distance to cursor. -• 'diffopt' `inline:` configures diff highlighting for changes within a line. -• 'pummaxwidth' sets maximum width for the completion popup menu. • 'shelltemp' defaults to "false". PLUGINS @@ -107,7 +103,6 @@ The following new features were added. API -• |vim.hl.range()| now allows multiple timed highlights • |nvim_win_text_height()| can limit the lines checked when a certain `max_height` is reached, and returns the `end_row` and `end_vcol` for which `max_height` or the calculated height is reached. @@ -140,12 +135,15 @@ LSP LUA • Lua type annotations for `vim.uv`. +• |vim.hl.range()| now allows multiple timed highlights. • 'autowriteall' writes all buffers upon receiving `SIGHUP`, `SIGQUIT` or `SIGTSTP`. +• 'chistory' and 'lhistory' set size of the |quickfix-stack|. • 'completefuzzycollect' enables fuzzy collection of candidates for (some) |ins-completion| modes. +• 'completeopt' flag "nearset" sorts completion results by distance to cursor. • 'diffopt' `inline:` configures diff highlighting for changes within a line. • 'pummaxwidth' sets maximum width for the completion popup menu. • 'winborder' "bold" style. @@ -189,8 +187,8 @@ CHANGED FEATURES *news-changed* These existing features changed their behavior. -• 'spellfile' location defaults to `stdpath("data").."/site/spell/"` instead of the - first writable directoy in 'runtimepath'. + the first writable directory in 'runtimepath'. • |vim.version.range()| doesn't exclude `to` if it is equal to `from`. ==============================================================================
[ "+• 'spellfile' location defaults to `stdpath(\"data\")..\"/site/spell/\"` instead of" ]
[ 45 ]
{ "additions": 5, "author": "zeertzjq", "deletions": 7, "html_url": "https://github.com/neovim/neovim/pull/33566", "issue_id": 33566, "merged_at": "2025-04-21T12:20:05Z", "omission_probability": 0.1, "pr_number": 33566, "repo": "neovim/neovim", "title": "docs(news): fix incorrect placements", "total_changes": 12 }
374
diff --git a/src/nvim/edit.c b/src/nvim/edit.c index d176c98ed18805..e6ed80bba81cb2 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1638,7 +1638,7 @@ void change_indent(int type, int amount, int round, bool call_changed_bytes) // MODE_VREPLACE state needs to know what the line was like before changing if (State & VREPLACE_FLAG) { - orig_line = xstrdup(get_cursor_line_ptr()); // Deal with NULL below + orig_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len()); orig_col = curwin->w_cursor.col; } @@ -1788,7 +1788,7 @@ void change_indent(int type, int amount, int round, bool call_changed_bytes) // then put it back again the way we wanted it. if (State & VREPLACE_FLAG) { // Save new line - char *new_line = xstrdup(get_cursor_line_ptr()); + char *new_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len()); // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; diff --git a/src/nvim/indent.c b/src/nvim/indent.c index 0d06199bde745d..96c746df43d6ba 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -488,6 +488,7 @@ bool set_indent(int size, int flags) int todo = size; int ind_len = 0; // Measured in characters. char *p = oldline = get_cursor_line_ptr(); + int line_len = get_cursor_line_len() + 1; // size of the line (including the NUL) // Calculate the buffer size for the new indent, and check to see if it // isn't already set. @@ -584,8 +585,8 @@ bool set_indent(int size, int flags) p = oldline; } else { p = skipwhite(p); + line_len -= (int)(p - oldline); } - int line_len = (int)strlen(p) + 1; // If 'preserveindent' and 'expandtab' are both set keep the original // characters and allocate accordingly. We will fill the rest with spaces @@ -1028,6 +1029,7 @@ void ex_retab(exarg_T *eap) } for (linenr_T lnum = eap->line1; !got_int && lnum <= eap->line2; lnum++) { char *ptr = ml_get(lnum); + int old_len = ml_get_len(lnum); int col = 0; int64_t vcol = 0; bool did_undo = false; // called u_save for current line @@ -1071,7 +1073,6 @@ void ex_retab(exarg_T *eap) // len is actual number of white characters used len = num_spaces + num_tabs; - int old_len = (int)strlen(ptr); const int new_len = old_len - col + start_col + len + 1; if (new_len <= 0 || new_len >= MAXCOL) { emsg_text_too_long(); @@ -1099,6 +1100,7 @@ void ex_retab(exarg_T *eap) } last_line = lnum; ptr = new_line; + old_len = new_len - 1; col = start_col + len; } } @@ -1410,10 +1412,8 @@ static int lisp_match(char *p) char *word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords; while (*word != NUL) { - copy_option_part(&word, buf, sizeof(buf), ","); - int len = (int)strlen(buf); - - if ((strncmp(buf, p, (size_t)len) == 0) && ascii_iswhite_or_nul(p[len])) { + size_t len = copy_option_part(&word, buf, sizeof(buf), ","); + if ((strncmp(buf, p, len) == 0) && ascii_iswhite_or_nul(p[len])) { return true; } }
diff --git a/src/nvim/edit.c b/src/nvim/edit.c index d176c98ed18805..e6ed80bba81cb2 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1638,7 +1638,7 @@ void change_indent(int type, int amount, int round, bool call_changed_bytes) // MODE_VREPLACE state needs to know what the line was like before changing + orig_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len()); orig_col = curwin->w_cursor.col; @@ -1788,7 +1788,7 @@ void change_indent(int type, int amount, int round, bool call_changed_bytes) // then put it back again the way we wanted it. // Save new line - char *new_line = xstrdup(get_cursor_line_ptr()); + char *new_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len()); // We only put back the new line up to the cursor new_line[curwin->w_cursor.col] = NUL; diff --git a/src/nvim/indent.c b/src/nvim/indent.c index 0d06199bde745d..96c746df43d6ba 100644 --- a/src/nvim/indent.c +++ b/src/nvim/indent.c @@ -488,6 +488,7 @@ bool set_indent(int size, int flags) int todo = size; int ind_len = 0; // Measured in characters. char *p = oldline = get_cursor_line_ptr(); + int line_len = get_cursor_line_len() + 1; // size of the line (including the NUL) // Calculate the buffer size for the new indent, and check to see if it // isn't already set. @@ -584,8 +585,8 @@ bool set_indent(int size, int flags) p = oldline; } else { p = skipwhite(p); + line_len -= (int)(p - oldline); // If 'preserveindent' and 'expandtab' are both set keep the original // characters and allocate accordingly. We will fill the rest with spaces @@ -1028,6 +1029,7 @@ void ex_retab(exarg_T *eap) for (linenr_T lnum = eap->line1; !got_int && lnum <= eap->line2; lnum++) { char *ptr = ml_get(lnum); int col = 0; int64_t vcol = 0; bool did_undo = false; // called u_save for current line @@ -1071,7 +1073,6 @@ void ex_retab(exarg_T *eap) // len is actual number of white characters used len = num_spaces + num_tabs; - int old_len = (int)strlen(ptr); const int new_len = old_len - col + start_col + len + 1; if (new_len <= 0 || new_len >= MAXCOL) { emsg_text_too_long(); @@ -1099,6 +1100,7 @@ void ex_retab(exarg_T *eap) } last_line = lnum; ptr = new_line; + old_len = new_len - 1; col = start_col + len; } } @@ -1410,10 +1412,8 @@ static int lisp_match(char *p) char *word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords; while (*word != NUL) { - copy_option_part(&word, buf, sizeof(buf), ","); - + size_t len = copy_option_part(&word, buf, sizeof(buf), ","); + if ((strncmp(buf, p, len) == 0) && ascii_iswhite_or_nul(p[len])) { return true; }
[ "- orig_line = xstrdup(get_cursor_line_ptr()); // Deal with NULL below", "- int line_len = (int)strlen(p) + 1;", "+ int old_len = ml_get_len(lnum);", "- int len = (int)strlen(buf);", "- if ((strncmp(buf, p, (size_t)len) == 0) && ascii_iswhite_or_nul(p[len])) {" ]
[ 8, 40, 48, 73, 75 ]
{ "additions": 8, "author": "zeertzjq", "deletions": 8, "html_url": "https://github.com/neovim/neovim/pull/33563", "issue_id": 33563, "merged_at": "2025-04-21T11:16:29Z", "omission_probability": 0.1, "pr_number": 33563, "repo": "neovim/neovim", "title": "vim-patch:9.1.1328: too many strlen() calls in indent.c", "total_changes": 16 }
375
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index a17d6dd03d6f17..ff46716477120e 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -835,6 +835,7 @@ local extension = { nix = 'nix', norg = 'norg', nqc = 'nqc', + ['0'] = detect.nroff, ['1'] = detect.nroff, ['2'] = detect.nroff, ['3'] = detect.nroff, @@ -844,6 +845,23 @@ local extension = { ['7'] = detect.nroff, ['8'] = detect.nroff, ['9'] = detect.nroff, + ['0p'] = detect.nroff, + ['1p'] = detect.nroff, + ['3p'] = detect.nroff, + ['1x'] = detect.nroff, + ['2x'] = detect.nroff, + ['3x'] = detect.nroff, + ['4x'] = detect.nroff, + ['5x'] = detect.nroff, + ['6x'] = detect.nroff, + ['7x'] = detect.nroff, + ['8x'] = detect.nroff, + ['3am'] = detect.nroff, + ['3perl'] = detect.nroff, + ['3pm'] = detect.nroff, + ['3posix'] = detect.nroff, + ['3type'] = detect.nroff, + n = detect.nroff, roff = 'nroff', tmac = 'nroff', man = 'nroff', diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index c2674febc6893f..9cc50952d1830f 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -1170,12 +1170,17 @@ function M.news(_, bufnr) end end ---- This function checks if one of the first five lines start with a dot. In ---- that case it is probably an nroff file. +--- This function checks if one of the first five lines start with a typical +--- nroff pattern in man files. In that case it is probably an nroff file. --- @type vim.filetype.mapfn function M.nroff(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 5)) do - if line:find('^%.') then + if + matchregex( + line, + [[^\%([.']\s*\%(TH\|D[dt]\|S[Hh]\|d[es]1\?\|so\)\s\+\S\|[.'']\s*ig\>\|\%([.'']\s*\)\?\\"\)]] + ) + then return 'nroff' end end diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim index 9affc308ee1ddd..97c03726eac5c5 100644 --- a/test/old/testdir/test_filetype.vim +++ b/test/old/testdir/test_filetype.vim @@ -2918,6 +2918,30 @@ func Test_map_file() filetype off endfunc +func Test_nroff_file() + filetype on + + call writefile(['.TH VIM 1 "YYYY Mth DD"'], 'Xfile.1', 'D') + split Xfile.1 + call assert_equal('nroff', &filetype) + bwipe! + + call writefile(['.Dd $Mdocdate$', '.Dt "DETECTION TEST" "7"', '.Os'], 'Xfile.7', 'D') + split Xfile.7 + call assert_equal('nroff', &filetype) + bwipe! + + call writefile(['''\" t'], 'Xfile.3p', 'D') + split Xfile.3p + call assert_equal('nroff', &filetype) + bwipe! + + call writefile(['. /etc/profile'], 'Xfile.1', 'D') + split Xfile.1 + call assert_notequal('nroff', &filetype) + bwipe! +endfunc + func Test_org_file() filetype on
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index a17d6dd03d6f17..ff46716477120e 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -835,6 +835,7 @@ local extension = { nix = 'nix', norg = 'norg', nqc = 'nqc', + ['0'] = detect.nroff, ['1'] = detect.nroff, ['2'] = detect.nroff, ['3'] = detect.nroff, @@ -844,6 +845,23 @@ local extension = { ['7'] = detect.nroff, ['8'] = detect.nroff, ['9'] = detect.nroff, + ['1p'] = detect.nroff, + ['3p'] = detect.nroff, + ['1x'] = detect.nroff, + ['2x'] = detect.nroff, + ['3x'] = detect.nroff, + ['4x'] = detect.nroff, + ['6x'] = detect.nroff, + ['7x'] = detect.nroff, + ['8x'] = detect.nroff, + ['3am'] = detect.nroff, + ['3perl'] = detect.nroff, + ['3pm'] = detect.nroff, + ['3posix'] = detect.nroff, + ['3type'] = detect.nroff, + n = detect.nroff, roff = 'nroff', tmac = 'nroff', man = 'nroff', diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index c2674febc6893f..9cc50952d1830f 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -1170,12 +1170,17 @@ function M.news(_, bufnr) end ---- This function checks if one of the first five lines start with a dot. In ---- that case it is probably an nroff file. +--- This function checks if one of the first five lines start with a typical +--- nroff pattern in man files. In that case it is probably an nroff file. --- @type vim.filetype.mapfn function M.nroff(_, bufnr) for _, line in ipairs(getlines(bufnr, 1, 5)) do - if line:find('^%.') then + if + matchregex( + line, + [[^\%([.']\s*\%(TH\|D[dt]\|S[Hh]\|d[es]1\?\|so\)\s\+\S\|[.'']\s*ig\>\|\%([.'']\s*\)\?\\"\)]] + ) + then return 'nroff' end diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim index 9affc308ee1ddd..97c03726eac5c5 100644 --- a/test/old/testdir/test_filetype.vim +++ b/test/old/testdir/test_filetype.vim @@ -2918,6 +2918,30 @@ func Test_map_file() filetype off endfunc +func Test_nroff_file() + filetype on + call writefile(['.TH VIM 1 "YYYY Mth DD"'], 'Xfile.1', 'D') + call writefile(['.Dd $Mdocdate$', '.Dt "DETECTION TEST" "7"', '.Os'], 'Xfile.7', 'D') + split Xfile.7 + call writefile(['''\" t'], 'Xfile.3p', 'D') + split Xfile.3p + call assert_notequal('nroff', &filetype) +endfunc func Test_org_file() filetype on
[ "+ ['0p'] = detect.nroff,", "+ ['5x'] = detect.nroff,", "+ call writefile(['. /etc/profile'], 'Xfile.1', 'D')" ]
[ 16, 23, 87 ]
{ "additions": 50, "author": "zeertzjq", "deletions": 1, "html_url": "https://github.com/neovim/neovim/pull/33561", "issue_id": 33561, "merged_at": "2025-04-21T11:09:30Z", "omission_probability": 0.1, "pr_number": 33561, "repo": "neovim/neovim", "title": "vim-patch:9.1.{1304,1327}: filetype: some man files are not recognized", "total_changes": 51 }
376
diff --git a/src/gen/gen_vimdoc.lua b/src/gen/gen_vimdoc.lua index 2bcb675349141a..c9b260b6f6acd4 100755 --- a/src/gen/gen_vimdoc.lua +++ b/src/gen/gen_vimdoc.lua @@ -983,11 +983,13 @@ local function gen_target(cfg) --- First pass so we can collect all classes for _, f in vim.spairs(cfg.files) do - local ext = assert(f:match('%.([^.]+)$')) --[[@as 'h'|'c'|'lua']] - local parser = assert(parsers[ext]) - local classes, funs, briefs = parser(f) - file_results[f] = { classes, funs, briefs } - all_classes = vim.tbl_extend('error', all_classes, classes) + local ext = f:match('%.([^.]+)$') + local parser = parsers[ext] + if parser then + local classes, funs, briefs = parser(f) + file_results[f] = { classes, funs, briefs } + all_classes = vim.tbl_extend('error', all_classes, classes) + end end for f, r in vim.spairs(file_results) do
diff --git a/src/gen/gen_vimdoc.lua b/src/gen/gen_vimdoc.lua index 2bcb675349141a..c9b260b6f6acd4 100755 --- a/src/gen/gen_vimdoc.lua +++ b/src/gen/gen_vimdoc.lua @@ -983,11 +983,13 @@ local function gen_target(cfg) --- First pass so we can collect all classes for _, f in vim.spairs(cfg.files) do - local ext = assert(f:match('%.([^.]+)$')) --[[@as 'h'|'c'|'lua']] - local parser = assert(parsers[ext]) - local classes, funs, briefs = parser(f) - file_results[f] = { classes, funs, briefs } - all_classes = vim.tbl_extend('error', all_classes, classes) + local ext = f:match('%.([^.]+)$') + local parser = parsers[ext] + if parser then + local classes, funs, briefs = parser(f) + file_results[f] = { classes, funs, briefs } + all_classes = vim.tbl_extend('error', all_classes, classes) + end end for f, r in vim.spairs(file_results) do
[]
[]
{ "additions": 7, "author": "luukvbaal", "deletions": 5, "html_url": "https://github.com/neovim/neovim/pull/33547", "issue_id": 33547, "merged_at": "2025-04-21T08:15:33Z", "omission_probability": 0.1, "pr_number": 33547, "repo": "neovim/neovim", "title": "fix(gen_vimdoc): unnecessary assert for non-source files", "total_changes": 12 }
377
diff --git a/src/nvim/tag.c b/src/nvim/tag.c index ee6b0863f33345..28a7106630b614 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -1250,6 +1250,7 @@ static int find_tagfunc_tags(char *pat, garray_T *ga, int *match_count, int flag pos_T save_pos = curwin->w_cursor; int result = callback_call(&curbuf->b_tfu_cb, 3, args, &rettv); curwin->w_cursor = save_pos; // restore the cursor position + check_cursor(curwin); // make sure cursor position is valid d->dv_refcount--; if (result == FAIL) { diff --git a/test/old/testdir/test_tagfunc.vim b/test/old/testdir/test_tagfunc.vim index ec1f93e9beb744..19fc8de8dd0b19 100644 --- a/test/old/testdir/test_tagfunc.vim +++ b/test/old/testdir/test_tagfunc.vim @@ -413,5 +413,24 @@ func Test_tagfunc_closes_window() set tagfunc= endfunc +func Test_tagfunc_deletes_lines() + defer delete('Xany') + split Xany + call writefile([''], 'Xtest', 'D') + call setline(1, range(10)) + call cursor(10, 1) + func MytagfuncDel(pat, flags, info) + 9,10d + return [{'name' : 'mytag', 'filename' : 'Xtest', 'cmd' : '1'}] + endfunc + set tagfunc=MytagfuncDel + call taglist('.') + call assert_equal([0, 8, 1, 0], getpos('.')) + norm! ofoobar + call assert_equal(['0', '1', '2', '3', '4', '5', '6', '7', 'foobar'], getline(1, '$')) + + bw! + set tagfunc= +endfunc " vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/tag.c b/src/nvim/tag.c index ee6b0863f33345..28a7106630b614 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -1250,6 +1250,7 @@ static int find_tagfunc_tags(char *pat, garray_T *ga, int *match_count, int flag pos_T save_pos = curwin->w_cursor; int result = callback_call(&curbuf->b_tfu_cb, 3, args, &rettv); curwin->w_cursor = save_pos; // restore the cursor position + check_cursor(curwin); // make sure cursor position is valid d->dv_refcount--; if (result == FAIL) { diff --git a/test/old/testdir/test_tagfunc.vim b/test/old/testdir/test_tagfunc.vim index ec1f93e9beb744..19fc8de8dd0b19 100644 --- a/test/old/testdir/test_tagfunc.vim +++ b/test/old/testdir/test_tagfunc.vim @@ -413,5 +413,24 @@ func Test_tagfunc_closes_window() set tagfunc= endfunc +func Test_tagfunc_deletes_lines() + defer delete('Xany') + split Xany + call writefile([''], 'Xtest', 'D') + call setline(1, range(10)) + call cursor(10, 1) + func MytagfuncDel(pat, flags, info) + 9,10d + return [{'name' : 'mytag', 'filename' : 'Xtest', 'cmd' : '1'}] + set tagfunc=MytagfuncDel + call assert_equal([0, 8, 1, 0], getpos('.')) + norm! ofoobar + call assert_equal(['0', '1', '2', '3', '4', '5', '6', '7', 'foobar'], getline(1, '$')) + + bw! + set tagfunc= +endfunc " vim: shiftwidth=2 sts=2 expandtab
[ "+ endfunc", "+ call taglist('.')" ]
[ 29, 31 ]
{ "additions": 20, "author": "zeertzjq", "deletions": 0, "html_url": "https://github.com/neovim/neovim/pull/33556", "issue_id": 33556, "merged_at": "2025-04-20T23:04:03Z", "omission_probability": 0.1, "pr_number": 33556, "repo": "neovim/neovim", "title": "vim-patch:9.1.1326: invalid cursor position after 'tagfunc'", "total_changes": 20 }
378
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 9b3e1526b2df45..a17d6dd03d6f17 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -345,6 +345,8 @@ local extension = { tcc = 'cpp', hxx = 'cpp', hpp = 'cpp', + ixx = 'cpp', + mpp = 'cpp', ccm = 'cpp', cppm = 'cpp', cxxm = 'cpp', @@ -1546,6 +1548,10 @@ local filename = { ['nfs.conf'] = 'dosini', ['nfsmount.conf'] = 'dosini', ['.notmuch-config'] = 'dosini', + ['.alsoftrc'] = 'dosini', + ['alsoft.conf'] = 'dosini', + ['alsoft.ini'] = 'dosini', + ['alsoftrc.sample'] = 'dosini', ['pacman.conf'] = 'confini', ['paru.conf'] = 'confini', ['mpv.conf'] = 'confini', diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim index 0c010b120a372a..9affc308ee1ddd 100644 --- a/test/old/testdir/test_filetype.vim +++ b/test/old/testdir/test_filetype.vim @@ -188,7 +188,7 @@ func s:GetFilenameChecks() abort \ 'cook': ['file.cook'], \ 'corn': ['file.corn'], \ 'cpon': ['file.cpon'], - \ 'cpp': ['file.cxx', 'file.c++', 'file.hh', 'file.hxx', 'file.hpp', 'file.ipp', 'file.moc', 'file.tcc', 'file.inl', 'file.tlh', 'file.cppm', 'file.ccm', 'file.cxxm', 'file.c++m'], + \ 'cpp': ['file.cxx', 'file.c++', 'file.hh', 'file.hxx', 'file.hpp', 'file.ipp', 'file.ixx', 'file.moc', 'file.tcc', 'file.inl', 'file.tlh', 'file.cppm', 'file.ccm', 'file.cxxm', 'file.c++m', 'file.mpp'], \ 'cqlang': ['file.cql'], \ 'crm': ['file.crm'], \ 'crontab': ['crontab', 'crontab.file', '/etc/cron.d/file', 'any/etc/cron.d/file'], @@ -239,7 +239,9 @@ func s:GetFilenameChecks() abort \ '.coveragerc', '.pypirc', '.gitlint', '.oelint.cfg', 'pylintrc', '.pylintrc', \ '/home/user/.config/bpython/config', '/home/user/.config/mypy/config', '.wakatime.cfg', '.replyrc', \ 'psprint.conf', 'sofficerc', 'any/.config/lxqt/globalkeyshortcuts.conf', 'any/.config/screengrab/screengrab.conf', - \ 'any/.local/share/flatpak/repo/config', '.notmuch-config', '.notmuch-config.myprofile', + \ 'any/.local/share/flatpak/repo/config', + \ '.alsoftrc', 'alsoft.conf', 'alsoft.ini', 'alsoftrc.sample', + \ '.notmuch-config', '.notmuch-config.myprofile', \ '~/.config/notmuch/myprofile/config'] + s:WhenConfigHome('$XDG_CONFIG_HOME/notmuch/myprofile/config'), \ 'dot': ['file.dot', 'file.gv'], \ 'dracula': ['file.drac', 'file.drc', 'file.lvs', 'file.lpe', 'drac.file'],
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 9b3e1526b2df45..a17d6dd03d6f17 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -345,6 +345,8 @@ local extension = { tcc = 'cpp', hxx = 'cpp', hpp = 'cpp', + ixx = 'cpp', + mpp = 'cpp', ccm = 'cpp', cppm = 'cpp', cxxm = 'cpp', @@ -1546,6 +1548,10 @@ local filename = { ['nfs.conf'] = 'dosini', ['nfsmount.conf'] = 'dosini', ['.notmuch-config'] = 'dosini', + ['.alsoftrc'] = 'dosini', + ['alsoft.conf'] = 'dosini', + ['alsoft.ini'] = 'dosini', + ['alsoftrc.sample'] = 'dosini', ['pacman.conf'] = 'confini', ['paru.conf'] = 'confini', ['mpv.conf'] = 'confini', diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim index 0c010b120a372a..9affc308ee1ddd 100644 --- a/test/old/testdir/test_filetype.vim +++ b/test/old/testdir/test_filetype.vim @@ -188,7 +188,7 @@ func s:GetFilenameChecks() abort \ 'cook': ['file.cook'], \ 'corn': ['file.corn'], \ 'cpon': ['file.cpon'], - \ 'cpp': ['file.cxx', 'file.c++', 'file.hh', 'file.hxx', 'file.hpp', 'file.ipp', 'file.moc', 'file.tcc', 'file.inl', 'file.tlh', 'file.cppm', 'file.ccm', 'file.cxxm', 'file.c++m'], \ 'cqlang': ['file.cql'], \ 'crm': ['file.crm'], \ 'crontab': ['crontab', 'crontab.file', '/etc/cron.d/file', 'any/etc/cron.d/file'], @@ -239,7 +239,9 @@ func s:GetFilenameChecks() abort \ '.coveragerc', '.pypirc', '.gitlint', '.oelint.cfg', 'pylintrc', '.pylintrc', \ '/home/user/.config/bpython/config', '/home/user/.config/mypy/config', '.wakatime.cfg', '.replyrc', \ 'psprint.conf', 'sofficerc', 'any/.config/lxqt/globalkeyshortcuts.conf', 'any/.config/screengrab/screengrab.conf', - \ 'any/.local/share/flatpak/repo/config', '.notmuch-config', '.notmuch-config.myprofile', + \ 'any/.local/share/flatpak/repo/config', + \ '.alsoftrc', 'alsoft.conf', 'alsoft.ini', 'alsoftrc.sample', + \ '.notmuch-config', '.notmuch-config.myprofile', \ '~/.config/notmuch/myprofile/config'] + s:WhenConfigHome('$XDG_CONFIG_HOME/notmuch/myprofile/config'), \ 'dot': ['file.dot', 'file.gv'], \ 'dracula': ['file.drac', 'file.drc', 'file.lvs', 'file.lpe', 'drac.file'],
[ "+ \\ 'cpp': ['file.cxx', 'file.c++', 'file.hh', 'file.hxx', 'file.hpp', 'file.ipp', 'file.ixx', 'file.moc', 'file.tcc', 'file.inl', 'file.tlh', 'file.cppm', 'file.ccm', 'file.cxxm', 'file.c++m', 'file.mpp']," ]
[ 33 ]
{ "additions": 10, "author": "clason", "deletions": 2, "html_url": "https://github.com/neovim/neovim/pull/33530", "issue_id": 33530, "merged_at": "2025-04-19T08:52:12Z", "omission_probability": 0.1, "pr_number": 33530, "repo": "neovim/neovim", "title": "vim-patch:9.1.1321: filetype: MS ixx and mpp files are not recognized", "total_changes": 12 }
379
diff --git a/test/functional/api/window_spec.lua b/test/functional/api/window_spec.lua index 2a0583b4e73379..2ad3961d2c3b65 100644 --- a/test/functional/api/window_spec.lua +++ b/test/functional/api/window_spec.lua @@ -1244,13 +1244,13 @@ describe('API/win', function() eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 45 })) eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 1 })) eq({ all = 4, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 0 })) - eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 6 })) - eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 0 })) - eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 44 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 45 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 89 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 90 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = X })) + eq({ all = 6, fill = 3 }, api.nvim_win_text_height(0, { start_row = 2 })) + eq({ all = 4, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 0 })) + eq({ all = 4, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 44 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 45 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 89 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 90 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = X })) end) end)
diff --git a/test/functional/api/window_spec.lua b/test/functional/api/window_spec.lua index 2a0583b4e73379..2ad3961d2c3b65 100644 --- a/test/functional/api/window_spec.lua +++ b/test/functional/api/window_spec.lua @@ -1244,13 +1244,13 @@ describe('API/win', function() eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 45 })) eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 1 })) eq({ all = 4, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 0 })) - eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 6 })) - eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 0 })) - eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 44 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 45 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 89 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 90 })) - eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = X })) + eq({ all = 6, fill = 3 }, api.nvim_win_text_height(0, { start_row = 2 })) + eq({ all = 4, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 0 })) + eq({ all = 4, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 44 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 45 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 89 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = 90 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 2, start_vcol = X })) end) end)
[]
[]
{ "additions": 7, "author": "zeertzjq", "deletions": 7, "html_url": "https://github.com/neovim/neovim/pull/33535", "issue_id": 33535, "merged_at": "2025-04-19T05:14:34Z", "omission_probability": 0.1, "pr_number": 33535, "repo": "neovim/neovim", "title": "test(api/window_spec): check start_vcol on folded line", "total_changes": 14 }
380
diff --git a/test/functional/api/window_spec.lua b/test/functional/api/window_spec.lua index 34b3b2dbe088d9..2a0583b4e73379 100644 --- a/test/functional/api/window_spec.lua +++ b/test/functional/api/window_spec.lua @@ -1201,6 +1201,57 @@ describe('API/win', function() api.nvim_win_text_height(0, { start_row = 0, start_vcol = 220, end_row = 2, end_vcol = 42 }) ) end) + + it('with virtual lines around a fold', function() + local X = api.nvim_get_vvar('maxcol') + local screen = Screen.new(45, 10) + exec([[ + call setline(1, range(1, 8)) + 3,6fold + ]]) + local ns = api.nvim_create_namespace('TEST') + api.nvim_buf_set_extmark( + 0, + ns, + 1, + 0, + { virt_lines = { { { 'VIRT LINE 1' } }, { { 'VIRT LINE 2' } } } } + ) + api.nvim_buf_set_extmark( + 0, + ns, + 6, + 0, + { virt_lines = { { { 'VIRT LINE 3' } } }, virt_lines_above = true } + ) + screen:expect([[ + ^1 | + 2 | + VIRT LINE 1 | + VIRT LINE 2 | + {13:+-- 4 lines: 3······························}| + VIRT LINE 3 | + 7 | + 8 | + {1:~ }| + | + ]]) + eq({ all = 8, fill = 3 }, api.nvim_win_text_height(0, {})) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = X })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 90 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 46 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 45 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 1 })) + eq({ all = 4, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 0 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 6 })) + eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 0 })) + eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 44 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 45 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 89 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 90 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = X })) + end) end) describe('open_win', function()
diff --git a/test/functional/api/window_spec.lua b/test/functional/api/window_spec.lua index 34b3b2dbe088d9..2a0583b4e73379 100644 --- a/test/functional/api/window_spec.lua +++ b/test/functional/api/window_spec.lua @@ -1201,6 +1201,57 @@ describe('API/win', function() api.nvim_win_text_height(0, { start_row = 0, start_vcol = 220, end_row = 2, end_vcol = 42 }) ) end) + + it('with virtual lines around a fold', function() + local X = api.nvim_get_vvar('maxcol') + local screen = Screen.new(45, 10) + exec([[ + call setline(1, range(1, 8)) + 3,6fold + local ns = api.nvim_create_namespace('TEST') + 1, + { virt_lines = { { { 'VIRT LINE 1' } }, { { 'VIRT LINE 2' } } } } + 6, + { virt_lines = { { { 'VIRT LINE 3' } } }, virt_lines_above = true } + screen:expect([[ + ^1 | + 2 | + VIRT LINE 1 | + VIRT LINE 2 | + {13:+-- 4 lines: 3······························}| + 7 | + {1:~ }| + | + eq({ all = 8, fill = 3 }, api.nvim_win_text_height(0, {})) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = X })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 90 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 46 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 45 })) + eq({ all = 5, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 1 })) + eq({ all = 4, fill = 2 }, api.nvim_win_text_height(0, { end_row = 2, end_vcol = 0 })) + eq({ all = 3, fill = 1 }, api.nvim_win_text_height(0, { start_row = 6 })) + eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 0 })) + eq({ all = 2, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 44 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 45 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 89 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = 90 })) + eq({ all = 1, fill = 0 }, api.nvim_win_text_height(0, { start_row = 6, start_vcol = X })) + end) end) describe('open_win', function()
[ "+ VIRT LINE 3 |", "+ 8 |" ]
[ 37, 39 ]
{ "additions": 51, "author": "zeertzjq", "deletions": 0, "html_url": "https://github.com/neovim/neovim/pull/33529", "issue_id": 33529, "merged_at": "2025-04-19T01:00:46Z", "omission_probability": 0.1, "pr_number": 33529, "repo": "neovim/neovim", "title": "test(api): nvim_win_text_height with virt_lines around fold", "total_changes": 51 }
381
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 4b98f487d30c52..da4d1e7f20a593 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -1590,8 +1590,10 @@ A jump table for the options with a short description can be found at |Q_op|. Useful when there is additional information about the match, e.g., what file it comes from. - nearest Matches are presented in order of proximity to the cursor - position. This applies only to matches from the current + nearest Matches are listed based on their proximity to the cursor + position, unlike the default behavior, which only + considers proximity for matches appearing below the + cursor. This applies only to matches from the current buffer. No effect if "fuzzy" is present. noinsert Do not insert any text for a match until the user selects diff --git a/runtime/lua/vim/_meta/options.lua b/runtime/lua/vim/_meta/options.lua index 956a22bd4b3d9f..78bce262cd2e4d 100644 --- a/runtime/lua/vim/_meta/options.lua +++ b/runtime/lua/vim/_meta/options.lua @@ -1123,8 +1123,10 @@ vim.go.cia = vim.go.completeitemalign --- Useful when there is additional information about the --- match, e.g., what file it comes from. --- ---- nearest Matches are presented in order of proximity to the cursor ---- position. This applies only to matches from the current +--- nearest Matches are listed based on their proximity to the cursor +--- position, unlike the default behavior, which only +--- considers proximity for matches appearing below the +--- cursor. This applies only to matches from the current --- buffer. No effect if "fuzzy" is present. --- --- noinsert Do not insert any text for a match until the user selects diff --git a/src/nvim/options.lua b/src/nvim/options.lua index d43a71e5e9406f..287bf49dad5b10 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -1580,8 +1580,10 @@ local options = { Useful when there is additional information about the match, e.g., what file it comes from. - nearest Matches are presented in order of proximity to the cursor - position. This applies only to matches from the current + nearest Matches are listed based on their proximity to the cursor + position, unlike the default behavior, which only + considers proximity for matches appearing below the + cursor. This applies only to matches from the current buffer. No effect if "fuzzy" is present. noinsert Do not insert any text for a match until the user selects
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 4b98f487d30c52..da4d1e7f20a593 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -1590,8 +1590,10 @@ A jump table for the options with a short description can be found at |Q_op|. Useful when there is additional information about the match, e.g., what file it comes from. - position. This applies only to matches from the current + nearest Matches are listed based on their proximity to the cursor + position, unlike the default behavior, which only + considers proximity for matches appearing below the + cursor. This applies only to matches from the current buffer. No effect if "fuzzy" is present. noinsert Do not insert any text for a match until the user selects diff --git a/runtime/lua/vim/_meta/options.lua b/runtime/lua/vim/_meta/options.lua index 956a22bd4b3d9f..78bce262cd2e4d 100644 --- a/runtime/lua/vim/_meta/options.lua +++ b/runtime/lua/vim/_meta/options.lua @@ -1123,8 +1123,10 @@ vim.go.cia = vim.go.completeitemalign --- Useful when there is additional information about the --- match, e.g., what file it comes from. ---- nearest Matches are presented in order of proximity to the cursor ---- position. This applies only to matches from the current +--- nearest Matches are listed based on their proximity to the cursor +--- position, unlike the default behavior, which only +--- considers proximity for matches appearing below the +--- cursor. This applies only to matches from the current --- buffer. No effect if "fuzzy" is present. --- noinsert Do not insert any text for a match until the user selects diff --git a/src/nvim/options.lua b/src/nvim/options.lua index d43a71e5e9406f..287bf49dad5b10 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -1580,8 +1580,10 @@ local options = { Useful when there is additional information about the match, e.g., what file it comes from. - nearest Matches are presented in order of proximity to the cursor - position. This applies only to matches from the current + nearest Matches are listed based on their proximity to the cursor + position, unlike the default behavior, which only + considers proximity for matches appearing below the + cursor. This applies only to matches from the current buffer. No effect if "fuzzy" is present. noinsert Do not insert any text for a match until the user selects
[ "-\t nearest Matches are presented in order of proximity to the cursor" ]
[ 8 ]
{ "additions": 12, "author": "zeertzjq", "deletions": 4, "html_url": "https://github.com/neovim/neovim/pull/33534", "issue_id": 33534, "merged_at": "2025-04-19T00:42:48Z", "omission_probability": 0.1, "pr_number": 33534, "repo": "neovim/neovim", "title": "vim-patch:cb3b752: runtime(doc): clarify \"nearest\" value for 'completeopt'", "total_changes": 16 }
382
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 7312177b998a92..e1d508fd8743b3 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -7392,7 +7392,8 @@ printf({fmt}, {expr1} ...) *printf()* < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua index 699975e62a189b..a69dd3d9b0d0b4 100644 --- a/runtime/lua/vim/_meta/vimfn.lua +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -6717,7 +6717,8 @@ function vim.fn.prevnonblank(lnum) end --- < 1.41 --- --- You will get an overflow error |E1510|, when the field-width ---- or precision will result in a string longer than 6400 chars. +--- or precision will result in a string longer than 1 MB +--- (1024*1024 = 1048576) chars. --- --- *E1500* --- You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 4e7cdbdffd38a6..bb33188649f222 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -8166,7 +8166,8 @@ M.funcs = { < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/strings.c b/src/nvim/strings.c index add4c9dcb68336..0538ee2b22a6a2 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -1027,7 +1027,7 @@ static void format_overflow_error(const char *pstart) xfree(argcopy); } -enum { MAX_ALLOWED_STRING_WIDTH = 6400, }; +enum { MAX_ALLOWED_STRING_WIDTH = 1048576, }; // 1MiB static int get_unsigned_int(const char *pstart, const char **p, unsigned *uj, bool overflow_err) { diff --git a/test/old/testdir/test_format.vim b/test/old/testdir/test_format.vim index 36795c87eaa073..c2126f583cc993 100644 --- a/test/old/testdir/test_format.vim +++ b/test/old/testdir/test_format.vim @@ -334,13 +334,13 @@ func Test_printf_pos_errors() call CheckLegacyAndVim9Failure(["call printf('%1$*123456789$.*987654321$d', 5)"], "E1510:") call CheckLegacyAndVim9Failure(["call printf('%123456789$*1$.*987654321$d', 5)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9123, 9312)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9999123, 9999312)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999999)"], "E1510:") endfunc func Test_printf_pos_64bit()
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 7312177b998a92..e1d508fd8743b3 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -7392,7 +7392,8 @@ printf({fmt}, {expr1} ...) *printf()* < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua index 699975e62a189b..a69dd3d9b0d0b4 100644 --- a/runtime/lua/vim/_meta/vimfn.lua +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -6717,7 +6717,8 @@ function vim.fn.prevnonblank(lnum) end --- < 1.41 --- You will get an overflow error |E1510|, when the field-width ---- or precision will result in a string longer than 6400 chars. +--- or precision will result in a string longer than 1 MB +--- (1024*1024 = 1048576) chars. --- *E1500* --- You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 4e7cdbdffd38a6..bb33188649f222 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -8166,7 +8166,8 @@ M.funcs = { < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/strings.c b/src/nvim/strings.c index add4c9dcb68336..0538ee2b22a6a2 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -1027,7 +1027,7 @@ static void format_overflow_error(const char *pstart) xfree(argcopy); } -enum { MAX_ALLOWED_STRING_WIDTH = 6400, }; +enum { MAX_ALLOWED_STRING_WIDTH = 1048576, }; // 1MiB static int get_unsigned_int(const char *pstart, const char **p, unsigned *uj, bool overflow_err) { diff --git a/test/old/testdir/test_format.vim b/test/old/testdir/test_format.vim index 36795c87eaa073..c2126f583cc993 100644 --- a/test/old/testdir/test_format.vim +++ b/test/old/testdir/test_format.vim @@ -334,13 +334,13 @@ func Test_printf_pos_errors() call CheckLegacyAndVim9Failure(["call printf('%1$*123456789$.*987654321$d', 5)"], "E1510:") call CheckLegacyAndVim9Failure(["call printf('%123456789$*1$.*987654321$d', 5)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9123, 9312)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9999123, 9999312)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999999)"], "E1510:") endfunc func Test_printf_pos_64bit()
[ "- call CheckLegacyAndVim9Failure([\"call printf('%2$*3$.*1$d', 5, 9123, 9321)\"], \"E1510:\")" ]
[ 65 ]
{ "additions": 13, "author": "neovim-backports[bot]", "deletions": 9, "html_url": "https://github.com/neovim/neovim/pull/33533", "issue_id": 33533, "merged_at": "2025-04-19T00:12:55Z", "omission_probability": 0.1, "pr_number": 33533, "repo": "neovim/neovim", "title": "vim-patch:9.1.{1314,1318}: max allowed string width too small", "total_changes": 22 }
383
diff --git a/src/nvim/ops.c b/src/nvim/ops.c index cab775a189b92b..d4e21c6ebfb05c 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -1367,7 +1367,7 @@ int insert_reg(int regname, yankreg_T *reg, bool literally_arg) retval = FAIL; } else { for (size_t i = 0; i < reg->y_size; i++) { - if (regname == '-') { + if (regname == '-' && reg->y_type == kMTCharWise) { Direction dir = BACKWARD; if ((State & REPLACE_FLAG) != 0) { pos_T curpos; @@ -1388,11 +1388,11 @@ int insert_reg(int regname, yankreg_T *reg, bool literally_arg) do_put(regname, NULL, dir, 1, PUT_CURSEND); } else { stuffescaped(reg->y_array[i].data, literally); - } - // Insert a newline between lines and after last line if - // y_type is kMTLineWise. - if (reg->y_type == kMTLineWise || i < reg->y_size - 1) { - stuffcharReadbuff('\n'); + // Insert a newline between lines and after last line if + // y_type is kMTLineWise. + if (reg->y_type == kMTLineWise || i < reg->y_size - 1) { + stuffcharReadbuff('\n'); + } } } } diff --git a/test/old/testdir/test_registers.vim b/test/old/testdir/test_registers.vim index 02da2ac689c9c8..1d06e54cc9cbe0 100644 --- a/test/old/testdir/test_registers.vim +++ b/test/old/testdir/test_registers.vim @@ -1087,4 +1087,13 @@ func Test_mark_from_yank() bw! endfunc +func Test_insert_small_delete_linewise() + new + call setline(1, ['foo']) + call cursor(1, 1) + exe ":norm! \"-cc\<C-R>-" + call assert_equal(['foo', ''], getline(1, '$')) + bwipe! +endfunc + " vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/ops.c b/src/nvim/ops.c index cab775a189b92b..d4e21c6ebfb05c 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -1367,7 +1367,7 @@ int insert_reg(int regname, yankreg_T *reg, bool literally_arg) retval = FAIL; } else { for (size_t i = 0; i < reg->y_size; i++) { - if (regname == '-') { + if (regname == '-' && reg->y_type == kMTCharWise) { Direction dir = BACKWARD; if ((State & REPLACE_FLAG) != 0) { pos_T curpos; @@ -1388,11 +1388,11 @@ int insert_reg(int regname, yankreg_T *reg, bool literally_arg) do_put(regname, NULL, dir, 1, PUT_CURSEND); } else { stuffescaped(reg->y_array[i].data, literally); - } - // Insert a newline between lines and after last line if - // y_type is kMTLineWise. - if (reg->y_type == kMTLineWise || i < reg->y_size - 1) { + // Insert a newline between lines and after last line if + // y_type is kMTLineWise. + if (reg->y_type == kMTLineWise || i < reg->y_size - 1) { + stuffcharReadbuff('\n'); + } } } } diff --git a/test/old/testdir/test_registers.vim b/test/old/testdir/test_registers.vim index 02da2ac689c9c8..1d06e54cc9cbe0 100644 --- a/test/old/testdir/test_registers.vim +++ b/test/old/testdir/test_registers.vim @@ -1087,4 +1087,13 @@ func Test_mark_from_yank() bw! endfunc +func Test_insert_small_delete_linewise() + new + call setline(1, ['foo']) + call cursor(1, 1) + exe ":norm! \"-cc\<C-R>-" + call assert_equal(['foo', ''], getline(1, '$')) + bwipe! +endfunc + " vim: shiftwidth=2 sts=2 expandtab
[ "- stuffcharReadbuff('\\n');" ]
[ 21 ]
{ "additions": 15, "author": "phanen", "deletions": 6, "html_url": "https://github.com/neovim/neovim/pull/33531", "issue_id": 33531, "merged_at": "2025-04-19T00:01:51Z", "omission_probability": 0.1, "pr_number": 33531, "repo": "neovim/neovim", "title": "vim-patch:9.1.1322: small delete register cannot paste multi-line correctly", "total_changes": 21 }
384
diff --git a/src/nvim/diff.c b/src/nvim/diff.c index ed2078207da027..60f271b08402cf 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -2916,7 +2916,7 @@ static void diff_refine_inline_char_highlight(diff_T *dp_orig, garray_T *linemap } while (pass++ < 4); // use limited number of passes to avoid excessive looping } -/// Find the inline difference within a diff block among differnt buffers. Do +/// Find the inline difference within a diff block among different buffers. Do /// this by splitting each block's content into characters or words, and then /// use internal xdiff to calculate the per-character/word diff. The result is /// stored in dp instead of returned by the function. @@ -4076,7 +4076,7 @@ void f_diff_hlID(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) diffline_T diffline = { 0 }; // Remember the results if using simple since it's recalculated per // call. Otherwise just call diff_find_change() every time since - // internally the result is cached interally. + // internally the result is cached internally. const bool cache_results = !(diff_flags & ALL_INLINE_DIFF); linenr_T lnum = tv_get_lnum(argvars); diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 83ab0d5c24b19c..a084127ee31d1c 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -2909,7 +2909,7 @@ static void nv_zet(cmdarg_T *cap) } break; - // "zp", "zP" in block mode put without addind trailing spaces + // "zp", "zP" in block mode put without adding trailing spaces case 'P': case 'p': nv_put(cap); diff --git a/src/nvim/ops.c b/src/nvim/ops.c index cab775a189b92b..19dc8fe43b0116 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -297,12 +297,12 @@ static int get_vts_sum(const int *vts_array, int index) int sum = 0; int i; - // Perform the summation for indeces within the actual array. + // Perform the summation for indices within the actual array. for (i = 1; i <= index && i <= vts_array[0]; i++) { sum += vts_array[i]; } - // Add topstops whose indeces exceed the actual array. + // Add tabstops whose indices exceed the actual array. if (i <= index) { sum += vts_array[vts_array[0]] * (index - vts_array[0]); } diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index f3c1a6fbcb47df..066a538906ce70 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -2988,7 +2988,7 @@ func Test_complete_fuzzy_collect() call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!') call assert_equal('completefuzzycollect', getline('.')) - execute('%d _') + %d _ call setline(1, ['fuzzy', 'fuzzy foo', "fuzzy bar", 'fuzzycollect']) call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!') call assert_equal('fuzzycollect', getline('.'))
diff --git a/src/nvim/diff.c b/src/nvim/diff.c index ed2078207da027..60f271b08402cf 100644 --- a/src/nvim/diff.c +++ b/src/nvim/diff.c @@ -2916,7 +2916,7 @@ static void diff_refine_inline_char_highlight(diff_T *dp_orig, garray_T *linemap } while (pass++ < 4); // use limited number of passes to avoid excessive looping } -/// Find the inline difference within a diff block among differnt buffers. Do /// this by splitting each block's content into characters or words, and then /// use internal xdiff to calculate the per-character/word diff. The result is /// stored in dp instead of returned by the function. @@ -4076,7 +4076,7 @@ void f_diff_hlID(typval_T *argvars, typval_T *rettv, EvalFuncData fptr) diffline_T diffline = { 0 }; // Remember the results if using simple since it's recalculated per // call. Otherwise just call diff_find_change() every time since - // internally the result is cached interally. + // internally the result is cached internally. const bool cache_results = !(diff_flags & ALL_INLINE_DIFF); linenr_T lnum = tv_get_lnum(argvars); diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 83ab0d5c24b19c..a084127ee31d1c 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -2909,7 +2909,7 @@ static void nv_zet(cmdarg_T *cap) } break; - // "zp", "zP" in block mode put without addind trailing spaces + // "zp", "zP" in block mode put without adding trailing spaces case 'P': case 'p': nv_put(cap); diff --git a/src/nvim/ops.c b/src/nvim/ops.c index cab775a189b92b..19dc8fe43b0116 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -297,12 +297,12 @@ static int get_vts_sum(const int *vts_array, int index) int sum = 0; int i; - // Perform the summation for indeces within the actual array. + // Perform the summation for indices within the actual array. for (i = 1; i <= index && i <= vts_array[0]; i++) { sum += vts_array[i]; + // Add tabstops whose indices exceed the actual array. if (i <= index) { sum += vts_array[vts_array[0]] * (index - vts_array[0]); diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index f3c1a6fbcb47df..066a538906ce70 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -2988,7 +2988,7 @@ func Test_complete_fuzzy_collect() call assert_equal('completefuzzycollect', getline('.')) - execute('%d _') + %d _ call setline(1, ['fuzzy', 'fuzzy foo', "fuzzy bar", 'fuzzycollect']) call assert_equal('fuzzycollect', getline('.'))
[ "+/// Find the inline difference within a diff block among different buffers. Do", "- // Add topstops whose indeces exceed the actual array." ]
[ 9, 49 ]
{ "additions": 6, "author": "zeertzjq", "deletions": 6, "html_url": "https://github.com/neovim/neovim/pull/33527", "issue_id": 33527, "merged_at": "2025-04-18T23:23:20Z", "omission_probability": 0.1, "pr_number": 33527, "repo": "neovim/neovim", "title": "vim-patch:9.1.1319: Various typos in the code, issue with test_inst_complete.vim", "total_changes": 12 }
385
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 549bd8db1af76a..351b17fc59d8d3 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -7395,7 +7395,8 @@ printf({fmt}, {expr1} ...) *printf()* < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua index 3b0d51a42907dd..c1387954df6b32 100644 --- a/runtime/lua/vim/_meta/vimfn.lua +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -6720,7 +6720,8 @@ function vim.fn.prevnonblank(lnum) end --- < 1.41 --- --- You will get an overflow error |E1510|, when the field-width ---- or precision will result in a string longer than 6400 chars. +--- or precision will result in a string longer than 1 MB +--- (1024*1024 = 1048576) chars. --- --- *E1500* --- You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 6b4c88f071d87c..1433394e19da70 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -8169,7 +8169,8 @@ M.funcs = { < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/strings.c b/src/nvim/strings.c index add4c9dcb68336..0538ee2b22a6a2 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -1027,7 +1027,7 @@ static void format_overflow_error(const char *pstart) xfree(argcopy); } -enum { MAX_ALLOWED_STRING_WIDTH = 6400, }; +enum { MAX_ALLOWED_STRING_WIDTH = 1048576, }; // 1MiB static int get_unsigned_int(const char *pstart, const char **p, unsigned *uj, bool overflow_err) { diff --git a/test/old/testdir/test_format.vim b/test/old/testdir/test_format.vim index 36795c87eaa073..c2126f583cc993 100644 --- a/test/old/testdir/test_format.vim +++ b/test/old/testdir/test_format.vim @@ -334,13 +334,13 @@ func Test_printf_pos_errors() call CheckLegacyAndVim9Failure(["call printf('%1$*123456789$.*987654321$d', 5)"], "E1510:") call CheckLegacyAndVim9Failure(["call printf('%123456789$*1$.*987654321$d', 5)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9123, 9312)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9999123, 9999312)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999999)"], "E1510:") endfunc func Test_printf_pos_64bit()
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt index 549bd8db1af76a..351b17fc59d8d3 100644 --- a/runtime/doc/builtin.txt +++ b/runtime/doc/builtin.txt @@ -7395,7 +7395,8 @@ printf({fmt}, {expr1} ...) *printf()* < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/runtime/lua/vim/_meta/vimfn.lua b/runtime/lua/vim/_meta/vimfn.lua index 3b0d51a42907dd..c1387954df6b32 100644 --- a/runtime/lua/vim/_meta/vimfn.lua +++ b/runtime/lua/vim/_meta/vimfn.lua @@ -6720,7 +6720,8 @@ function vim.fn.prevnonblank(lnum) end --- < 1.41 --- You will get an overflow error |E1510|, when the field-width ---- or precision will result in a string longer than 6400 chars. +--- or precision will result in a string longer than 1 MB +--- (1024*1024 = 1048576) chars. --- *E1500* --- You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 6b4c88f071d87c..1433394e19da70 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -8169,7 +8169,8 @@ M.funcs = { < 1.41 You will get an overflow error |E1510|, when the field-width - or precision will result in a string longer than 6400 chars. + or precision will result in a string longer than 1 MB + (1024*1024 = 1048576) chars. *E1500* You cannot mix positional and non-positional arguments: >vim diff --git a/src/nvim/strings.c b/src/nvim/strings.c index add4c9dcb68336..0538ee2b22a6a2 100644 --- a/src/nvim/strings.c +++ b/src/nvim/strings.c @@ -1027,7 +1027,7 @@ static void format_overflow_error(const char *pstart) xfree(argcopy); } -enum { MAX_ALLOWED_STRING_WIDTH = 6400, }; +enum { MAX_ALLOWED_STRING_WIDTH = 1048576, }; // 1MiB static int get_unsigned_int(const char *pstart, const char **p, unsigned *uj, bool overflow_err) { diff --git a/test/old/testdir/test_format.vim b/test/old/testdir/test_format.vim index 36795c87eaa073..c2126f583cc993 100644 --- a/test/old/testdir/test_format.vim +++ b/test/old/testdir/test_format.vim @@ -334,13 +334,13 @@ func Test_printf_pos_errors() call CheckLegacyAndVim9Failure(["call printf('%1$*123456789$.*987654321$d', 5)"], "E1510:") call CheckLegacyAndVim9Failure(["call printf('%123456789$*1$.*987654321$d', 5)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9123, 9321)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9123, 9312)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*1$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*2$d', 5, 9999999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*3$.*1$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$.*3$d', 5, 9999123, 9999321)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%2$*1$.*3$d', 5, 9999123, 9999312)"], "E1510:") - call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999)"], "E1510:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2$d', 5, 9999999)"], "E1510:") endfunc func Test_printf_pos_64bit()
[ "- call CheckLegacyAndVim9Failure([\"call printf('%1$*2$.*1$d', 5, 9999)\"], \"E1510:\")" ]
[ 63 ]
{ "additions": 13, "author": "zeertzjq", "deletions": 9, "html_url": "https://github.com/neovim/neovim/pull/33519", "issue_id": 33519, "merged_at": "2025-04-18T23:22:40Z", "omission_probability": 0.1, "pr_number": 33519, "repo": "neovim/neovim", "title": "vim-patch:9.1.{1314,1318}: max allowed string width too small", "total_changes": 22 }
386
diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index 48162b9fa207e5..740036297bdb3c 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -186,7 +186,7 @@ CHANGED FEATURES *news-changed* These existing features changed their behavior. -• 'spellfile' location defaults to `stdpath("data").."/spell/"` instead of the +• 'spellfile' location defaults to `stdpath("data").."/site/spell/"` instead of the first writable directoy in 'runtimepath'. • |vim.version.range()| doesn't exclude `to` if it is equal to `from`. diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 4740b03c17f175..4b98f487d30c52 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -5795,7 +5795,7 @@ A jump table for the options with a short description can be found at |Q_op|. |zg| and |zw| commands can be used to access each. This allows using a personal word list file and a project word list file. When a word is added while this option is empty Nvim will use - (and auto-create) `stdpath('data')/spell/`. For the file name the + (and auto-create) `stdpath('data')/site/spell/`. For the file name the first language name that appears in 'spelllang' is used, ignoring the region. The resulting ".spl" file will be used for spell checking, it does not diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index d475ef1f3dd10a..7ffb5055282919 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -79,7 +79,7 @@ Defaults *defaults* *nvim-defaults* - 'showcmd' is enabled - 'sidescroll' defaults to 1 - 'smarttab' is enabled -- 'spellfile' defaults to `stdpath("data").."/spell/"` +- 'spellfile' defaults to `stdpath("data").."/site/spell/"` - 'startofline' is disabled - 'switchbuf' defaults to "uselast" - 'tabpagemax' defaults to 50 diff --git a/runtime/lua/vim/_meta/options.lua b/runtime/lua/vim/_meta/options.lua index a73204c88b8449..956a22bd4b3d9f 100644 --- a/runtime/lua/vim/_meta/options.lua +++ b/runtime/lua/vim/_meta/options.lua @@ -6169,7 +6169,7 @@ vim.bo.spc = vim.bo.spellcapcheck --- `zg` and `zw` commands can be used to access each. This allows using --- a personal word list file and a project word list file. --- When a word is added while this option is empty Nvim will use ---- (and auto-create) `stdpath('data')/spell/`. For the file name the +--- (and auto-create) `stdpath('data')/site/spell/`. For the file name the --- first language name that appears in 'spelllang' is used, ignoring the --- region. --- The resulting ".spl" file will be used for spell checking, it does not diff --git a/src/nvim/options.lua b/src/nvim/options.lua index 504e5defa138c4..d43a71e5e9406f 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -8216,7 +8216,7 @@ local options = { |zg| and |zw| commands can be used to access each. This allows using a personal word list file and a project word list file. When a word is added while this option is empty Nvim will use - (and auto-create) `stdpath('data')/spell/`. For the file name the + (and auto-create) `stdpath('data')/site/spell/`. For the file name the first language name that appears in 'spelllang' is used, ignoring the region. The resulting ".spl" file will be used for spell checking, it does not diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index 44e084dd2a2fb8..743e7916d17d25 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -5550,7 +5550,7 @@ void spell_add_word(char *word, int len, SpellAddType what, int idx, bool undo) // Initialize 'spellfile' for the current buffer. // // If the location does not exist, create it. Defaults to -// stdpath("data") + "/spell/{spelllang}.{encoding}.add". +// stdpath("data") + "/site/spell/{spelllang}.{encoding}.add". static void init_spellfile(void) { char *lend; @@ -5579,7 +5579,7 @@ static void init_spellfile(void) xstrlcpy(buf, xdg_path, buf_len); xfree(xdg_path); - xstrlcat(buf, "/spell", buf_len); + xstrlcat(buf, "/site/spell", buf_len); char *failed_dir; if (os_mkdir_recurse(buf, 0755, &failed_dir, NULL) != 0) { diff --git a/test/functional/core/spellfile_spec.lua b/test/functional/core/spellfile_spec.lua index 96841f030ee11e..90531de429d865 100644 --- a/test/functional/core/spellfile_spec.lua +++ b/test/functional/core/spellfile_spec.lua @@ -119,12 +119,12 @@ describe('spellfile', function() end) describe('default location', function() - it("is stdpath('data')/spell/en.utf-8.add", function() + it("is stdpath('data')/site/spell/en.utf-8.add", function() n.command('set spell') n.insert('abc') n.feed('zg') eq( - t.fix_slashes(fn.stdpath('data') .. '/spell/en.utf-8.add'), + t.fix_slashes(fn.stdpath('data') .. '/site/spell/en.utf-8.add'), t.fix_slashes(api.nvim_get_option_value('spellfile', {})) ) end)
diff --git a/runtime/doc/news.txt b/runtime/doc/news.txt index 48162b9fa207e5..740036297bdb3c 100644 --- a/runtime/doc/news.txt +++ b/runtime/doc/news.txt @@ -186,7 +186,7 @@ CHANGED FEATURES *news-changed* These existing features changed their behavior. -• 'spellfile' location defaults to `stdpath("data").."/spell/"` instead of the +• 'spellfile' location defaults to `stdpath("data").."/site/spell/"` instead of the first writable directoy in 'runtimepath'. • |vim.version.range()| doesn't exclude `to` if it is equal to `from`. diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index 4740b03c17f175..4b98f487d30c52 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -5795,7 +5795,7 @@ A jump table for the options with a short description can be found at |Q_op|. |zg| and |zw| commands can be used to access each. This allows using a personal word list file and a project word list file. When a word is added while this option is empty Nvim will use - (and auto-create) `stdpath('data')/spell/`. For the file name the + (and auto-create) `stdpath('data')/site/spell/`. For the file name the first language name that appears in 'spelllang' is used, ignoring the region. The resulting ".spl" file will be used for spell checking, it does not diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index d475ef1f3dd10a..7ffb5055282919 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -79,7 +79,7 @@ Defaults *defaults* *nvim-defaults* - 'showcmd' is enabled - 'sidescroll' defaults to 1 - 'smarttab' is enabled -- 'spellfile' defaults to `stdpath("data").."/spell/"` +- 'spellfile' defaults to `stdpath("data").."/site/spell/"` - 'startofline' is disabled - 'switchbuf' defaults to "uselast" - 'tabpagemax' defaults to 50 diff --git a/runtime/lua/vim/_meta/options.lua b/runtime/lua/vim/_meta/options.lua index a73204c88b8449..956a22bd4b3d9f 100644 --- a/runtime/lua/vim/_meta/options.lua +++ b/runtime/lua/vim/_meta/options.lua @@ -6169,7 +6169,7 @@ vim.bo.spc = vim.bo.spellcapcheck --- `zg` and `zw` commands can be used to access each. This allows using --- a personal word list file and a project word list file. --- When a word is added while this option is empty Nvim will use ---- (and auto-create) `stdpath('data')/spell/`. For the file name the +--- (and auto-create) `stdpath('data')/site/spell/`. For the file name the --- first language name that appears in 'spelllang' is used, ignoring the --- region. --- The resulting ".spl" file will be used for spell checking, it does not diff --git a/src/nvim/options.lua b/src/nvim/options.lua index 504e5defa138c4..d43a71e5e9406f 100644 --- a/src/nvim/options.lua +++ b/src/nvim/options.lua @@ -8216,7 +8216,7 @@ local options = { |zg| and |zw| commands can be used to access each. This allows using a personal word list file and a project word list file. When a word is added while this option is empty Nvim will use - (and auto-create) `stdpath('data')/spell/`. For the file name the + (and auto-create) `stdpath('data')/site/spell/`. For the file name the first language name that appears in 'spelllang' is used, ignoring the region. The resulting ".spl" file will be used for spell checking, it does not diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c index 44e084dd2a2fb8..743e7916d17d25 100644 --- a/src/nvim/spellfile.c +++ b/src/nvim/spellfile.c @@ -5550,7 +5550,7 @@ void spell_add_word(char *word, int len, SpellAddType what, int idx, bool undo) // Initialize 'spellfile' for the current buffer. // // If the location does not exist, create it. Defaults to -// stdpath("data") + "/spell/{spelllang}.{encoding}.add". static void init_spellfile(void) { char *lend; @@ -5579,7 +5579,7 @@ static void init_spellfile(void) xstrlcpy(buf, xdg_path, buf_len); xfree(xdg_path); - xstrlcat(buf, "/spell", buf_len); + xstrlcat(buf, "/site/spell", buf_len); char *failed_dir; if (os_mkdir_recurse(buf, 0755, &failed_dir, NULL) != 0) { diff --git a/test/functional/core/spellfile_spec.lua b/test/functional/core/spellfile_spec.lua index 96841f030ee11e..90531de429d865 100644 --- a/test/functional/core/spellfile_spec.lua +++ b/test/functional/core/spellfile_spec.lua @@ -119,12 +119,12 @@ describe('spellfile', function() end) describe('default location', function() - it("is stdpath('data')/spell/en.utf-8.add", function() + it("is stdpath('data')/site/spell/en.utf-8.add", function() n.command('set spell') n.insert('abc') n.feed('zg') eq( + t.fix_slashes(fn.stdpath('data') .. '/site/spell/en.utf-8.add'), t.fix_slashes(api.nvim_get_option_value('spellfile', {})) ) end)
[ "+// stdpath(\"data\") + \"/site/spell/{spelllang}.{encoding}.add\".", "- t.fix_slashes(fn.stdpath('data') .. '/spell/en.utf-8.add')," ]
[ 74, 101 ]
{ "additions": 9, "author": "acehinnnqru", "deletions": 8, "html_url": "https://github.com/neovim/neovim/pull/33528", "issue_id": 33528, "merged_at": "2025-04-18T15:56:20Z", "omission_probability": 0.1, "pr_number": 33528, "repo": "neovim/neovim", "title": "fix(spell): save spell files to stdpath('data')/site/spell", "total_changes": 17 }
387
diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 80a1ed9667905b..2a605303c739a4 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -3099,7 +3099,7 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off) if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) { return FAIL; } - if (fprintf(fd, "%" PRId64 ",%" PRId64 "fold", + if (fprintf(fd, "sil! %" PRId64 ",%" PRId64 "fold", (int64_t)fp->fd_top + off, (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0 || put_eol(fd) == FAIL) { @@ -3121,9 +3121,10 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off if (fp->fd_flags != FD_LEVEL) { if (!GA_EMPTY(&fp->fd_nested)) { // open nested folds while this fold is open + // ignore errors if (fprintf(fd, "%" PRId64, (int64_t)fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || put_line(fd, "normal! zo") == FAIL) { + || put_line(fd, "sil! normal! zo") == FAIL) { return FAIL; } if (put_foldopen_recurse(fd, wp, &fp->fd_nested, @@ -3164,7 +3165,7 @@ static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off) { if (fprintf(fd, "%" PRIdLINENR, fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || fprintf(fd, "normal! z%c", + || fprintf(fd, "sil! normal! z%c", fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 || put_eol(fd) == FAIL) { return FAIL; diff --git a/test/old/testdir/setup.vim b/test/old/testdir/setup.vim index 87287a57ffb78b..b1ee4e3a3d8a7d 100644 --- a/test/old/testdir/setup.vim +++ b/test/old/testdir/setup.vim @@ -109,6 +109,14 @@ if executable('gem') let $GEM_PATH = system('gem env gempath') endif +" Have current $HOME available as $ORIGHOME. $HOME is used for option +" defaults before we get here, and test_mksession checks that. +let $ORIGHOME = $HOME + +if !exists('$XDG_CONFIG_HOME') + let $XDG_CONFIG_HOME = $HOME .. '/.config' +endif + " Make sure $HOME does not get read or written. let $HOME = expand(getcwd() . '/XfakeHOME') if !isdirectory($HOME) diff --git a/test/old/testdir/test_mksession.vim b/test/old/testdir/test_mksession.vim index 7e9cd6c8e8ce5a..8c9b3f1c227def 100644 --- a/test/old/testdir/test_mksession.vim +++ b/test/old/testdir/test_mksession.vim @@ -1170,8 +1170,8 @@ endfunc " Test for creating views with manual folds func Test_mkview_manual_fold() - call writefile(range(1,10), 'Xfile') - new Xfile + call writefile(range(1,10), 'Xmkvfile', 'D') + new Xmkvfile " create recursive folds 5,6fold 4,7fold @@ -1194,9 +1194,44 @@ func Test_mkview_manual_fold() source Xview call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) - call delete('Xfile') call delete('Xview') bw! endfunc +" Test for handling invalid folds within views +func Test_mkview_ignore_invalid_folds() + call writefile(range(1,10), 'Xmkvfile', 'D') + new Xmkvfile + " create some folds + 5,6fold + 4,7fold + mkview Xview + normal zE + " delete lines to make folds invalid + call deletebufline('', 6, '$') + source Xview + call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + call delete('Xview') + bw! +endfunc + +" Test default 'viewdir' value +func Test_mkview_default_home() + throw 'Skipped: N/A' + if has('win32') + " use escape() to handle backslash path separators + call assert_match('^' .. escape($ORIGHOME, '\') .. '/vimfiles', &viewdir) + elseif has('unix') + call assert_match( + \ '^' .. $ORIGHOME .. '/.vim\|' .. + \ '^' .. $XDG_CONFIG_HOME .. '/vim' + \ , &viewdir) + elseif has('amiga') + call assert_match('^home:vimfiles', &viewdir) + elseif has('mac') + call assert_match('^' .. $VIM .. '/vimfiles', &viewdir) + endif +endfunc + " vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 80a1ed9667905b..2a605303c739a4 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -3099,7 +3099,7 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off) if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) { return FAIL; } - if (fprintf(fd, "%" PRId64 ",%" PRId64 "fold", + if (fprintf(fd, "sil! %" PRId64 ",%" PRId64 "fold", (int64_t)fp->fd_top + off, (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0 || put_eol(fd) == FAIL) { @@ -3121,9 +3121,10 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off if (fp->fd_flags != FD_LEVEL) { if (!GA_EMPTY(&fp->fd_nested)) { // open nested folds while this fold is open + // ignore errors if (fprintf(fd, "%" PRId64, (int64_t)fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || put_line(fd, "normal! zo") == FAIL) { + || put_line(fd, "sil! normal! zo") == FAIL) { return FAIL; } if (put_foldopen_recurse(fd, wp, &fp->fd_nested, @@ -3164,7 +3165,7 @@ static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off) { if (fprintf(fd, "%" PRIdLINENR, fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || fprintf(fd, "normal! z%c", + || fprintf(fd, "sil! normal! z%c", fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 || put_eol(fd) == FAIL) { return FAIL; diff --git a/test/old/testdir/setup.vim b/test/old/testdir/setup.vim index 87287a57ffb78b..b1ee4e3a3d8a7d 100644 --- a/test/old/testdir/setup.vim +++ b/test/old/testdir/setup.vim @@ -109,6 +109,14 @@ if executable('gem') let $GEM_PATH = system('gem env gempath') endif +" Have current $HOME available as $ORIGHOME. $HOME is used for option +" defaults before we get here, and test_mksession checks that. +if !exists('$XDG_CONFIG_HOME') + let $XDG_CONFIG_HOME = $HOME .. '/.config' +endif " Make sure $HOME does not get read or written. let $HOME = expand(getcwd() . '/XfakeHOME') if !isdirectory($HOME) diff --git a/test/old/testdir/test_mksession.vim b/test/old/testdir/test_mksession.vim index 7e9cd6c8e8ce5a..8c9b3f1c227def 100644 --- a/test/old/testdir/test_mksession.vim +++ b/test/old/testdir/test_mksession.vim @@ -1170,8 +1170,8 @@ endfunc " Test for creating views with manual folds func Test_mkview_manual_fold() - call writefile(range(1,10), 'Xfile') - new Xfile " create recursive folds 5,6fold 4,7fold @@ -1194,9 +1194,44 @@ func Test_mkview_manual_fold() source Xview call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) - call delete('Xfile') call delete('Xview') bw! endfunc +" Test for handling invalid folds within views +func Test_mkview_ignore_invalid_folds() + " create some folds + 5,6fold + 4,7fold + mkview Xview + normal zE + call deletebufline('', 6, '$') + source Xview + call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + call delete('Xview') + bw! +" Test default 'viewdir' value +func Test_mkview_default_home() + throw 'Skipped: N/A' + if has('win32') + " use escape() to handle backslash path separators + call assert_match('^' .. escape($ORIGHOME, '\') .. '/vimfiles', &viewdir) + elseif has('unix') + call assert_match( + \ '^' .. $ORIGHOME .. '/.vim\|' .. + \ '^' .. $XDG_CONFIG_HOME .. '/vim' + \ , &viewdir) + elseif has('amiga') + call assert_match('^home:vimfiles', &viewdir) + elseif has('mac') + call assert_match('^' .. $VIM .. '/vimfiles', &viewdir) + endif " vim: shiftwidth=2 sts=2 expandtab
[ "+let $ORIGHOME = $HOME", "+ \" delete lines to make folds invalid" ]
[ 44, 86 ]
{ "additions": 50, "author": "neovim-backports[bot]", "deletions": 6, "html_url": "https://github.com/neovim/neovim/pull/33522", "issue_id": 33522, "merged_at": "2025-04-18T01:04:02Z", "omission_probability": 0.1, "pr_number": 33522, "repo": "neovim/neovim", "title": "vim-patch:9.0.{1653,1654},9.1.{0721,1317}", "total_changes": 56 }
388
diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 80a1ed9667905b..2a605303c739a4 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -3099,7 +3099,7 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off) if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) { return FAIL; } - if (fprintf(fd, "%" PRId64 ",%" PRId64 "fold", + if (fprintf(fd, "sil! %" PRId64 ",%" PRId64 "fold", (int64_t)fp->fd_top + off, (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0 || put_eol(fd) == FAIL) { @@ -3121,9 +3121,10 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off if (fp->fd_flags != FD_LEVEL) { if (!GA_EMPTY(&fp->fd_nested)) { // open nested folds while this fold is open + // ignore errors if (fprintf(fd, "%" PRId64, (int64_t)fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || put_line(fd, "normal! zo") == FAIL) { + || put_line(fd, "sil! normal! zo") == FAIL) { return FAIL; } if (put_foldopen_recurse(fd, wp, &fp->fd_nested, @@ -3164,7 +3165,7 @@ static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off) { if (fprintf(fd, "%" PRIdLINENR, fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || fprintf(fd, "normal! z%c", + || fprintf(fd, "sil! normal! z%c", fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 || put_eol(fd) == FAIL) { return FAIL; diff --git a/test/old/testdir/setup.vim b/test/old/testdir/setup.vim index a6c7917f630829..d81a8f61cff4c5 100644 --- a/test/old/testdir/setup.vim +++ b/test/old/testdir/setup.vim @@ -110,6 +110,14 @@ if executable('gem') let $GEM_PATH = system('gem env gempath') endif +" Have current $HOME available as $ORIGHOME. $HOME is used for option +" defaults before we get here, and test_mksession checks that. +let $ORIGHOME = $HOME + +if !exists('$XDG_CONFIG_HOME') + let $XDG_CONFIG_HOME = $HOME .. '/.config' +endif + " Make sure $HOME does not get read or written. let $HOME = expand(getcwd() . '/XfakeHOME') if !isdirectory($HOME) diff --git a/test/old/testdir/test_mksession.vim b/test/old/testdir/test_mksession.vim index 7e9cd6c8e8ce5a..8c9b3f1c227def 100644 --- a/test/old/testdir/test_mksession.vim +++ b/test/old/testdir/test_mksession.vim @@ -1170,8 +1170,8 @@ endfunc " Test for creating views with manual folds func Test_mkview_manual_fold() - call writefile(range(1,10), 'Xfile') - new Xfile + call writefile(range(1,10), 'Xmkvfile', 'D') + new Xmkvfile " create recursive folds 5,6fold 4,7fold @@ -1194,9 +1194,44 @@ func Test_mkview_manual_fold() source Xview call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) - call delete('Xfile') call delete('Xview') bw! endfunc +" Test for handling invalid folds within views +func Test_mkview_ignore_invalid_folds() + call writefile(range(1,10), 'Xmkvfile', 'D') + new Xmkvfile + " create some folds + 5,6fold + 4,7fold + mkview Xview + normal zE + " delete lines to make folds invalid + call deletebufline('', 6, '$') + source Xview + call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + call delete('Xview') + bw! +endfunc + +" Test default 'viewdir' value +func Test_mkview_default_home() + throw 'Skipped: N/A' + if has('win32') + " use escape() to handle backslash path separators + call assert_match('^' .. escape($ORIGHOME, '\') .. '/vimfiles', &viewdir) + elseif has('unix') + call assert_match( + \ '^' .. $ORIGHOME .. '/.vim\|' .. + \ '^' .. $XDG_CONFIG_HOME .. '/vim' + \ , &viewdir) + elseif has('amiga') + call assert_match('^home:vimfiles', &viewdir) + elseif has('mac') + call assert_match('^' .. $VIM .. '/vimfiles', &viewdir) + endif +endfunc + " vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/fold.c b/src/nvim/fold.c index 80a1ed9667905b..2a605303c739a4 100644 --- a/src/nvim/fold.c +++ b/src/nvim/fold.c @@ -3099,7 +3099,7 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off) if (put_folds_recurse(fd, &fp->fd_nested, off + fp->fd_top) == FAIL) { return FAIL; } - if (fprintf(fd, "%" PRId64 ",%" PRId64 "fold", + if (fprintf(fd, "sil! %" PRId64 ",%" PRId64 "fold", (int64_t)fp->fd_top + off, (int64_t)(fp->fd_top + off + fp->fd_len - 1)) < 0 || put_eol(fd) == FAIL) { @@ -3121,9 +3121,10 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off if (fp->fd_flags != FD_LEVEL) { if (!GA_EMPTY(&fp->fd_nested)) { // open nested folds while this fold is open + // ignore errors if (fprintf(fd, "%" PRId64, (int64_t)fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || put_line(fd, "normal! zo") == FAIL) { + || put_line(fd, "sil! normal! zo") == FAIL) { return FAIL; } if (put_foldopen_recurse(fd, wp, &fp->fd_nested, @@ -3164,7 +3165,7 @@ static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off) { if (fprintf(fd, "%" PRIdLINENR, fp->fd_top + off) < 0 || put_eol(fd) == FAIL - || fprintf(fd, "normal! z%c", + || fprintf(fd, "sil! normal! z%c", fp->fd_flags == FD_CLOSED ? 'c' : 'o') < 0 || put_eol(fd) == FAIL) { return FAIL; diff --git a/test/old/testdir/setup.vim b/test/old/testdir/setup.vim index a6c7917f630829..d81a8f61cff4c5 100644 --- a/test/old/testdir/setup.vim +++ b/test/old/testdir/setup.vim @@ -110,6 +110,14 @@ if executable('gem') let $GEM_PATH = system('gem env gempath') endif +" Have current $HOME available as $ORIGHOME. $HOME is used for option +" defaults before we get here, and test_mksession checks that. +if !exists('$XDG_CONFIG_HOME') + let $XDG_CONFIG_HOME = $HOME .. '/.config' +endif " Make sure $HOME does not get read or written. let $HOME = expand(getcwd() . '/XfakeHOME') if !isdirectory($HOME) diff --git a/test/old/testdir/test_mksession.vim b/test/old/testdir/test_mksession.vim index 7e9cd6c8e8ce5a..8c9b3f1c227def 100644 --- a/test/old/testdir/test_mksession.vim +++ b/test/old/testdir/test_mksession.vim @@ -1170,8 +1170,8 @@ endfunc " Test for creating views with manual folds func Test_mkview_manual_fold() - call writefile(range(1,10), 'Xfile') - new Xfile " create recursive folds 5,6fold 4,7fold @@ -1194,9 +1194,44 @@ func Test_mkview_manual_fold() source Xview call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) - call delete('Xfile') call delete('Xview') bw! endfunc +" Test for handling invalid folds within views +func Test_mkview_ignore_invalid_folds() + " create some folds + 5,6fold + 4,7fold + mkview Xview + call deletebufline('', 6, '$') + call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + call delete('Xview') +func Test_mkview_default_home() + throw 'Skipped: N/A' + if has('win32') + " use escape() to handle backslash path separators + call assert_match('^' .. escape($ORIGHOME, '\') .. '/vimfiles', &viewdir) + elseif has('unix') + \ '^' .. $ORIGHOME .. '/.vim\|' .. + \ , &viewdir) + elseif has('amiga') + elseif has('mac') + call assert_match('^' .. $VIM .. '/vimfiles', &viewdir) + endif " vim: shiftwidth=2 sts=2 expandtab
[ "+let $ORIGHOME = $HOME", "+ normal zE", "+ \" delete lines to make folds invalid", "+ source Xview", "+ bw!", "+\" Test default 'viewdir' value", "+ call assert_match(", "+ \\ '^' .. $XDG_CONFIG_HOME .. '/vim'", "+ call assert_match('^home:vimfiles', &viewdir)" ]
[ 44, 85, 86, 88, 92, 95, 102, 104, 107 ]
{ "additions": 50, "author": "zeertzjq", "deletions": 6, "html_url": "https://github.com/neovim/neovim/pull/33521", "issue_id": 33521, "merged_at": "2025-04-18T00:30:21Z", "omission_probability": 0.1, "pr_number": 33521, "repo": "neovim/neovim", "title": "vim-patch:9.0.{1653,1654},9.1.{0721,1317}", "total_changes": 56 }
389
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index dea767ac3ae28a..ab8bf2eec81465 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -5102,7 +5102,6 @@ static int ins_compl_start(void) line = ml_get(curwin->w_cursor.lnum); } - bool in_fuzzy = get_cot_flags() & kOptCotFlagFuzzy; if (compl_status_adding()) { edit_submode_pre = _(" Adding"); if (ctrl_x_mode_line_or_eval()) { @@ -5117,7 +5116,7 @@ static int ins_compl_start(void) compl_length = 0; compl_col = curwin->w_cursor.col; compl_lnum = curwin->w_cursor.lnum; - } else if (ctrl_x_mode_normal() && in_fuzzy) { + } else if (ctrl_x_mode_normal() && cfc_has_mode()) { compl_startpos = curwin->w_cursor; compl_cont_status &= CONT_S_IPOS; } diff --git a/src/nvim/search.c b/src/nvim/search.c index fe8e54fed49de8..03a6fa69f4bafa 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -3745,22 +3745,6 @@ bool search_for_fuzzy_match(buf_T *buf, pos_T *pos, char *pattern, int dir, pos_ found_new_match = fuzzy_match_str_in_line(ptr, pattern, len, &current_pos, score); if (found_new_match) { - if (ctrl_x_mode_normal()) { - if (strncmp(*ptr, pattern, (size_t)(*len)) == 0 && pattern[*len] == NUL) { - char *next_word_end = find_word_start(*ptr + *len); - if (*next_word_end != NUL && *next_word_end != NL) { - // Find end of the word. - while (*next_word_end != NUL) { - int l = utfc_ptr2len(next_word_end); - if (l < 2 && !vim_iswordc(*next_word_end)) { - break; - } - next_word_end += l; - } - } - *len = (int)(next_word_end - *ptr); - } - } *pos = current_pos; break; } else if (looped_around && current_pos.lnum == circly_end.lnum) { diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index c5e2bc8a740ec2..f3c1a6fbcb47df 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -2869,6 +2869,14 @@ func Test_complete_opt_fuzzy() call feedkeys("Sb\<C-X>\<C-P>\<C-N>\<C-Y>\<ESC>", 'tx') call assert_equal('b', getline('.')) + " chain completion + call feedkeys("Slore spum\<CR>lor\<C-X>\<C-P>\<C-X>\<C-P>\<ESC>", 'tx') + call assert_equal('lore spum', getline('.')) + + " issue #15412 + call feedkeys("Salpha bravio charlie\<CR>alpha\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<ESC>", 'tx') + call assert_equal('alpha bravio charlie', getline('.')) + " clean up set omnifunc= bw! @@ -2955,34 +2963,6 @@ func Test_complete_fuzzy_collect() call feedkeys("Su\<C-X>\<C-L>\<C-P>\<Esc>0", 'tx!') call assert_equal('no one can save me but you', getline('.')) - " issue #15412 - call setline(1, ['alpha bravio charlie']) - call feedkeys("Salpha\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha bravio', getline('.')) - call feedkeys("Salp\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha', getline('.')) - call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha bravio', getline('.')) - call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha bravio charlie', getline('.')) - - set complete-=i - call feedkeys("Salp\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha', getline('.')) - call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha bravio', getline('.')) - call feedkeys("A\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha bravio charlie', getline('.')) - - call setline(1, ['alpha bravio charlie', 'alpha another']) - call feedkeys("Salpha\<C-X>\<C-N>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha another', getline('.')) - call setline(1, ['你好 我好', '你好 他好']) - call feedkeys("S你好\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('你好 我好', getline('.')) - call feedkeys("S你好\<C-X>\<C-N>\<C-N>\<Esc>0", 'tx!') - call assert_equal('你好 他好', getline('.')) - " issue #15526 set completeopt=menuone,menu,noselect call setline(1, ['Text', 'ToText', '']) @@ -3008,6 +2988,11 @@ func Test_complete_fuzzy_collect() call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!') call assert_equal('completefuzzycollect', getline('.')) + execute('%d _') + call setline(1, ['fuzzy', 'fuzzy foo', "fuzzy bar", 'fuzzycollect']) + call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!') + call assert_equal('fuzzycollect', getline('.')) + bw! bw! set dict&
diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index dea767ac3ae28a..ab8bf2eec81465 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -5102,7 +5102,6 @@ static int ins_compl_start(void) line = ml_get(curwin->w_cursor.lnum); } - bool in_fuzzy = get_cot_flags() & kOptCotFlagFuzzy; if (compl_status_adding()) { edit_submode_pre = _(" Adding"); if (ctrl_x_mode_line_or_eval()) { @@ -5117,7 +5116,7 @@ static int ins_compl_start(void) compl_length = 0; compl_col = curwin->w_cursor.col; compl_lnum = curwin->w_cursor.lnum; - } else if (ctrl_x_mode_normal() && in_fuzzy) { + } else if (ctrl_x_mode_normal() && cfc_has_mode()) { compl_startpos = curwin->w_cursor; compl_cont_status &= CONT_S_IPOS; } diff --git a/src/nvim/search.c b/src/nvim/search.c index fe8e54fed49de8..03a6fa69f4bafa 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -3745,22 +3745,6 @@ bool search_for_fuzzy_match(buf_T *buf, pos_T *pos, char *pattern, int dir, pos_ found_new_match = fuzzy_match_str_in_line(ptr, pattern, len, &current_pos, score); if (found_new_match) { - if (ctrl_x_mode_normal()) { - if (strncmp(*ptr, pattern, (size_t)(*len)) == 0 && pattern[*len] == NUL) { - if (*next_word_end != NUL && *next_word_end != NL) { - // Find end of the word. - while (*next_word_end != NUL) { - int l = utfc_ptr2len(next_word_end); - if (l < 2 && !vim_iswordc(*next_word_end)) { - break; - } - next_word_end += l; - } - } - *len = (int)(next_word_end - *ptr); - } - } *pos = current_pos; break; } else if (looped_around && current_pos.lnum == circly_end.lnum) { diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim index c5e2bc8a740ec2..f3c1a6fbcb47df 100644 --- a/test/old/testdir/test_ins_complete.vim +++ b/test/old/testdir/test_ins_complete.vim @@ -2869,6 +2869,14 @@ func Test_complete_opt_fuzzy() call feedkeys("Sb\<C-X>\<C-P>\<C-N>\<C-Y>\<ESC>", 'tx') call assert_equal('b', getline('.')) + call feedkeys("Slore spum\<CR>lor\<C-X>\<C-P>\<C-X>\<C-P>\<ESC>", 'tx') + call assert_equal('lore spum', getline('.')) + " issue #15412 + call feedkeys("Salpha bravio charlie\<CR>alpha\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<ESC>", 'tx') " clean up set omnifunc= @@ -2955,34 +2963,6 @@ func Test_complete_fuzzy_collect() call feedkeys("Su\<C-X>\<C-L>\<C-P>\<Esc>0", 'tx!') call assert_equal('no one can save me but you', getline('.')) - " issue #15412 - call setline(1, ['alpha bravio charlie']) - call feedkeys("Salpha\<C-X>\<C-N>\<Esc>0", 'tx!') - set complete-=i - call setline(1, ['alpha bravio charlie', 'alpha another']) - call feedkeys("Salpha\<C-X>\<C-N>\<C-N>\<Esc>0", 'tx!') - call assert_equal('alpha another', getline('.')) - call setline(1, ['你好 我好', '你好 他好']) - call feedkeys("S你好\<C-X>\<C-N>\<Esc>0", 'tx!') - call assert_equal('你好 我好', getline('.')) - call feedkeys("S你好\<C-X>\<C-N>\<C-N>\<Esc>0", 'tx!') - call assert_equal('你好 他好', getline('.')) " issue #15526 set completeopt=menuone,menu,noselect call setline(1, ['Text', 'ToText', '']) @@ -3008,6 +2988,11 @@ func Test_complete_fuzzy_collect() call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!') call assert_equal('completefuzzycollect', getline('.')) + execute('%d _') + call setline(1, ['fuzzy', 'fuzzy foo', "fuzzy bar", 'fuzzycollect']) + call feedkeys("Gofuzzy\<C-X>\<C-N>\<C-N>\<C-N>\<C-Y>\<Esc>0", 'tx!') + call assert_equal('fuzzycollect', getline('.')) set dict&
[ "- char *next_word_end = find_word_start(*ptr + *len);", "+ \" chain completion", "+ call assert_equal('alpha bravio charlie', getline('.'))" ]
[ 31, 56, 62 ]
{ "additions": 14, "author": "zeertzjq", "deletions": 46, "html_url": "https://github.com/neovim/neovim/pull/33520", "issue_id": 33520, "merged_at": "2025-04-17T23:22:50Z", "omission_probability": 0.1, "pr_number": 33520, "repo": "neovim/neovim", "title": "vim-patch:9.1.1315: completion: issue with fuzzy completion and 'completefuzzycollect'", "total_changes": 60 }
390
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bd78f1ad505a0c..3fc567b6948116 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -215,7 +215,13 @@ local function get_locations(method, opts) vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't') vim.bo[b].buflisted = true - local w = opts.reuse_win and vim.fn.win_findbuf(b)[1] or win + local w = win + if opts.reuse_win then + w = vim.fn.win_findbuf(b)[1] or w + if w ~= win then + api.nvim_set_current_win(w) + end + end api.nvim_win_set_buf(w, b) api.nvim_win_set_cursor(w, { item.lnum, item.col - 1 }) vim._with({ win = w }, function() diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index 22758319661e77..1ee145f92020d6 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -5230,7 +5230,7 @@ describe('LSP', function() end) describe('lsp.buf.definition', function() - it('jumps to single location', function() + it('jumps to single location and can reuse win', function() exec_lua(create_server_definition) local result = exec_lua(function() local bufnr = vim.api.nvim_get_current_buf() @@ -5256,8 +5256,10 @@ describe('LSP', function() vim.api.nvim_win_set_cursor(win, { 3, 6 }) local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd })) vim.lsp.buf.definition() - vim.lsp.stop_client(client_id) return { + win = win, + bufnr = bufnr, + client_id = client_id, cursor = vim.api.nvim_win_get_cursor(win), messages = server.messages, tagstack = vim.fn.gettagstack(win), @@ -5269,6 +5271,15 @@ describe('LSP', function() eq('x', result.tagstack.items[1].tagname) eq(3, result.tagstack.items[1].from[2]) eq(7, result.tagstack.items[1].from[3]) + + n.feed(':vnew<CR>') + api.nvim_win_set_buf(0, result.bufnr) + api.nvim_win_set_cursor(0, { 3, 6 }) + n.feed(':=vim.lsp.buf.definition({ reuse_win = true })<CR>') + eq(result.win, api.nvim_get_current_win()) + exec_lua(function() + vim.lsp.stop_client(result.client_id) + end) end) it('merges results from multiple servers', function() exec_lua(create_server_definition)
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bd78f1ad505a0c..3fc567b6948116 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -215,7 +215,13 @@ local function get_locations(method, opts) vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't') vim.bo[b].buflisted = true - local w = opts.reuse_win and vim.fn.win_findbuf(b)[1] or win + local w = win + w = vim.fn.win_findbuf(b)[1] or w + if w ~= win then + api.nvim_set_current_win(w) + end + end api.nvim_win_set_buf(w, b) api.nvim_win_set_cursor(w, { item.lnum, item.col - 1 }) vim._with({ win = w }, function() diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index 22758319661e77..1ee145f92020d6 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -5230,7 +5230,7 @@ describe('LSP', function() end) describe('lsp.buf.definition', function() + it('jumps to single location and can reuse win', function() local result = exec_lua(function() local bufnr = vim.api.nvim_get_current_buf() @@ -5256,8 +5256,10 @@ describe('LSP', function() vim.api.nvim_win_set_cursor(win, { 3, 6 }) local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd })) vim.lsp.buf.definition() - vim.lsp.stop_client(client_id) return { + win = win, + bufnr = bufnr, + client_id = client_id, cursor = vim.api.nvim_win_get_cursor(win), messages = server.messages, tagstack = vim.fn.gettagstack(win), @@ -5269,6 +5271,15 @@ describe('LSP', function() eq('x', result.tagstack.items[1].tagname) eq(3, result.tagstack.items[1].from[2]) eq(7, result.tagstack.items[1].from[3]) + n.feed(':vnew<CR>') + api.nvim_win_set_buf(0, result.bufnr) + api.nvim_win_set_cursor(0, { 3, 6 }) + n.feed(':=vim.lsp.buf.definition({ reuse_win = true })<CR>') + eq(result.win, api.nvim_get_current_win()) + exec_lua(function() + vim.lsp.stop_client(result.client_id) + end) end) it('merges results from multiple servers', function()
[ "+ if opts.reuse_win then", "- it('jumps to single location', function()", "+" ]
[ 10, 27, 48 ]
{ "additions": 20, "author": "neovim-backports[bot]", "deletions": 3, "html_url": "https://github.com/neovim/neovim/pull/33514", "issue_id": 33514, "merged_at": "2025-04-17T15:12:47Z", "omission_probability": 0.1, "pr_number": 33514, "repo": "neovim/neovim", "title": "fix(lsp): jump to the target win when opts.reuse_win is true", "total_changes": 23 }
391
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bd78f1ad505a0c..3fc567b6948116 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -215,7 +215,13 @@ local function get_locations(method, opts) vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't') vim.bo[b].buflisted = true - local w = opts.reuse_win and vim.fn.win_findbuf(b)[1] or win + local w = win + if opts.reuse_win then + w = vim.fn.win_findbuf(b)[1] or w + if w ~= win then + api.nvim_set_current_win(w) + end + end api.nvim_win_set_buf(w, b) api.nvim_win_set_cursor(w, { item.lnum, item.col - 1 }) vim._with({ win = w }, function() diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index ebb8f20aaa496f..78fcda610edebe 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -5230,7 +5230,7 @@ describe('LSP', function() end) describe('lsp.buf.definition', function() - it('jumps to single location', function() + it('jumps to single location and can reuse win', function() exec_lua(create_server_definition) local result = exec_lua(function() local bufnr = vim.api.nvim_get_current_buf() @@ -5256,8 +5256,10 @@ describe('LSP', function() vim.api.nvim_win_set_cursor(win, { 3, 6 }) local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd })) vim.lsp.buf.definition() - vim.lsp.stop_client(client_id) return { + win = win, + bufnr = bufnr, + client_id = client_id, cursor = vim.api.nvim_win_get_cursor(win), messages = server.messages, tagstack = vim.fn.gettagstack(win), @@ -5269,6 +5271,15 @@ describe('LSP', function() eq('x', result.tagstack.items[1].tagname) eq(3, result.tagstack.items[1].from[2]) eq(7, result.tagstack.items[1].from[3]) + + n.feed(':vnew<CR>') + api.nvim_win_set_buf(0, result.bufnr) + api.nvim_win_set_cursor(0, { 3, 6 }) + n.feed(':=vim.lsp.buf.definition({ reuse_win = true })<CR>') + eq(result.win, api.nvim_get_current_win()) + exec_lua(function() + vim.lsp.stop_client(result.client_id) + end) end) it('merges results from multiple servers', function() exec_lua(create_server_definition)
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bd78f1ad505a0c..3fc567b6948116 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -215,7 +215,13 @@ local function get_locations(method, opts) vim.fn.settagstack(vim.fn.win_getid(win), { items = tagstack }, 't') vim.bo[b].buflisted = true - local w = opts.reuse_win and vim.fn.win_findbuf(b)[1] or win + local w = win + if opts.reuse_win then + if w ~= win then + api.nvim_set_current_win(w) + end + end api.nvim_win_set_buf(w, b) api.nvim_win_set_cursor(w, { item.lnum, item.col - 1 }) vim._with({ win = w }, function() diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua index ebb8f20aaa496f..78fcda610edebe 100644 --- a/test/functional/plugin/lsp_spec.lua +++ b/test/functional/plugin/lsp_spec.lua @@ -5230,7 +5230,7 @@ describe('LSP', function() end) describe('lsp.buf.definition', function() - it('jumps to single location', function() + it('jumps to single location and can reuse win', function() local result = exec_lua(function() local bufnr = vim.api.nvim_get_current_buf() @@ -5256,8 +5256,10 @@ describe('LSP', function() vim.api.nvim_win_set_cursor(win, { 3, 6 }) local client_id = assert(vim.lsp.start({ name = 'dummy', cmd = server.cmd })) vim.lsp.buf.definition() - vim.lsp.stop_client(client_id) return { + win = win, + bufnr = bufnr, + client_id = client_id, cursor = vim.api.nvim_win_get_cursor(win), messages = server.messages, tagstack = vim.fn.gettagstack(win), @@ -5269,6 +5271,15 @@ describe('LSP', function() eq('x', result.tagstack.items[1].tagname) eq(3, result.tagstack.items[1].from[2]) eq(7, result.tagstack.items[1].from[3]) + + n.feed(':vnew<CR>') + api.nvim_win_set_buf(0, result.bufnr) + api.nvim_win_set_cursor(0, { 3, 6 }) + n.feed(':=vim.lsp.buf.definition({ reuse_win = true })<CR>') + eq(result.win, api.nvim_get_current_win()) + exec_lua(function() + vim.lsp.stop_client(result.client_id) + end) end) it('merges results from multiple servers', function()
[ "+ w = vim.fn.win_findbuf(b)[1] or w" ]
[ 11 ]
{ "additions": 20, "author": "acehinnnqru", "deletions": 3, "html_url": "https://github.com/neovim/neovim/pull/33476", "issue_id": 33476, "merged_at": "2025-04-17T14:46:18Z", "omission_probability": 0.1, "pr_number": 33476, "repo": "neovim/neovim", "title": "fix(lsp): jump to the target win when opts.reuse_win is true", "total_changes": 23 }
392
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 9f8e982d3a5dc6..c618be7fd941ee 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -1285,7 +1285,7 @@ end ---@since 7 --- ---@param bufnr integer Buffer handle, or 0 for current. ----@param method string LSP method name +---@param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name ---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server. --- Can also be passed as a function that returns the params table for cases where --- parameters are specific to the client. diff --git a/runtime/lua/vim/lsp/_meta/protocol.lua b/runtime/lua/vim/lsp/_meta/protocol.lua index 442efe9f03cb7a..7d588c0fd91793 100644 --- a/runtime/lua/vim/lsp/_meta/protocol.lua +++ b/runtime/lua/vim/lsp/_meta/protocol.lua @@ -1,11 +1,11 @@ --[[ -THIS FILE IS GENERATED by scripts/gen_lsp.lua +THIS FILE IS GENERATED by scr/gen/gen_lsp.lua DO NOT EDIT MANUALLY Based on LSP protocol 3.18 Regenerate: -nvim -l scripts/gen_lsp.lua gen --version 3.18 +nvim -l scr/gen/gen_lsp.lua gen --version 3.18 --]] ---@meta diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bd78f1ad505a0c..6ef2913ba2480d 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -158,7 +158,7 @@ local function request_with_opts(name, params, opts) lsp.buf_request(0, name, params, req_handler) end ----@param method string +---@param method vim.lsp.protocol.Method.ClientToServer.Request ---@param opts? vim.lsp.LocationOpts local function get_locations(method, opts) opts = opts or {} @@ -814,7 +814,7 @@ function M.document_symbol(opts) end --- @param client_id integer ---- @param method string +--- @param method vim.lsp.protocol.Method.ClientToServer.Request --- @param params table --- @param handler? lsp.Handler --- @param bufnr? integer @@ -845,7 +845,7 @@ local hierarchy_methods = { [ms.callHierarchy_outgoingCalls] = 'call', } ---- @param method string +--- @param method vim.lsp.protocol.Method.ClientToServer.Request local function hierarchy(method) local kind = hierarchy_methods[method] if not kind then diff --git a/runtime/lua/vim/lsp/client.lua b/runtime/lua/vim/lsp/client.lua index b256eab1a65301..2219876a3d2a33 100644 --- a/runtime/lua/vim/lsp/client.lua +++ b/runtime/lua/vim/lsp/client.lua @@ -656,7 +656,7 @@ end --- This is a thin wrapper around {client.rpc.request} with some additional --- checks for capabilities and handler availability. --- ---- @param method string LSP method name. +--- @param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name. --- @param params? table LSP request params. --- @param handler? lsp.Handler Response |lsp-handler| for this method. --- @param bufnr? integer (default: 0) Buffer handle, or 0 for current. @@ -721,7 +721,7 @@ end --- --- This is a wrapper around |Client:request()| --- ---- @param method string LSP method name. +--- @param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name. --- @param params table LSP request params. --- @param timeout_ms integer? Maximum time in milliseconds to wait for --- a result. Defaults to 1000 @@ -757,7 +757,7 @@ end --- Sends a notification to an LSP server. --- ---- @param method string LSP method name. +--- @param method vim.lsp.protocol.Method.ClientToServer.Notification LSP method name. --- @param params table? LSP request params. --- @return boolean status indicating if the notification was successful. --- If it is false, then the client has shutdown. @@ -828,7 +828,7 @@ function Client:stop(force) end --- Get options for a method that is registered dynamically. ---- @param method string +--- @param method vim.lsp.protocol.Method function Client:_supports_registration(method) local capability = vim.tbl_get(self.capabilities, unpack(vim.split(method, '/'))) return type(capability) == 'table' and capability.dynamicRegistration @@ -901,7 +901,7 @@ function Client:_get_language_id(bufnr) return self.get_language_id(bufnr, vim.bo[bufnr].filetype) end ---- @param method string +--- @param method vim.lsp.protocol.Method --- @param bufnr? integer --- @return lsp.Registration? function Client:_get_registration(method, bufnr) @@ -1051,7 +1051,7 @@ end --- Always returns true for unknown off-spec methods. --- --- Note: Some language server capabilities can be file specific. ---- @param method string +--- @param method vim.lsp.protocol.Method.ClientToServer --- @param bufnr? integer function Client:supports_method(method, bufnr) -- Deprecated form @@ -1082,27 +1082,11 @@ function Client:supports_method(method, bufnr) return false end ---- Get options for a method that is registered dynamically. ---- @param method string ---- @param bufnr? integer ---- @return lsp.LSPAny? -function Client:_get_registration_options(method, bufnr) - if not self:_supports_registration(method) then - return - end - - local reg = self:_get_registration(method, bufnr) - - if reg then - return reg.registerOptions - end -end - --- @private --- Handles a notification sent by an LSP server by invoking the --- corresponding handler. --- ---- @param method string LSP method name +--- @param method vim.lsp.protocol.Method.ServerToClient.Notification LSP method name --- @param params table The parameters for that method. function Client:_notification(method, params) log.trace('notification', method, params) diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index ececc41cee5c37..167dcb561b7cfc 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -621,22 +621,15 @@ function protocol.resolve_capabilities(server_capabilities) end -- Generated by gen_lsp.lua, keep at end of file. ---- @alias vim.lsp.protocol.Method.ClientToServer +--- @alias vim.lsp.protocol.Method.ClientToServer.Request --- | 'callHierarchy/incomingCalls', --- | 'callHierarchy/outgoingCalls', --- | 'codeAction/resolve', --- | 'codeLens/resolve', --- | 'completionItem/resolve', --- | 'documentLink/resolve', ---- | '$/setTrace', ---- | 'exit', --- | 'initialize', ---- | 'initialized', --- | 'inlayHint/resolve', ---- | 'notebookDocument/didChange', ---- | 'notebookDocument/didClose', ---- | 'notebookDocument/didOpen', ---- | 'notebookDocument/didSave', --- | 'shutdown', --- | 'textDocument/codeAction', --- | 'textDocument/codeLens', @@ -645,10 +638,6 @@ end --- | 'textDocument/declaration', --- | 'textDocument/definition', --- | 'textDocument/diagnostic', ---- | 'textDocument/didChange', ---- | 'textDocument/didClose', ---- | 'textDocument/didOpen', ---- | 'textDocument/didSave', --- | 'textDocument/documentColor', --- | 'textDocument/documentHighlight', --- | 'textDocument/documentLink', @@ -676,19 +665,11 @@ end --- | 'textDocument/semanticTokens/range', --- | 'textDocument/signatureHelp', --- | 'textDocument/typeDefinition', ---- | 'textDocument/willSave', --- | 'textDocument/willSaveWaitUntil', --- | 'typeHierarchy/subtypes', --- | 'typeHierarchy/supertypes', ---- | 'window/workDoneProgress/cancel', --- | 'workspaceSymbol/resolve', --- | 'workspace/diagnostic', ---- | 'workspace/didChangeConfiguration', ---- | 'workspace/didChangeWatchedFiles', ---- | 'workspace/didChangeWorkspaceFolders', ---- | 'workspace/didCreateFiles', ---- | 'workspace/didDeleteFiles', ---- | 'workspace/didRenameFiles', --- | 'workspace/executeCommand', --- | 'workspace/symbol', --- | 'workspace/textDocumentContent', @@ -696,15 +677,35 @@ end --- | 'workspace/willDeleteFiles', --- | 'workspace/willRenameFiles', ---- @alias vim.lsp.protocol.Method.ServerToClient +--- @alias vim.lsp.protocol.Method.ClientToServer.Notification +--- | '$/setTrace', +--- | 'exit', +--- | 'initialized', +--- | 'notebookDocument/didChange', +--- | 'notebookDocument/didClose', +--- | 'notebookDocument/didOpen', +--- | 'notebookDocument/didSave', +--- | 'textDocument/didChange', +--- | 'textDocument/didClose', +--- | 'textDocument/didOpen', +--- | 'textDocument/didSave', +--- | 'textDocument/willSave', +--- | 'window/workDoneProgress/cancel', +--- | 'workspace/didChangeConfiguration', +--- | 'workspace/didChangeWatchedFiles', +--- | 'workspace/didChangeWorkspaceFolders', +--- | 'workspace/didCreateFiles', +--- | 'workspace/didDeleteFiles', +--- | 'workspace/didRenameFiles', + +--- @alias vim.lsp.protocol.Method.ClientToServer +--- | vim.lsp.protocol.Method.ClientToServer.Request +--- | vim.lsp.protocol.Method.ClientToServer.Notification + +--- @alias vim.lsp.protocol.Method.ServerToClient.Request --- | 'client/registerCapability', --- | 'client/unregisterCapability', ---- | '$/logTrace', ---- | 'telemetry/event', ---- | 'textDocument/publishDiagnostics', ---- | 'window/logMessage', --- | 'window/showDocument', ---- | 'window/showMessage', --- | 'window/showMessageRequest', --- | 'window/workDoneProgress/create', --- | 'workspace/applyEdit', @@ -718,6 +719,17 @@ end --- | 'workspace/textDocumentContent/refresh', --- | 'workspace/workspaceFolders', +--- @alias vim.lsp.protocol.Method.ServerToClient.Notification +--- | '$/logTrace', +--- | 'telemetry/event', +--- | 'textDocument/publishDiagnostics', +--- | 'window/logMessage', +--- | 'window/showMessage', + +--- @alias vim.lsp.protocol.Method.ServerToClient +--- | vim.lsp.protocol.Method.ServerToClient.Request +--- | vim.lsp.protocol.Method.ServerToClient.Notification + --- @alias vim.lsp.protocol.Method --- | vim.lsp.protocol.Method.ClientToServer --- | vim.lsp.protocol.Method.ServerToClient diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 82fc39142d34df..63f7914465289a 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2164,7 +2164,7 @@ end ---@class (private) vim.lsp.util._cancel_requests.Filter ---@field bufnr? integer ---@field clients? vim.lsp.Client[] ----@field method? string +---@field method? vim.lsp.protocol.Method.ClientToServer.Request ---@field type? string ---@private diff --git a/src/gen/gen_lsp.lua b/src/gen/gen_lsp.lua index 38792307e48bf0..f1306d3b4c8ae1 100644 --- a/src/gen/gen_lsp.lua +++ b/src/gen/gen_lsp.lua @@ -33,6 +33,24 @@ end --- @field enumerations vim._gen_lsp.Enumeration[] --- @field typeAliases vim._gen_lsp.TypeAlias[] +--- @class vim._gen_lsp.Notification +--- @field deprecated? string +--- @field documentation? string +--- @field messageDirection string +--- @field clientCapability? string +--- @field serverCapability? string +--- @field method string +--- @field params? any +--- @field proposed? boolean +--- @field registrationMethod? string +--- @field registrationOptions? any +--- @field since? string + +--- @class vim._gen_lsp.Request : vim._gen_lsp.Notification +--- @field errorData? any +--- @field partialResult? any +--- @field result any + ---@param opt vim._gen_lsp.opt ---@return vim._gen_lsp.Protocol local function read_json(opt) @@ -66,64 +84,47 @@ local function write_to_protocol(protocol, gen_methods, gen_capabilities) local indent = (' '):rep(2) - --- @class vim._gen_lsp.Request - --- @field deprecated? string - --- @field documentation? string - --- @field messageDirection string - --- @field clientCapability? string - --- @field serverCapability? string - --- @field method string - --- @field params? any - --- @field proposed? boolean - --- @field registrationMethod? string - --- @field registrationOptions? any - --- @field since? string - - --- @class vim._gen_lsp.Notification - --- @field deprecated? string - --- @field documentation? string - --- @field errorData? any - --- @field messageDirection string - --- @field clientCapability? string - --- @field serverCapability? string - --- @field method string - --- @field params? any[] - --- @field partialResult? any - --- @field proposed? boolean - --- @field registrationMethod? string - --- @field registrationOptions? any - --- @field result any - --- @field since? string + local function compare_method(a, b) + return to_luaname(a.method) < to_luaname(b.method) + end ---@type (vim._gen_lsp.Request|vim._gen_lsp.Notification)[] - local all = vim.list_extend(protocol.requests, protocol.notifications) - table.sort(all, function(a, b) - return to_luaname(a.method) < to_luaname(b.method) - end) + local all = {} + vim.list_extend(all, protocol.notifications) + vim.list_extend(all, protocol.requests) + + table.sort(all, compare_method) + table.sort(protocol.requests, compare_method) + table.sort(protocol.notifications, compare_method) local output = { '-- Generated by gen_lsp.lua, keep at end of file.' } if gen_methods then - output[#output + 1] = '--- @alias vim.lsp.protocol.Method.ClientToServer' - - for _, item in ipairs(all) do - if item.method and item.messageDirection == 'clientToServer' then - output[#output + 1] = ("--- | '%s',"):format(item.method) + for _, dir in ipairs({ 'clientToServer', 'serverToClient' }) do + local dir1 = dir:sub(1, 1):upper() .. dir:sub(2) + local alias = ('vim.lsp.protocol.Method.%s'):format(dir1) + for _, b in ipairs({ + { title = 'Request', methods = protocol.requests }, + { title = 'Notification', methods = protocol.notifications }, + }) do + output[#output + 1] = ('--- @alias %s.%s'):format(alias, b.title) + for _, item in ipairs(b.methods) do + if item.messageDirection == dir then + output[#output + 1] = ("--- | '%s',"):format(item.method) + end + end + output[#output + 1] = '' end - end - vim.list_extend(output, { - '', - '--- @alias vim.lsp.protocol.Method.ServerToClient', - }) - for _, item in ipairs(all) do - if item.method and item.messageDirection == 'serverToClient' then - output[#output + 1] = ("--- | '%s',"):format(item.method) - end + vim.list_extend(output, { + ('--- @alias %s'):format(alias), + ('--- | %s.Request'):format(alias), + ('--- | %s.Notification'):format(alias), + '', + }) end vim.list_extend(output, { - '', '--- @alias vim.lsp.protocol.Method', '--- | vim.lsp.protocol.Method.ClientToServer', '--- | vim.lsp.protocol.Method.ServerToClient', diff --git a/src/gen/gen_vimdoc.lua b/src/gen/gen_vimdoc.lua index 68912cf0b52499..2bcb675349141a 100755 --- a/src/gen/gen_vimdoc.lua +++ b/src/gen/gen_vimdoc.lua @@ -427,6 +427,9 @@ end --- @param generics? table<string,string> --- @param default? string local function render_type(ty, generics, default) + -- TODO(lewis6991): Document LSP protocol types + ty = ty:gsub('vim%.lsp%.protocol%.Method.[%w.]+', 'string') + if generics then ty = replace_generics(ty, generics) end
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua index 9f8e982d3a5dc6..c618be7fd941ee 100644 --- a/runtime/lua/vim/lsp.lua +++ b/runtime/lua/vim/lsp.lua @@ -1285,7 +1285,7 @@ end ---@since 7 ---@param bufnr integer Buffer handle, or 0 for current. ----@param method string LSP method name ---@param params? table|(fun(client: vim.lsp.Client, bufnr: integer): table?) Parameters to send to the server. --- Can also be passed as a function that returns the params table for cases where --- parameters are specific to the client. diff --git a/runtime/lua/vim/lsp/_meta/protocol.lua b/runtime/lua/vim/lsp/_meta/protocol.lua index 442efe9f03cb7a..7d588c0fd91793 100644 --- a/runtime/lua/vim/lsp/_meta/protocol.lua +++ b/runtime/lua/vim/lsp/_meta/protocol.lua @@ -1,11 +1,11 @@ --[[ -THIS FILE IS GENERATED by scripts/gen_lsp.lua +THIS FILE IS GENERATED by scr/gen/gen_lsp.lua DO NOT EDIT MANUALLY Based on LSP protocol 3.18 Regenerate: -nvim -l scripts/gen_lsp.lua gen --version 3.18 +nvim -l scr/gen/gen_lsp.lua gen --version 3.18 --]] ---@meta diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua index bd78f1ad505a0c..6ef2913ba2480d 100644 --- a/runtime/lua/vim/lsp/buf.lua +++ b/runtime/lua/vim/lsp/buf.lua @@ -158,7 +158,7 @@ local function request_with_opts(name, params, opts) lsp.buf_request(0, name, params, req_handler) ----@param method string +---@param method vim.lsp.protocol.Method.ClientToServer.Request ---@param opts? vim.lsp.LocationOpts local function get_locations(method, opts) opts = opts or {} @@ -814,7 +814,7 @@ function M.document_symbol(opts) --- @param client_id integer --- @param params table --- @param handler? lsp.Handler @@ -845,7 +845,7 @@ local hierarchy_methods = { [ms.callHierarchy_outgoingCalls] = 'call', } local function hierarchy(method) local kind = hierarchy_methods[method] if not kind then diff --git a/runtime/lua/vim/lsp/client.lua b/runtime/lua/vim/lsp/client.lua index b256eab1a65301..2219876a3d2a33 100644 --- a/runtime/lua/vim/lsp/client.lua +++ b/runtime/lua/vim/lsp/client.lua @@ -656,7 +656,7 @@ end --- This is a thin wrapper around {client.rpc.request} with some additional --- checks for capabilities and handler availability. --- @param params? table LSP request params. --- @param handler? lsp.Handler Response |lsp-handler| for this method. --- @param bufnr? integer (default: 0) Buffer handle, or 0 for current. @@ -721,7 +721,7 @@ end --- This is a wrapper around |Client:request()| --- @param params table LSP request params. --- @param timeout_ms integer? Maximum time in milliseconds to wait for --- a result. Defaults to 1000 @@ -757,7 +757,7 @@ end --- Sends a notification to an LSP server. +--- @param method vim.lsp.protocol.Method.ClientToServer.Notification LSP method name. --- @param params table? LSP request params. --- @return boolean status indicating if the notification was successful. --- If it is false, then the client has shutdown. @@ -828,7 +828,7 @@ function Client:stop(force) --- Get options for a method that is registered dynamically. function Client:_supports_registration(method) local capability = vim.tbl_get(self.capabilities, unpack(vim.split(method, '/'))) return type(capability) == 'table' and capability.dynamicRegistration @@ -901,7 +901,7 @@ function Client:_get_language_id(bufnr) return self.get_language_id(bufnr, vim.bo[bufnr].filetype) --- @return lsp.Registration? function Client:_get_registration(method, bufnr) @@ -1051,7 +1051,7 @@ end --- Always returns true for unknown off-spec methods. --- Note: Some language server capabilities can be file specific. +--- @param method vim.lsp.protocol.Method.ClientToServer function Client:supports_method(method, bufnr) -- Deprecated form @@ -1082,27 +1082,11 @@ function Client:supports_method(method, bufnr) return false ---- Get options for a method that is registered dynamically. ---- @param bufnr? integer ---- @return lsp.LSPAny? -function Client:_get_registration_options(method, bufnr) - if not self:_supports_registration(method) then - return - local reg = self:_get_registration(method, bufnr) - if reg then - return reg.registerOptions -end --- @private --- Handles a notification sent by an LSP server by invoking the --- corresponding handler. ---- @param method string LSP method name +--- @param method vim.lsp.protocol.Method.ServerToClient.Notification LSP method name --- @param params table The parameters for that method. function Client:_notification(method, params) log.trace('notification', method, params) diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua index ececc41cee5c37..167dcb561b7cfc 100644 --- a/runtime/lua/vim/lsp/protocol.lua +++ b/runtime/lua/vim/lsp/protocol.lua @@ -621,22 +621,15 @@ function protocol.resolve_capabilities(server_capabilities) -- Generated by gen_lsp.lua, keep at end of file. ---- @alias vim.lsp.protocol.Method.ClientToServer +--- @alias vim.lsp.protocol.Method.ClientToServer.Request --- | 'callHierarchy/incomingCalls', --- | 'callHierarchy/outgoingCalls', --- | 'codeAction/resolve', --- | 'codeLens/resolve', --- | 'completionItem/resolve', --- | 'documentLink/resolve', ---- | '$/setTrace', ---- | 'exit', --- | 'initialize', ---- | 'initialized', --- | 'inlayHint/resolve', ---- | 'notebookDocument/didChange', ---- | 'notebookDocument/didClose', ---- | 'notebookDocument/didOpen', ---- | 'notebookDocument/didSave', --- | 'shutdown', --- | 'textDocument/codeAction', --- | 'textDocument/codeLens', @@ -645,10 +638,6 @@ end --- | 'textDocument/declaration', --- | 'textDocument/definition', --- | 'textDocument/diagnostic', ---- | 'textDocument/didChange', ---- | 'textDocument/didClose', ---- | 'textDocument/didOpen', ---- | 'textDocument/didSave', --- | 'textDocument/documentColor', --- | 'textDocument/documentHighlight', --- | 'textDocument/documentLink', @@ -676,19 +665,11 @@ end --- | 'textDocument/semanticTokens/range', --- | 'textDocument/signatureHelp', --- | 'textDocument/typeDefinition', ---- | 'textDocument/willSave', --- | 'textDocument/willSaveWaitUntil', --- | 'typeHierarchy/subtypes', --- | 'typeHierarchy/supertypes', ---- | 'window/workDoneProgress/cancel', --- | 'workspaceSymbol/resolve', --- | 'workspace/diagnostic', ---- | 'workspace/didChangeConfiguration', ---- | 'workspace/didChangeWatchedFiles', ---- | 'workspace/didChangeWorkspaceFolders', ---- | 'workspace/didCreateFiles', ---- | 'workspace/didDeleteFiles', ---- | 'workspace/didRenameFiles', --- | 'workspace/executeCommand', --- | 'workspace/symbol', --- | 'workspace/textDocumentContent', @@ -696,15 +677,35 @@ end --- | 'workspace/willDeleteFiles', --- | 'workspace/willRenameFiles', ---- @alias vim.lsp.protocol.Method.ServerToClient +--- @alias vim.lsp.protocol.Method.ClientToServer.Notification +--- | 'exit', +--- | 'initialized', +--- | 'notebookDocument/didChange', +--- | 'notebookDocument/didClose', +--- | 'notebookDocument/didOpen', +--- | 'notebookDocument/didSave', +--- | 'textDocument/didChange', +--- | 'textDocument/didSave', +--- | 'textDocument/willSave', +--- | 'window/workDoneProgress/cancel', +--- | 'workspace/didChangeConfiguration', +--- | 'workspace/didChangeWatchedFiles', +--- | 'workspace/didChangeWorkspaceFolders', +--- | 'workspace/didCreateFiles', +--- | 'workspace/didDeleteFiles', +--- | 'workspace/didRenameFiles', +--- @alias vim.lsp.protocol.Method.ClientToServer +--- | vim.lsp.protocol.Method.ClientToServer.Request +--- | vim.lsp.protocol.Method.ClientToServer.Notification +--- @alias vim.lsp.protocol.Method.ServerToClient.Request --- | 'client/registerCapability', --- | 'client/unregisterCapability', ---- | '$/logTrace', ---- | 'telemetry/event', ---- | 'textDocument/publishDiagnostics', ---- | 'window/logMessage', --- | 'window/showDocument', ---- | 'window/showMessage', --- | 'window/showMessageRequest', --- | 'window/workDoneProgress/create', --- | 'workspace/applyEdit', @@ -718,6 +719,17 @@ end --- | 'workspace/textDocumentContent/refresh', --- | 'workspace/workspaceFolders', +--- @alias vim.lsp.protocol.Method.ServerToClient.Notification +--- | '$/logTrace', +--- | 'telemetry/event', +--- | 'textDocument/publishDiagnostics', +--- | 'window/logMessage', +--- | 'window/showMessage', +--- @alias vim.lsp.protocol.Method.ServerToClient +--- | vim.lsp.protocol.Method.ServerToClient.Request +--- | vim.lsp.protocol.Method.ServerToClient.Notification --- @alias vim.lsp.protocol.Method --- | vim.lsp.protocol.Method.ClientToServer --- | vim.lsp.protocol.Method.ServerToClient diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua index 82fc39142d34df..63f7914465289a 100644 --- a/runtime/lua/vim/lsp/util.lua +++ b/runtime/lua/vim/lsp/util.lua @@ -2164,7 +2164,7 @@ end ---@class (private) vim.lsp.util._cancel_requests.Filter ---@field bufnr? integer ---@field clients? vim.lsp.Client[] ----@field method? string ---@field type? string ---@private diff --git a/src/gen/gen_lsp.lua b/src/gen/gen_lsp.lua index 38792307e48bf0..f1306d3b4c8ae1 100644 --- a/src/gen/gen_lsp.lua +++ b/src/gen/gen_lsp.lua @@ -33,6 +33,24 @@ end --- @field enumerations vim._gen_lsp.Enumeration[] --- @field typeAliases vim._gen_lsp.TypeAlias[] +--- @class vim._gen_lsp.Notification +--- @field deprecated? string +--- @field documentation? string +--- @field clientCapability? string +--- @field serverCapability? string +--- @field method string +--- @field params? any +--- @field proposed? boolean +--- @field registrationMethod? string +--- @field registrationOptions? any +--- @field since? string +--- @class vim._gen_lsp.Request : vim._gen_lsp.Notification +--- @field errorData? any +--- @field partialResult? any ---@param opt vim._gen_lsp.opt ---@return vim._gen_lsp.Protocol local function read_json(opt) @@ -66,64 +84,47 @@ local function write_to_protocol(protocol, gen_methods, gen_capabilities) local indent = (' '):rep(2) - --- @class vim._gen_lsp.Request - --- @field params? any - --- @class vim._gen_lsp.Notification - --- @field errorData? any - --- @field params? any[] - --- @field partialResult? any - --- @field result any + return to_luaname(a.method) < to_luaname(b.method) ---@type (vim._gen_lsp.Request|vim._gen_lsp.Notification)[] - local all = vim.list_extend(protocol.requests, protocol.notifications) - table.sort(all, function(a, b) - return to_luaname(a.method) < to_luaname(b.method) - end) + local all = {} + vim.list_extend(all, protocol.notifications) + vim.list_extend(all, protocol.requests) + table.sort(all, compare_method) + table.sort(protocol.requests, compare_method) + table.sort(protocol.notifications, compare_method) local output = { '-- Generated by gen_lsp.lua, keep at end of file.' } if gen_methods then - output[#output + 1] = '--- @alias vim.lsp.protocol.Method.ClientToServer' - if item.method and item.messageDirection == 'clientToServer' then + for _, dir in ipairs({ 'clientToServer', 'serverToClient' }) do + local dir1 = dir:sub(1, 1):upper() .. dir:sub(2) + local alias = ('vim.lsp.protocol.Method.%s'):format(dir1) + { title = 'Request', methods = protocol.requests }, + { title = 'Notification', methods = protocol.notifications }, + output[#output + 1] = ('--- @alias %s.%s'):format(alias, b.title) + for _, item in ipairs(b.methods) do + if item.messageDirection == dir then + output[#output + 1] = ("--- | '%s',"):format(item.method) + end + end + output[#output + 1] = '' end - end - '--- @alias vim.lsp.protocol.Method.ServerToClient', - }) - if item.method and item.messageDirection == 'serverToClient' then - end + vim.list_extend(output, { + ('--- @alias %s'):format(alias), + ('--- | %s.Request'):format(alias), + ('--- | %s.Notification'):format(alias), + '', + }) end vim.list_extend(output, { '--- @alias vim.lsp.protocol.Method', '--- | vim.lsp.protocol.Method.ClientToServer', '--- | vim.lsp.protocol.Method.ServerToClient', diff --git a/src/gen/gen_vimdoc.lua b/src/gen/gen_vimdoc.lua index 68912cf0b52499..2bcb675349141a 100755 --- a/src/gen/gen_vimdoc.lua +++ b/src/gen/gen_vimdoc.lua @@ -427,6 +427,9 @@ end --- @param generics? table<string,string> --- @param default? string local function render_type(ty, generics, default) + -- TODO(lewis6991): Document LSP protocol types + ty = ty:gsub('vim%.lsp%.protocol%.Method.[%w.]+', 'string') if generics then ty = replace_generics(ty, generics) end
[ "+---@param method vim.lsp.protocol.Method.ClientToServer.Request LSP method name", "+--- | '$/setTrace',", "+--- | 'textDocument/didClose',", "+--- | 'textDocument/didOpen',", "+---@field method? vim.lsp.protocol.Method.ClientToServer.Request", "+--- @field messageDirection string", "+--- @field result any", "+ local function compare_method(a, b)", "+ end", "+ for _, b in ipairs({", "+ }) do", "- vim.list_extend(output, {" ]
[ 9, 214, 222, 223, 277, 292, 305, 342, 344, 370, 373, 384 ]
{ "additions": 103, "author": "lewis6991", "deletions": 61, "html_url": "https://github.com/neovim/neovim/pull/33509", "issue_id": 33509, "merged_at": "2025-04-17T10:40:46Z", "omission_probability": 0.1, "pr_number": 33509, "repo": "neovim/neovim", "title": "feat(lsp): use stricter types for methods", "total_changes": 164 }
393
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 0815c64c935bc9..2382a9e165a4c6 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -623,6 +623,16 @@ possibilities: > The `:Cycle` command is also mapped to the CTRL-A and CTRL-X keys. For details, see `git-rebase --help`. +GLEAM *ft-gleam-plugin* + +By default the following options are set for the recommended gleam style: > + + setlocal expandtab shiftwidth=2 softtabstop=2 + +To disable this behavior, set the following variable in your vimrc: > + + let g:gleam_recommended_style = 0 + GO *ft-go-plugin* By default the following options are set, based on Golang official docs: > diff --git a/runtime/ftplugin/gleam.vim b/runtime/ftplugin/gleam.vim index 5187d4d0088ca3..70958c70fc8209 100644 --- a/runtime/ftplugin/gleam.vim +++ b/runtime/ftplugin/gleam.vim @@ -2,7 +2,7 @@ " Language: Gleam " Maintainer: Kirill Morozov <[email protected]> " Previous Maintainer: Trilowy (https://github.com/trilowy) -" Last Change: 2025-04-12 +" Last Change: 2025 Apr 16 if exists('b:did_ftplugin') finish @@ -11,11 +11,15 @@ let b:did_ftplugin = 1 setlocal comments=://,:///,://// setlocal commentstring=//\ %s -setlocal expandtab setlocal formatprg=gleam\ format\ --stdin -setlocal shiftwidth=2 -setlocal softtabstop=2 -let b:undo_ftplugin = "setlocal com< cms< fp< et< sw< sts<" +let b:undo_ftplugin = "setlocal com< cms< fp<" + +if get(g:, "gleam_recommended_style", 1) + setlocal expandtab + setlocal shiftwidth=2 + setlocal softtabstop=2 + let b:undo_ftplugin ..= " | setlocal et< sw< sts<" +endif " vim: sw=2 sts=2 et diff --git a/runtime/ftplugin/go.vim b/runtime/ftplugin/go.vim index 57fc73cd131514..f3cae02065e819 100644 --- a/runtime/ftplugin/go.vim +++ b/runtime/ftplugin/go.vim @@ -5,12 +5,16 @@ " 2024 Jul 16 by Vim Project (add recommended indent style) " 2025 Mar 07 by Vim Project (add formatprg and keywordprg option #16804) " 2025 Mar 18 by Vim Project (use :term for 'keywordprg' #16911) +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists('b:did_ftplugin') finish endif let b:did_ftplugin = 1 +let s:cpo_save = &cpo +set cpo&vim + setlocal formatoptions-=t setlocal formatprg=gofmt @@ -45,4 +49,7 @@ if !exists('*' .. expand('<SID>') .. 'GoKeywordPrg') endfunc endif +let &cpo = s:cpo_save +unlet s:cpo_save + " vim: sw=2 sts=2 et diff --git a/runtime/ftplugin/heex.vim b/runtime/ftplugin/heex.vim index becc071c37921b..2f53d22ee6a83a 100644 --- a/runtime/ftplugin/heex.vim +++ b/runtime/ftplugin/heex.vim @@ -2,12 +2,16 @@ " Language: HEEx " Maintainer: Mitchell Hanberg <[email protected]> " Last Change: 2022 Sep 21 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1 +let s:cpo_save = &cpo +set cpo&vim + setlocal shiftwidth=2 softtabstop=2 expandtab setlocal comments=:<%!-- @@ -25,3 +29,6 @@ if exists("loaded_matchit") && !exists("b:match_words") \ '<\@<=\([^/!][^ \t>]*\)[^>]*\%(>\|$\):<\@<=/\1>' let b:undo_ftplugin ..= " | unlet! b:match_ignorecase b:match_words" endif + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/lprolog.vim b/runtime/ftplugin/lprolog.vim index 1075a9c8139c76..07ffc527c848ec 100644 --- a/runtime/ftplugin/lprolog.vim +++ b/runtime/ftplugin/lprolog.vim @@ -2,7 +2,9 @@ " Language: LambdaProlog (Teyjus) " Maintainer: Markus Mottl <[email protected]> " URL: http://www.ocaml.info/vim/ftplugin/lprolog.vim -" Last Change: 2023 Aug 28 - added undo_ftplugin (Vim Project) +" Last Change: 2025 Apr 16 +" 2025 Apr 16 - set 'cpoptions' for line continuation +" 2023 Aug 28 - added undo_ftplugin (Vim Project) " 2006 Feb 05 " 2001 Sep 16 - fixed 'no_mail_maps'-bug (MM) " 2001 Sep 02 - initial release (MM) @@ -12,6 +14,9 @@ if exists("b:did_ftplugin") finish endif +let s:cpo_save = &cpo +set cpo&vim + " Don't do other file type settings for this buffer let b:did_ftplugin = 1 @@ -43,3 +48,6 @@ if !exists("no_plugin_maps") && !exists("no_lprolog_maps") vnoremap <buffer> <Plug>BUncomOn <ESC>:'<,'><CR>`<O<ESC>0i/*<ESC>`>o<ESC>0i*/<ESC>`< vnoremap <buffer> <Plug>BUncomOff <ESC>:'<,'><CR>`<dd`>dd`< endif + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/mediawiki.vim b/runtime/ftplugin/mediawiki.vim index 46182461065065..399de421eefdac 100644 --- a/runtime/ftplugin/mediawiki.vim +++ b/runtime/ftplugin/mediawiki.vim @@ -3,6 +3,7 @@ " Home: http://en.wikipedia.org/wiki/Wikipedia:Text_editor_support#Vim " Last Change: 2024 Jul 14 " Credits: chikamichi +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) " if exists("b:did_ftplugin") @@ -10,6 +11,9 @@ if exists("b:did_ftplugin") endif let b:did_ftplugin = 1 +let s:cpo_save = &cpo +set cpo&vim + " Many MediaWiki wikis prefer line breaks only at the end of paragraphs " (like in a text processor), which results in long, wrapping lines. setlocal wrap linebreak @@ -40,3 +44,6 @@ setlocal foldmethod=expr let b:undo_ftplugin = "setl commentstring< comments< formatoptions< foldexpr< foldmethod<" let b:undo_ftplugin += " matchpairs< linebreak< wrap< textwidth<" + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/mojo.vim b/runtime/ftplugin/mojo.vim index ff502299341525..c7f3b6b41e4d7a 100644 --- a/runtime/ftplugin/mojo.vim +++ b/runtime/ftplugin/mojo.vim @@ -2,12 +2,16 @@ " Language: Mojo " Maintainer: Riley Bruins <[email protected]> " Last Change: 2024 Jul 07 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists('b:did_ftplugin') finish endif let b:did_ftplugin = 1 +let s:cpo_save = &cpo +set cpo&vim + setlocal include=^\\s*\\(from\\\|import\\) setlocal define=^\\s*\\(\\(async\\s\\+\\)\\?def\\\|class\\) @@ -39,3 +43,6 @@ let b:undo_ftplugin = 'setlocal include<' \ . '|setlocal suffixesadd<' \ . '|setlocal comments<' \ . '|setlocal commentstring<' + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/nroff.vim b/runtime/ftplugin/nroff.vim index 7d3d2a597f5a3b..1c6d4ebc799aa6 100644 --- a/runtime/ftplugin/nroff.vim +++ b/runtime/ftplugin/nroff.vim @@ -7,12 +7,16 @@ " Last Changes: " 2024 May 24 by Riley Bruins <[email protected]> ('commentstring' #14843) " 2025 Feb 12 by Wu, Zhenyu <[email protected]> (matchit configuration #16619) +" 2025 Apr 16 by Eisuke Kawashima (cpoptions #17121) if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1 +let s:cpo_save = &cpo +set cpo&vim + setlocal commentstring=.\\\"\ %s setlocal comments=:.\\\" setlocal sections+=Sh @@ -30,3 +34,6 @@ if exists('loaded_matchit') \ . ',^\.\s*FS\>:^\.\s*FE\>' let b:undo_ftplugin .= "| unlet b:match_words" endif + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/ftplugin/tera.vim b/runtime/ftplugin/tera.vim index 65bae700486a52..ce4134ae03696d 100644 --- a/runtime/ftplugin/tera.vim +++ b/runtime/ftplugin/tera.vim @@ -2,12 +2,16 @@ " Language: Tera " Maintainer: Muntasir Mahmud <[email protected]> " Last Change: 2025 Mar 08 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1 +let s:cpo_save = &cpo +set cpo&vim + setlocal autoindent setlocal commentstring={#\ %s\ #} @@ -28,3 +32,6 @@ setlocal softtabstop=2 let b:undo_ftplugin = "setlocal autoindent< commentstring< comments< " .. \ "includeexpr< suffixesadd< expandtab< shiftwidth< softtabstop<" let b:undo_ftplugin .= "|unlet! b:match_ignorecase b:match_words" + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/indent/cucumber.vim b/runtime/indent/cucumber.vim index 5d144e426b5266..33d4cc73177eec 100644 --- a/runtime/indent/cucumber.vim +++ b/runtime/indent/cucumber.vim @@ -2,11 +2,14 @@ " Language: Cucumber " Maintainer: Tim Pope <[email protected]> " Last Change: 2023 Dec 28 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists("b:did_indent") finish endif let b:did_indent = 1 +let s:cpo_save = &cpo +set cpo&vim setlocal autoindent setlocal indentexpr=GetCucumberIndent() @@ -95,4 +98,7 @@ function! GetCucumberIndent(...) abort return prev.indent < 0 ? 0 : prev.indent endfunction +let &cpo = s:cpo_save +unlet s:cpo_save + " vim:set sts=2 sw=2: diff --git a/runtime/syntax/asy.vim b/runtime/syntax/asy.vim index ed2bf712f5c1e1..de17d925d0a642 100644 --- a/runtime/syntax/asy.vim +++ b/runtime/syntax/asy.vim @@ -3,6 +3,7 @@ " Maintainer: Avid Seeker <[email protected]> " Andy Hammerlindl " Last Change: 2022 Jan 05 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) " Hacked together from Bram Moolenaar's C syntax file, and Claudio Fleiner's " Java syntax file. @@ -11,6 +12,9 @@ if exists("b:current_syntax") finish endif +let s:cpo_save = &cpo +set cpo&vim + " useful C/C++/Java keywords syn keyword asyStatement break return continue unravel syn keyword asyConditional if else @@ -241,3 +245,5 @@ hi def link asyTodo Todo hi def link asyPathSpec Statement let b:current_syntax = "asy" +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/jq.vim b/runtime/syntax/jq.vim index 272dcb4ebeb531..3275e2ef5e35a8 100644 --- a/runtime/syntax/jq.vim +++ b/runtime/syntax/jq.vim @@ -3,12 +3,16 @@ " Maintainer: Vito <[email protected]> " Last Change: 2024 Apr 17 " Upstream: https://github.com/vito-c/jq.vim +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) " " Quit when a (custom) syntax file was already loaded if exists('b:current_syntax') finish endif +let s:cpo_save = &cpo +set cpo&vim + " syn include @jqHtml syntax/html.vim " Doc comment HTML " jqTodo @@ -128,3 +132,6 @@ hi def link jqString String hi def link jqInterpolationDelimiter Delimiter hi def link jqConditional Conditional hi def link jqNumber Number + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/modula2.vim b/runtime/syntax/modula2.vim index 6a9f4af6aaf6a7..3c1346e9f53f16 100644 --- a/runtime/syntax/modula2.vim +++ b/runtime/syntax/modula2.vim @@ -3,14 +3,21 @@ " Maintainer: Doug Kearns <[email protected]> " Previous Maintainer: [email protected] (Peter Funk) " Last Change: 2024 Jan 04 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists("b:current_syntax") finish endif +let s:cpo_save = &cpo +set cpo&vim + let dialect = modula2#GetDialect() exe "runtime! syntax/modula2/opt/" .. dialect .. ".vim" let b:current_syntax = "modula2" +let &cpo = s:cpo_save +unlet s:cpo_save + " vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/syntax/pacmanlog.vim b/runtime/syntax/pacmanlog.vim index 98abd586854260..798b48f72792c4 100644 --- a/runtime/syntax/pacmanlog.vim +++ b/runtime/syntax/pacmanlog.vim @@ -2,11 +2,15 @@ " Language: pacman.log " Maintainer: Ronan Pigott <[email protected]> " Last Change: 2023 Dec 04 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists("b:current_syntax") finish endif +let s:cpo_save = &cpo +set cpo&vim + syn sync maxlines=1 syn region pacmanlogMsg start='\S' end='$' keepend contains=pacmanlogTransaction,pacmanlogALPMMsg syn region pacmanlogTag start='\['hs=s+1 end='\]'he=e-1 keepend nextgroup=pacmanlogMsg @@ -39,3 +43,6 @@ hi def link pacmanlogPackageName Normal hi def link pacmanlogPackageVersion Comment let b:current_syntax = "pacmanlog" + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/rasi.vim b/runtime/syntax/rasi.vim index 40c3393fc574cc..c4c4508f12e933 100644 --- a/runtime/syntax/rasi.vim +++ b/runtime/syntax/rasi.vim @@ -2,6 +2,7 @@ " Language: rasi (Rofi Advanced Style Information) " Maintainer: Pierrick Guillaume <[email protected]> " Last Change: 2024 May 21 +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) " " Syntax support for rasi config file @@ -12,6 +13,8 @@ if exists('b:current_syntax') finish endif let b:current_syntax = 'rasi' +let s:cpo_save = &cpo +set cpo&vim " String {{{ syn region rasiString start=+"+ skip=+\\"+ end=+"+ oneline contained @@ -295,4 +298,7 @@ hi def link rasiInvPropertyId rasiError hi def link rasiInvPropertyVal rasiError " }}} +let &cpo = s:cpo_save +unlet s:cpo_save + " vim:ts=8 diff --git a/runtime/syntax/tutor.vim b/runtime/syntax/tutor.vim index 399026790a42ff..4326d88fb36fc2 100644 --- a/runtime/syntax/tutor.vim +++ b/runtime/syntax/tutor.vim @@ -1,7 +1,14 @@ +" Language: Vim Tutor +" Maintainer: Vim Project +" Last Change: 2025 Apr 16 + if exists("b:current_syntax") finish endif +let s:cpo_save = &cpo +set cpo&vim + syn include @VIM syntax/vim.vim unlet b:current_syntax syn include @TUTORSHELL syntax/sh.vim @@ -77,3 +84,5 @@ hi def link tutorInlineX tutorX hi def link tutorShellPrompt Delimiter let b:current_syntax = "tutor" +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/runtime/syntax/typst.vim b/runtime/syntax/typst.vim index b1f05ec85391a5..686f7c3f31e216 100644 --- a/runtime/syntax/typst.vim +++ b/runtime/syntax/typst.vim @@ -1,14 +1,18 @@ " Vim syntax file " Language: Typst -" Previous Maintainer: Gregory Anders " Maintainer: Luca Saccarola <[email protected]> +" Previous Maintainer: Gregory Anders +" Based On: https://github.com/kaarmu/typst.vim " Last Change: 2024 Dec 09 -" Based on: https://github.com/kaarmu/typst.vim +" 2025 Apr 16 by Vim Project (set 'cpoptions' for line continuation, #17121) if exists('b:current_syntax') finish endif +let s:cpo_save = &cpo +set cpo&vim + syntax sync fromstart syntax spell toplevel @@ -470,4 +474,7 @@ highlight default typstMarkupBoldItalic term=bold,italic let b:current_syntax = 'typst' +let &cpo = s:cpo_save +unlet s:cpo_save + " }}}1
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 0815c64c935bc9..2382a9e165a4c6 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -623,6 +623,16 @@ possibilities: > The `:Cycle` command is also mapped to the CTRL-A and CTRL-X keys. For details, see `git-rebase --help`. +GLEAM *ft-gleam-plugin* +By default the following options are set for the recommended gleam style: > + setlocal expandtab shiftwidth=2 softtabstop=2 +To disable this behavior, set the following variable in your vimrc: > + let g:gleam_recommended_style = 0 GO *ft-go-plugin* By default the following options are set, based on Golang official docs: > diff --git a/runtime/ftplugin/gleam.vim b/runtime/ftplugin/gleam.vim index 5187d4d0088ca3..70958c70fc8209 100644 --- a/runtime/ftplugin/gleam.vim +++ b/runtime/ftplugin/gleam.vim @@ -2,7 +2,7 @@ " Language: Gleam " Maintainer: Kirill Morozov <[email protected]> " Previous Maintainer: Trilowy (https://github.com/trilowy) -" Last Change: 2025-04-12 +" Last Change: 2025 Apr 16 @@ -11,11 +11,15 @@ let b:did_ftplugin = 1 setlocal comments=://,:///,://// setlocal commentstring=//\ %s -setlocal expandtab setlocal formatprg=gleam\ format\ --stdin -setlocal shiftwidth=2 -setlocal softtabstop=2 -let b:undo_ftplugin = "setlocal com< cms< fp< et< sw< sts<" +let b:undo_ftplugin = "setlocal com< cms< fp<" +if get(g:, "gleam_recommended_style", 1) + setlocal expandtab + setlocal shiftwidth=2 + setlocal softtabstop=2 + let b:undo_ftplugin ..= " | setlocal et< sw< sts<" +endif diff --git a/runtime/ftplugin/go.vim b/runtime/ftplugin/go.vim index 57fc73cd131514..f3cae02065e819 100644 --- a/runtime/ftplugin/go.vim +++ b/runtime/ftplugin/go.vim @@ -5,12 +5,16 @@ " 2024 Jul 16 by Vim Project (add recommended indent style) " 2025 Mar 07 by Vim Project (add formatprg and keywordprg option #16804) " 2025 Mar 18 by Vim Project (use :term for 'keywordprg' #16911) setlocal formatoptions-=t setlocal formatprg=gofmt @@ -45,4 +49,7 @@ if !exists('*' .. expand('<SID>') .. 'GoKeywordPrg') endfunc diff --git a/runtime/ftplugin/heex.vim b/runtime/ftplugin/heex.vim index becc071c37921b..2f53d22ee6a83a 100644 --- a/runtime/ftplugin/heex.vim +++ b/runtime/ftplugin/heex.vim " Language: HEEx " Maintainer: Mitchell Hanberg <[email protected]> " Last Change: 2022 Sep 21 setlocal shiftwidth=2 softtabstop=2 expandtab setlocal comments=:<%!-- @@ -25,3 +29,6 @@ if exists("loaded_matchit") && !exists("b:match_words") \ '<\@<=\([^/!][^ \t>]*\)[^>]*\%(>\|$\):<\@<=/\1>' let b:undo_ftplugin ..= " | unlet! b:match_ignorecase b:match_words" diff --git a/runtime/ftplugin/lprolog.vim b/runtime/ftplugin/lprolog.vim index 1075a9c8139c76..07ffc527c848ec 100644 --- a/runtime/ftplugin/lprolog.vim +++ b/runtime/ftplugin/lprolog.vim @@ -2,7 +2,9 @@ " Language: LambdaProlog (Teyjus) " Maintainer: Markus Mottl <[email protected]> " URL: http://www.ocaml.info/vim/ftplugin/lprolog.vim -" Last Change: 2023 Aug 28 - added undo_ftplugin (Vim Project) +" Last Change: 2025 Apr 16 +" 2025 Apr 16 - set 'cpoptions' for line continuation +" 2023 Aug 28 - added undo_ftplugin (Vim Project) " 2006 Feb 05 " 2001 Sep 16 - fixed 'no_mail_maps'-bug (MM) " 2001 Sep 02 - initial release (MM) @@ -12,6 +14,9 @@ if exists("b:did_ftplugin") " Don't do other file type settings for this buffer @@ -43,3 +48,6 @@ if !exists("no_plugin_maps") && !exists("no_lprolog_maps") vnoremap <buffer> <Plug>BUncomOn <ESC>:'<,'><CR>`<O<ESC>0i/*<ESC>`>o<ESC>0i*/<ESC>`< vnoremap <buffer> <Plug>BUncomOff <ESC>:'<,'><CR>`<dd`>dd`< diff --git a/runtime/ftplugin/mediawiki.vim b/runtime/ftplugin/mediawiki.vim index 46182461065065..399de421eefdac 100644 --- a/runtime/ftplugin/mediawiki.vim +++ b/runtime/ftplugin/mediawiki.vim " Home: http://en.wikipedia.org/wiki/Wikipedia:Text_editor_support#Vim " Last Change: 2024 Jul 14 " Credits: chikamichi @@ -10,6 +11,9 @@ if exists("b:did_ftplugin") " Many MediaWiki wikis prefer line breaks only at the end of paragraphs " (like in a text processor), which results in long, wrapping lines. setlocal wrap linebreak @@ -40,3 +44,6 @@ setlocal foldmethod=expr let b:undo_ftplugin = "setl commentstring< comments< formatoptions< foldexpr< foldmethod<" let b:undo_ftplugin += " matchpairs< linebreak< wrap< textwidth<" diff --git a/runtime/ftplugin/mojo.vim b/runtime/ftplugin/mojo.vim index ff502299341525..c7f3b6b41e4d7a 100644 --- a/runtime/ftplugin/mojo.vim +++ b/runtime/ftplugin/mojo.vim " Language: Mojo " Maintainer: Riley Bruins <[email protected]> " Last Change: 2024 Jul 07 setlocal include=^\\s*\\(from\\\|import\\) setlocal define=^\\s*\\(\\(async\\s\\+\\)\\?def\\\|class\\) @@ -39,3 +43,6 @@ let b:undo_ftplugin = 'setlocal include<' \ . '|setlocal suffixesadd<' \ . '|setlocal comments<' \ . '|setlocal commentstring<' diff --git a/runtime/ftplugin/nroff.vim b/runtime/ftplugin/nroff.vim index 7d3d2a597f5a3b..1c6d4ebc799aa6 100644 --- a/runtime/ftplugin/nroff.vim +++ b/runtime/ftplugin/nroff.vim @@ -7,12 +7,16 @@ " Last Changes: " 2024 May 24 by Riley Bruins <[email protected]> ('commentstring' #14843) " 2025 Feb 12 by Wu, Zhenyu <[email protected]> (matchit configuration #16619) +" 2025 Apr 16 by Eisuke Kawashima (cpoptions #17121) setlocal commentstring=.\\\"\ %s setlocal comments=:.\\\" setlocal sections+=Sh @@ -30,3 +34,6 @@ if exists('loaded_matchit') \ . ',^\.\s*FS\>:^\.\s*FE\>' let b:undo_ftplugin .= "| unlet b:match_words" diff --git a/runtime/ftplugin/tera.vim b/runtime/ftplugin/tera.vim index 65bae700486a52..ce4134ae03696d 100644 --- a/runtime/ftplugin/tera.vim +++ b/runtime/ftplugin/tera.vim " Language: Tera " Maintainer: Muntasir Mahmud <[email protected]> " Last Change: 2025 Mar 08 setlocal commentstring={#\ %s\ #} @@ -28,3 +32,6 @@ setlocal softtabstop=2 let b:undo_ftplugin = "setlocal autoindent< commentstring< comments< " .. \ "includeexpr< suffixesadd< expandtab< shiftwidth< softtabstop<" let b:undo_ftplugin .= "|unlet! b:match_ignorecase b:match_words" diff --git a/runtime/indent/cucumber.vim b/runtime/indent/cucumber.vim index 5d144e426b5266..33d4cc73177eec 100644 --- a/runtime/indent/cucumber.vim +++ b/runtime/indent/cucumber.vim @@ -2,11 +2,14 @@ " Language: Cucumber " Maintainer: Tim Pope <[email protected]> " Last Change: 2023 Dec 28 if exists("b:did_indent") let b:did_indent = 1 setlocal indentexpr=GetCucumberIndent() @@ -95,4 +98,7 @@ function! GetCucumberIndent(...) abort return prev.indent < 0 ? 0 : prev.indent endfunction " vim:set sts=2 sw=2: diff --git a/runtime/syntax/asy.vim b/runtime/syntax/asy.vim index ed2bf712f5c1e1..de17d925d0a642 100644 --- a/runtime/syntax/asy.vim +++ b/runtime/syntax/asy.vim " Maintainer: Avid Seeker <[email protected]> " Andy Hammerlindl " Last Change: 2022 Jan 05 " Hacked together from Bram Moolenaar's C syntax file, and Claudio Fleiner's " Java syntax file. @@ -11,6 +12,9 @@ if exists("b:current_syntax") " useful C/C++/Java keywords syn keyword asyStatement break return continue unravel syn keyword asyConditional if else @@ -241,3 +245,5 @@ hi def link asyTodo Todo hi def link asyPathSpec Statement let b:current_syntax = "asy" diff --git a/runtime/syntax/jq.vim b/runtime/syntax/jq.vim index 272dcb4ebeb531..3275e2ef5e35a8 100644 --- a/runtime/syntax/jq.vim +++ b/runtime/syntax/jq.vim @@ -3,12 +3,16 @@ " Maintainer: Vito <[email protected]> " Last Change: 2024 Apr 17 " Upstream: https://github.com/vito-c/jq.vim " Quit when a (custom) syntax file was already loaded " syn include @jqHtml syntax/html.vim " Doc comment HTML " jqTodo @@ -128,3 +132,6 @@ hi def link jqString String hi def link jqInterpolationDelimiter Delimiter hi def link jqConditional Conditional hi def link jqNumber Number diff --git a/runtime/syntax/modula2.vim b/runtime/syntax/modula2.vim index 6a9f4af6aaf6a7..3c1346e9f53f16 100644 --- a/runtime/syntax/modula2.vim +++ b/runtime/syntax/modula2.vim @@ -3,14 +3,21 @@ " Maintainer: Doug Kearns <[email protected]> " Previous Maintainer: [email protected] (Peter Funk) " Last Change: 2024 Jan 04 let dialect = modula2#GetDialect() exe "runtime! syntax/modula2/opt/" .. dialect .. ".vim" let b:current_syntax = "modula2" " vim: nowrap sw=2 sts=2 ts=8 noet: diff --git a/runtime/syntax/pacmanlog.vim b/runtime/syntax/pacmanlog.vim index 98abd586854260..798b48f72792c4 100644 --- a/runtime/syntax/pacmanlog.vim +++ b/runtime/syntax/pacmanlog.vim @@ -2,11 +2,15 @@ " Language: pacman.log " Maintainer: Ronan Pigott <[email protected]> " Last Change: 2023 Dec 04 syn sync maxlines=1 syn region pacmanlogMsg start='\S' end='$' keepend contains=pacmanlogTransaction,pacmanlogALPMMsg syn region pacmanlogTag start='\['hs=s+1 end='\]'he=e-1 keepend nextgroup=pacmanlogMsg @@ -39,3 +43,6 @@ hi def link pacmanlogPackageName Normal hi def link pacmanlogPackageVersion Comment let b:current_syntax = "pacmanlog" diff --git a/runtime/syntax/rasi.vim b/runtime/syntax/rasi.vim index 40c3393fc574cc..c4c4508f12e933 100644 --- a/runtime/syntax/rasi.vim +++ b/runtime/syntax/rasi.vim @@ -2,6 +2,7 @@ " Language: rasi (Rofi Advanced Style Information) " Maintainer: Pierrick Guillaume <[email protected]> " Last Change: 2024 May 21 " Syntax support for rasi config file @@ -12,6 +13,8 @@ if exists('b:current_syntax') let b:current_syntax = 'rasi' " String {{{ syn region rasiString start=+"+ skip=+\\"+ end=+"+ oneline contained @@ -295,4 +298,7 @@ hi def link rasiInvPropertyId rasiError hi def link rasiInvPropertyVal rasiError " }}} " vim:ts=8 diff --git a/runtime/syntax/tutor.vim b/runtime/syntax/tutor.vim index 399026790a42ff..4326d88fb36fc2 100644 --- a/runtime/syntax/tutor.vim +++ b/runtime/syntax/tutor.vim @@ -1,7 +1,14 @@ +" Maintainer: Vim Project +" Last Change: 2025 Apr 16 syn include @VIM syntax/vim.vim unlet b:current_syntax syn include @TUTORSHELL syntax/sh.vim @@ -77,3 +84,5 @@ hi def link tutorInlineX tutorX hi def link tutorShellPrompt Delimiter let b:current_syntax = "tutor" diff --git a/runtime/syntax/typst.vim b/runtime/syntax/typst.vim index b1f05ec85391a5..686f7c3f31e216 100644 --- a/runtime/syntax/typst.vim +++ b/runtime/syntax/typst.vim @@ -1,14 +1,18 @@ " Vim syntax file " Language: Typst -" Previous Maintainer: Gregory Anders " Maintainer: Luca Saccarola <[email protected]> +" Previous Maintainer: Gregory Anders +" Based On: https://github.com/kaarmu/typst.vim " Last Change: 2024 Dec 09 -" Based on: https://github.com/kaarmu/typst.vim syntax sync fromstart syntax spell toplevel @@ -470,4 +474,7 @@ highlight default typstMarkupBoldItalic term=bold,italic let b:current_syntax = 'typst' " }}}1
[ "+\" Language:\tVim Tutor" ]
[ 426 ]
{ "additions": 127, "author": "clason", "deletions": 8, "html_url": "https://github.com/neovim/neovim/pull/33501", "issue_id": 33501, "merged_at": "2025-04-17T07:25:42Z", "omission_probability": 0.1, "pr_number": 33501, "repo": "neovim/neovim", "title": "vim-patch: update runtime files", "total_changes": 135 }
394
diff --git a/src/nvim/edit.c b/src/nvim/edit.c index 9bdd035cb42390..d176c98ed18805 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -3250,7 +3250,7 @@ static void ins_reg(void) do_put(regname, NULL, BACKWARD, 1, (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND); - } else if (insert_reg(regname, literally) == FAIL) { + } else if (insert_reg(regname, NULL, literally) == FAIL) { vim_beep(kOptBoFlagRegister); need_redraw = true; // remove the '"' } else if (stop_insert_mode) { diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index abc2137bc2fa1a..6d0619d8299c2b 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -503,15 +503,16 @@ bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent) // happens for the GUI). if ((State & MODE_INSERT)) { if (regname == '.') { - insert_reg(regname, true); + insert_reg(regname, NULL, true); } else { if (regname == 0 && eval_has_provider("clipboard", false)) { regname = '*'; } - if ((State & REPLACE_FLAG) && !yank_register_mline(regname)) { - insert_reg(regname, true); + yankreg_T *reg = NULL; + if ((State & REPLACE_FLAG) && !yank_register_mline(regname, &reg)) { + insert_reg(regname, reg, true); } else { - do_put(regname, NULL, BACKWARD, 1, + do_put(regname, reg, BACKWARD, 1, (fixindent ? PUT_FIXINDENT : 0) | PUT_CURSEND); // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r @@ -833,7 +834,8 @@ bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent) if (regname == 0 && eval_has_provider("clipboard", false)) { regname = '*'; } - if (yank_register_mline(regname)) { + yankreg_T *reg = NULL; + if (yank_register_mline(regname, &reg)) { if (mouse_past_bottom) { dir = FORWARD; } @@ -855,7 +857,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent) if (restart_edit != 0) { where_paste_started = curwin->w_cursor; } - do_put(regname, NULL, dir, count, + do_put(regname, reg, dir, count, (fixindent ? PUT_FIXINDENT : 0)| PUT_CURSEND); } else if (((mod_mask & MOD_MASK_CTRL) || (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) && bt_quickfix(curbuf)) { diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 977d26890e0081..cab775a189b92b 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -966,16 +966,23 @@ yankreg_T *copy_register(int name) } /// Check if the current yank register has kMTLineWise register type -bool yank_register_mline(int regname) +/// For valid, non-blackhole registers also provides pointer to the register +/// structure prepared for pasting. +/// +/// @param regname The name of the register used or 0 for the unnamed register +/// @param reg Pointer to store yankreg_T* for the requested register. Will be +/// set to NULL for invalid or blackhole registers. +bool yank_register_mline(int regname, yankreg_T **reg) { + *reg = NULL; if (regname != 0 && !valid_yank_reg(regname, false)) { return false; } if (regname == '_') { // black hole is always empty return false; } - yankreg_T *reg = get_yank_register(regname, YREG_PASTE); - return reg->y_type == kMTLineWise; + *reg = get_yank_register(regname, YREG_PASTE); + return (*reg)->y_type == kMTLineWise; } /// Start or stop recording into a yank register. @@ -1322,7 +1329,7 @@ static int put_in_typebuf(char *s, bool esc, bool colon, int silent) /// @param literally_arg insert literally, not as if typed /// /// @return FAIL for failure, OK otherwise -int insert_reg(int regname, bool literally_arg) +int insert_reg(int regname, yankreg_T *reg, bool literally_arg) { int retval = OK; bool allocated; @@ -1353,7 +1360,9 @@ int insert_reg(int regname, bool literally_arg) xfree(arg); } } else { // Name or number register. - yankreg_T *reg = get_yank_register(regname, YREG_PASTE); + if (reg == NULL) { + reg = get_yank_register(regname, YREG_PASTE); + } if (reg->y_array == NULL) { retval = FAIL; } else {
diff --git a/src/nvim/edit.c b/src/nvim/edit.c index 9bdd035cb42390..d176c98ed18805 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -3250,7 +3250,7 @@ static void ins_reg(void) do_put(regname, NULL, BACKWARD, 1, (literally == Ctrl_P ? PUT_FIXINDENT : 0) | PUT_CURSEND); - } else if (insert_reg(regname, literally) == FAIL) { + } else if (insert_reg(regname, NULL, literally) == FAIL) { vim_beep(kOptBoFlagRegister); need_redraw = true; // remove the '"' } else if (stop_insert_mode) { diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c index abc2137bc2fa1a..6d0619d8299c2b 100644 --- a/src/nvim/mouse.c +++ b/src/nvim/mouse.c @@ -503,15 +503,16 @@ bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent) // happens for the GUI). if ((State & MODE_INSERT)) { if (regname == '.') { + insert_reg(regname, NULL, true); } else { if (regname == 0 && eval_has_provider("clipboard", false)) { regname = '*'; } - if ((State & REPLACE_FLAG) && !yank_register_mline(regname)) { - insert_reg(regname, true); + yankreg_T *reg = NULL; + if ((State & REPLACE_FLAG) && !yank_register_mline(regname, &reg)) { + insert_reg(regname, reg, true); } else { - do_put(regname, NULL, BACKWARD, 1, + do_put(regname, reg, BACKWARD, 1, (fixindent ? PUT_FIXINDENT : 0) | PUT_CURSEND); // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r @@ -833,7 +834,8 @@ bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent) if (regname == 0 && eval_has_provider("clipboard", false)) { regname = '*'; + yankreg_T *reg = NULL; + if (yank_register_mline(regname, &reg)) { if (mouse_past_bottom) { dir = FORWARD; } @@ -855,7 +857,7 @@ bool do_mouse(oparg_T *oap, int c, int dir, int count, bool fixindent) if (restart_edit != 0) { where_paste_started = curwin->w_cursor; - do_put(regname, NULL, dir, count, + do_put(regname, reg, dir, count, (fixindent ? PUT_FIXINDENT : 0)| PUT_CURSEND); } else if (((mod_mask & MOD_MASK_CTRL) || (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK) && bt_quickfix(curbuf)) { diff --git a/src/nvim/ops.c b/src/nvim/ops.c index 977d26890e0081..cab775a189b92b 100644 --- a/src/nvim/ops.c +++ b/src/nvim/ops.c @@ -966,16 +966,23 @@ yankreg_T *copy_register(int name) /// Check if the current yank register has kMTLineWise register type -bool yank_register_mline(int regname) +/// For valid, non-blackhole registers also provides pointer to the register +/// structure prepared for pasting. +/// +/// @param regname The name of the register used or 0 for the unnamed register +/// @param reg Pointer to store yankreg_T* for the requested register. Will be +/// set to NULL for invalid or blackhole registers. +bool yank_register_mline(int regname, yankreg_T **reg) + *reg = NULL; if (regname != 0 && !valid_yank_reg(regname, false)) { if (regname == '_') { // black hole is always empty - yankreg_T *reg = get_yank_register(regname, YREG_PASTE); - return reg->y_type == kMTLineWise; + *reg = get_yank_register(regname, YREG_PASTE); + return (*reg)->y_type == kMTLineWise; /// Start or stop recording into a yank register. @@ -1322,7 +1329,7 @@ static int put_in_typebuf(char *s, bool esc, bool colon, int silent) /// @param literally_arg insert literally, not as if typed /// /// @return FAIL for failure, OK otherwise -int insert_reg(int regname, bool literally_arg) +int insert_reg(int regname, yankreg_T *reg, bool literally_arg) int retval = OK; bool allocated; @@ -1353,7 +1360,9 @@ int insert_reg(int regname, bool literally_arg) xfree(arg); } else { // Name or number register. - yankreg_T *reg = get_yank_register(regname, YREG_PASTE); + reg = get_yank_register(regname, YREG_PASTE); + } if (reg->y_array == NULL) { retval = FAIL; } else {
[ "- insert_reg(regname, true);", "- if (yank_register_mline(regname)) {", "+ if (reg == NULL) {" ]
[ 21, 42, 102 ]
{ "additions": 23, "author": "dtor", "deletions": 12, "html_url": "https://github.com/neovim/neovim/pull/33494", "issue_id": 33494, "merged_at": "2025-04-16T10:08:42Z", "omission_probability": 0.1, "pr_number": 33494, "repo": "neovim/neovim", "title": "fix(mouse): do not fetch clipboard twice when pasting with middle button", "total_changes": 35 }
395
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 0815c64c935bc9..6d77a93ccfa4d3 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -156,6 +156,8 @@ variables can be used to overrule the filetype used for certain extensions: `*.inc` g:filetype_inc `*.lsl` g:filetype_lsl `*.m` g:filetype_m |ft-mathematica-syntax| + `*[mM]makefile,*.mk,*.mak,[mM]akefile*` + g:make_flavor |ft-make-syntax| `*.markdown,*.mdown,*.mkd,*.mkdn,*.mdwn,*.md` g:filetype_md |ft-pandoc-syntax| `*.mod` g:filetype_mod diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 317961c12bf49d..faa42b066c1700 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -1914,11 +1914,16 @@ Comments are also highlighted by default. You can turn this off by using: > :let make_no_comments = 1 -Microsoft Makefile handles variable expansion and comments differently -(backslashes are not used for escape). If you see any wrong highlights -because of this, you can try this: > - - :let make_microsoft = 1 +There are various Make implementations, which add extensions other than the +POSIX specification and thus are mutually incompatible. If the filename is +BSDmakefile or GNUmakefile, the corresponding implementation is automatically +determined; otherwise vim tries to detect it by the file contents. If you see +any wrong highlights because of this, you can enforce a flavor by setting one +of the following: > + + :let g:make_flavor = 'bsd' " or + :let g:make_flavor = 'gnu' " or + :let g:make_flavor = 'microsoft' MAPLE *maple.vim* *ft-maple-syntax* diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 426102b35330d4..9b3e1526b2df45 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -2290,7 +2290,7 @@ local pattern = { ['^Containerfile%.'] = starsetf('dockerfile'), ['^Dockerfile%.'] = starsetf('dockerfile'), ['[mM]akefile$'] = detect.make, - ['^[mM]akefile'] = starsetf('make'), + ['^[mM]akefile'] = starsetf(detect.make), ['^[rR]akefile'] = starsetf('ruby'), ['^%.profile'] = detect.sh, }, diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index 96be7edbae6976..c2674febc6893f 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -1021,16 +1021,46 @@ end --- Check if it is a Microsoft Makefile --- @type vim.filetype.mapfn -function M.make(_, bufnr) - vim.b.make_microsoft = nil +function M.make(path, bufnr) + vim.b.make_flavor = nil + + -- 1. filename + local file_name = fn.fnamemodify(path, ':t') + if file_name == 'BSDmakefile' then + vim.b.make_flavor = 'bsd' + return 'make' + elseif file_name == 'GNUmakefile' then + vim.b.make_flavor = 'gnu' + return 'make' + end + + -- 2. user's setting + if vim.g.make_flavor ~= nil then + vim.b.make_flavor = vim.g.make_flavor + return 'make' + elseif vim.g.make_microsoft ~= nil then + vim._truncated_echo_once( + "make_microsoft is deprecated; try g:make_flavor = 'microsoft' instead" + ) + vim.b.make_flavor = 'microsoft' + return 'make' + end + + -- 3. try to detect a flavor from file content for _, line in ipairs(getlines(bufnr, 1, 1000)) do if matchregex(line, [[\c^\s*!\s*\(ifn\=\(def\)\=\|include\|message\|error\)\>]]) then - vim.b.make_microsoft = 1 + vim.b.make_flavor = 'microsoft' + break + elseif + matchregex(line, [[^\.\%(export\|error\|for\|if\%(n\=\%(def\|make\)\)\=\|info\|warning\)\>]]) + then + vim.b.make_flavor = 'bsd' break elseif - matchregex(line, [[^ *ifn\=\(eq\|def\)\>]]) - or findany(line, { '^ *[-s]?%s', '^ *%w+%s*[!?:+]=' }) + matchregex(line, [[^ *\%(ifn\=\%(eq\|def\)\|define\|override\)\>]]) + or line:find('%$[({][a-z-]+%s+%S+') -- a function call, e.g. $(shell pwd) then + vim.b.make_flavor = 'gnu' break end end diff --git a/runtime/syntax/make.vim b/runtime/syntax/make.vim index d3ddf782912d40..a6d8ad47e39709 100644 --- a/runtime/syntax/make.vim +++ b/runtime/syntax/make.vim @@ -4,6 +4,7 @@ " Previous Maintainer: Claudio Fleiner <[email protected]> " URL: https://github.com/vim/vim/blob/master/runtime/syntax/make.vim " Last Change: 2022 Nov 06 +" 2025 Apr 15 by Vim project: rework Make flavor detection (#17089) " quit when a syntax file was already loaded if exists("b:current_syntax") @@ -13,6 +14,9 @@ endif let s:cpo_save = &cpo set cpo&vim +" enable GNU extension when b:make_flavor is not set—detection failed or Makefile is POSIX-compliant +let s:make_flavor = 'gnu' + " some special characters syn match makeSpecial "^\s*[@+-]\+" syn match makeNextLine "\\\n\s*" @@ -21,14 +25,16 @@ syn match makeNextLine "\\\n\s*" syn region makeDefine start="^\s*define\s" end="^\s*endef\s*\(#.*\)\?$" \ contains=makeStatement,makeIdent,makePreCondit,makeDefine -" Microsoft Makefile specials -syn case ignore -syn match makeInclude "^!\s*include\s.*$" -syn match makePreCondit "^!\s*\(cmdswitches\|error\|message\|include\|if\|ifdef\|ifndef\|else\|else\s*if\|else\s*ifdef\|else\s*ifndef\|endif\|undef\)\>" -syn case match +if get(b:, 'make_flavor', s:make_flavor) == 'microsoft' + " Microsoft Makefile specials + syn case ignore + syn match makeInclude "^!\s*include\s.*$" + syn match makePreCondit "^!\s*\(cmdswitches\|error\|message\|include\|if\|ifdef\|ifndef\|else\|else\s*if\|else\s*ifdef\|else\s*ifndef\|endif\|undef\)\>" + syn case match +endif " identifiers -if exists("b:make_microsoft") || exists("make_microsoft") +if get(b:, 'make_flavor', s:make_flavor) == 'microsoft' syn region makeIdent start="\$(" end=")" contains=makeStatement,makeIdent syn region makeIdent start="\${" end="}" contains=makeStatement,makeIdent else @@ -59,13 +65,31 @@ syn match makeTarget "^[~A-Za-z0-9_./$(){}%*@-][A-Za-z0-9_./\t $(){}%* \ skipnl nextgroup=makeCommands,makeCommandError syn region makeSpecTarget transparent matchgroup=makeSpecTarget - \ start="^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|EXPORT_ALL_VARIABLES\|KEEP_STATE\|LIBPATTERNS\|NOTPARALLEL\|DELETE_ON_ERROR\|INTERMEDIATE\|POSIX\|SECONDARY\|ONESHELL\)\>\s*:\{1,2}[^:=]"rs=e-1 + \ start="^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|NOTPARALLEL\|POSIX\)\>\s*:\{1,2}[^:=]"rs=e-1 \ end="[^\\]$" keepend \ contains=makeIdent,makeSpecTarget,makeNextLine,makeComment skipnl nextGroup=makeCommands -syn match makeSpecTarget "^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|EXPORT_ALL_VARIABLES\|KEEP_STATE\|LIBPATTERNS\|NOTPARALLEL\|DELETE_ON_ERROR\|INTERMEDIATE\|POSIX\|SECONDARY\|ONESHELL\)\>\s*::\=\s*$" +syn match makeSpecTarget "^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|NOTPARALLEL\|POSIX\)\>\s*::\=\s*$" \ contains=makeIdent,makeComment \ skipnl nextgroup=makeCommands,makeCommandError +if get(b:, 'make_flavor', s:make_flavor) == 'bsd' + syn region makeSpecTarget transparent matchgroup=makeSpecTarget + \ start="^\.DELETE_ON_ERROR\>\s*:\{1,2}[^:=]"rs=e-1 + \ end="[^\\]$" keepend + \ contains=makeIdent,makeSpecTarget,makeNextLine,makeComment skipnl nextGroup=makeCommands + syn match makeSpecTarget "^\.DELETE_ON_ERROR\>\s*::\=\s*$" + \ contains=makeIdent,makeComment + \ skipnl nextgroup=makeCommands,makeCommandError +elseif get(b:, 'make_flavor', s:make_flavor) == 'gnu' + syn region makeSpecTarget transparent matchgroup=makeSpecTarget + \ start="^\.\(EXPORT_ALL_VARIABLES\|DELETE_ON_ERROR\|INTERMEDIATE\|KEEP_STATE\|LIBPATTERNS\|ONESHELL\|SECONDARY\)\>\s*:\{1,2}[^:=]"rs=e-1 + \ end="[^\\]$" keepend + \ contains=makeIdent,makeSpecTarget,makeNextLine,makeComment skipnl nextGroup=makeCommands + syn match makeSpecTarget "^\.\(EXPORT_ALL_VARIABLES\|DELETE_ON_ERROR\|INTERMEDIATE\|KEEP_STATE\|LIBPATTERNS\|ONESHELL\|SECONDARY\)\>\s*::\=\s*$" + \ contains=makeIdent,makeComment + \ skipnl nextgroup=makeCommands,makeCommandError +endif + syn match makeCommandError "^\s\+\S.*" contained syn region makeCommands contained start=";"hs=s+1 start="^\t" \ end="^[^\t#]"me=e-1,re=e-1 end="^$" @@ -74,17 +98,19 @@ syn region makeCommands contained start=";"hs=s+1 start="^\t" syn match makeCmdNextLine "\\\n."he=e-1 contained " some directives -syn match makePreCondit "^ *\(ifn\=\(eq\|def\)\>\|else\(\s\+ifn\=\(eq\|def\)\)\=\>\|endif\>\)" syn match makeInclude "^ *[-s]\=include\s.*$" -syn match makeStatement "^ *vpath" syn match makeExport "^ *\(export\|unexport\)\>" -syn match makeOverride "^ *override\>" -" Statements / Functions (GNU make) -syn match makeStatement contained "(\(abspath\|addprefix\|addsuffix\|and\|basename\|call\|dir\|error\|eval\|file\|filter-out\|filter\|findstring\|firstword\|flavor\|foreach\|guile\|if\|info\|join\|lastword\|notdir\|or\|origin\|patsubst\|realpath\|shell\|sort\|strip\|subst\|suffix\|value\|warning\|wildcard\|word\|wordlist\|words\)\>"ms=s+1 +if get(b:, 'make_flavor', s:make_flavor) == 'gnu' + " Statements / Functions (GNU make) + syn match makePreCondit "^ *\(ifn\=\(eq\|def\)\>\|else\(\s\+ifn\=\(eq\|def\)\)\=\>\|endif\>\)" + syn match makeStatement "^ *vpath\>" + syn match makeOverride "^ *override\>" + syn match makeStatement contained "[({]\(abspath\|addprefix\|addsuffix\|and\|basename\|call\|dir\|error\|eval\|file\|filter-out\|filter\|findstring\|firstword\|flavor\|foreach\|guile\|if\|info\|intcmp\|join\|lastword\|let\|notdir\|or\|origin\|patsubst\|realpath\|shell\|sort\|strip\|subst\|suffix\|value\|warning\|wildcard\|word\|wordlist\|words\)\>"ms=s+1 +endif " Comment if !exists("make_no_comments") - if exists("b:make_microsoft") || exists("make_microsoft") + if get(b:, 'make_flavor', s:make_flavor) == 'microsoft' syn match makeComment "#.*" contains=@Spell,makeTodo else syn region makeComment start="#" end="^$" end="[^\\]$" keepend contains=@Spell,makeTodo diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim index ec15fadf28a791..0c010b120a372a 100644 --- a/test/old/testdir/test_filetype.vim +++ b/test/old/testdir/test_filetype.vim @@ -2851,15 +2851,48 @@ endfunc func Test_make_file() filetype on + " BSD Makefile + call writefile([''], 'BSDmakefile', 'D') + split BSDmakefile + call assert_equal('bsd', get(b:, 'make_flavor', '')) + bwipe! + + call writefile(['.ifmake all', '.endif'], 'XMakefile.mak', 'D') + split XMakefile.mak + call assert_equal('bsd', get(b:, 'make_flavor', '')) + bwipe! + + " GNU Makefile + call writefile([''], 'GNUmakefile', 'D') + split GNUmakefile + call assert_equal('gnu', get(b:, 'make_flavor', '')) + bwipe! + + call writefile(['ifeq ($(foo),foo)', 'endif'], 'XMakefile.mak', 'D') + split XMakefile.mak + call assert_equal('gnu', get(b:, 'make_flavor', '')) + bwipe! + + call writefile(['define foo', 'endef'], 'XMakefile.mak', 'D') + split XMakefile.mak + call assert_equal('gnu', get(b:, 'make_flavor', '')) + bwipe! + + call writefile(['vim := $(wildcard *.vim)'], 'XMakefile.mak', 'D') + split XMakefile.mak + call assert_equal('gnu', get(b:, 'make_flavor', '')) + bwipe! + " Microsoft Makefile call writefile(['# Makefile for Windows', '!if "$(VIMDLL)" == "yes"'], 'XMakefile.mak', 'D') split XMakefile.mak - call assert_equal(1, get(b:, 'make_microsoft', 0)) + call assert_equal('microsoft', get(b:, 'make_flavor', '')) bwipe! + " BSD or GNU call writefile(['# get the list of tests', 'include testdir/Make_all.mak'], 'XMakefile.mak', 'D') split XMakefile.mak - call assert_equal(0, get(b:, 'make_microsoft', 0)) + call assert_notequal('microsoft', get(b:, 'make_flavor', '')) bwipe! filetype off
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt index 0815c64c935bc9..6d77a93ccfa4d3 100644 --- a/runtime/doc/filetype.txt +++ b/runtime/doc/filetype.txt @@ -156,6 +156,8 @@ variables can be used to overrule the filetype used for certain extensions: `*.inc` g:filetype_inc `*.lsl` g:filetype_lsl `*.m` g:filetype_m |ft-mathematica-syntax| + `*[mM]makefile,*.mk,*.mak,[mM]akefile*` + g:make_flavor |ft-make-syntax| `*.markdown,*.mdown,*.mkd,*.mkdn,*.mdwn,*.md` g:filetype_md |ft-pandoc-syntax| `*.mod` g:filetype_mod diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt index 317961c12bf49d..faa42b066c1700 100644 --- a/runtime/doc/syntax.txt +++ b/runtime/doc/syntax.txt @@ -1914,11 +1914,16 @@ Comments are also highlighted by default. You can turn this off by using: > :let make_no_comments = 1 -Microsoft Makefile handles variable expansion and comments differently -(backslashes are not used for escape). If you see any wrong highlights -because of this, you can try this: > - - :let make_microsoft = 1 +There are various Make implementations, which add extensions other than the +POSIX specification and thus are mutually incompatible. If the filename is +BSDmakefile or GNUmakefile, the corresponding implementation is automatically +determined; otherwise vim tries to detect it by the file contents. If you see +any wrong highlights because of this, you can enforce a flavor by setting one +of the following: > + :let g:make_flavor = 'bsd' " or + :let g:make_flavor = 'gnu' " or + :let g:make_flavor = 'microsoft' MAPLE *maple.vim* *ft-maple-syntax* diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua index 426102b35330d4..9b3e1526b2df45 100644 --- a/runtime/lua/vim/filetype.lua +++ b/runtime/lua/vim/filetype.lua @@ -2290,7 +2290,7 @@ local pattern = { ['^Containerfile%.'] = starsetf('dockerfile'), ['^Dockerfile%.'] = starsetf('dockerfile'), ['[mM]akefile$'] = detect.make, - ['^[mM]akefile'] = starsetf('make'), + ['^[mM]akefile'] = starsetf(detect.make), ['^[rR]akefile'] = starsetf('ruby'), ['^%.profile'] = detect.sh, }, diff --git a/runtime/lua/vim/filetype/detect.lua b/runtime/lua/vim/filetype/detect.lua index 96be7edbae6976..c2674febc6893f 100644 --- a/runtime/lua/vim/filetype/detect.lua +++ b/runtime/lua/vim/filetype/detect.lua @@ -1021,16 +1021,46 @@ end --- Check if it is a Microsoft Makefile --- @type vim.filetype.mapfn -function M.make(_, bufnr) - vim.b.make_microsoft = nil +function M.make(path, bufnr) + vim.b.make_flavor = nil + local file_name = fn.fnamemodify(path, ':t') + elseif file_name == 'GNUmakefile' then + vim.b.make_flavor = 'gnu' + if vim.g.make_flavor ~= nil then + vim.b.make_flavor = vim.g.make_flavor + elseif vim.g.make_microsoft ~= nil then + vim._truncated_echo_once( for _, line in ipairs(getlines(bufnr, 1, 1000)) do if matchregex(line, [[\c^\s*!\s*\(ifn\=\(def\)\=\|include\|message\|error\)\>]]) then - vim.b.make_microsoft = 1 + vim.b.make_flavor = 'microsoft' + break + matchregex(line, [[^\.\%(export\|error\|for\|if\%(n\=\%(def\|make\)\)\=\|info\|warning\)\>]]) + then + vim.b.make_flavor = 'bsd' elseif - matchregex(line, [[^ *ifn\=\(eq\|def\)\>]]) - or findany(line, { '^ *[-s]?%s', '^ *%w+%s*[!?:+]=' }) + matchregex(line, [[^ *\%(ifn\=\%(eq\|def\)\|define\|override\)\>]]) then + vim.b.make_flavor = 'gnu' end end diff --git a/runtime/syntax/make.vim b/runtime/syntax/make.vim index d3ddf782912d40..a6d8ad47e39709 100644 --- a/runtime/syntax/make.vim +++ b/runtime/syntax/make.vim @@ -4,6 +4,7 @@ " Previous Maintainer: Claudio Fleiner <[email protected]> " URL: https://github.com/vim/vim/blob/master/runtime/syntax/make.vim " Last Change: 2022 Nov 06 +" 2025 Apr 15 by Vim project: rework Make flavor detection (#17089) " quit when a syntax file was already loaded if exists("b:current_syntax") @@ -13,6 +14,9 @@ endif let s:cpo_save = &cpo set cpo&vim +" enable GNU extension when b:make_flavor is not set—detection failed or Makefile is POSIX-compliant +let s:make_flavor = 'gnu' " some special characters syn match makeSpecial "^\s*[@+-]\+" syn match makeNextLine "\\\n\s*" @@ -21,14 +25,16 @@ syn match makeNextLine "\\\n\s*" syn region makeDefine start="^\s*define\s" end="^\s*endef\s*\(#.*\)\?$" \ contains=makeStatement,makeIdent,makePreCondit,makeDefine -" Microsoft Makefile specials -syn case ignore -syn match makeInclude "^!\s*include\s.*$" -syn match makePreCondit "^!\s*\(cmdswitches\|error\|message\|include\|if\|ifdef\|ifndef\|else\|else\s*if\|else\s*ifdef\|else\s*ifndef\|endif\|undef\)\>" -syn case match + " Microsoft Makefile specials + syn case ignore + syn match makeInclude "^!\s*include\s.*$" + syn match makePreCondit "^!\s*\(cmdswitches\|error\|message\|include\|if\|ifdef\|ifndef\|else\|else\s*if\|else\s*ifdef\|else\s*ifndef\|endif\|undef\)\>" + syn case match " identifiers -if exists("b:make_microsoft") || exists("make_microsoft") syn region makeIdent start="\$(" end=")" contains=makeStatement,makeIdent syn region makeIdent start="\${" end="}" contains=makeStatement,makeIdent else @@ -59,13 +65,31 @@ syn match makeTarget "^[~A-Za-z0-9_./$(){}%*@-][A-Za-z0-9_./\t $(){}%* syn region makeSpecTarget transparent matchgroup=makeSpecTarget - \ start="^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|EXPORT_ALL_VARIABLES\|KEEP_STATE\|LIBPATTERNS\|NOTPARALLEL\|DELETE_ON_ERROR\|INTERMEDIATE\|POSIX\|SECONDARY\|ONESHELL\)\>\s*:\{1,2}[^:=]"rs=e-1 \ end="[^\\]$" keepend \ contains=makeIdent,makeSpecTarget,makeNextLine,makeComment skipnl nextGroup=makeCommands -syn match makeSpecTarget "^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|EXPORT_ALL_VARIABLES\|KEEP_STATE\|LIBPATTERNS\|NOTPARALLEL\|DELETE_ON_ERROR\|INTERMEDIATE\|POSIX\|SECONDARY\|ONESHELL\)\>\s*::\=\s*$" +syn match makeSpecTarget "^\.\(SUFFIXES\|PHONY\|DEFAULT\|PRECIOUS\|IGNORE\|SILENT\|NOTPARALLEL\|POSIX\)\>\s*::\=\s*$" \ contains=makeIdent,makeComment +if get(b:, 'make_flavor', s:make_flavor) == 'bsd' + \ start="^\.DELETE_ON_ERROR\>\s*:\{1,2}[^:=]"rs=e-1 + syn match makeSpecTarget "^\.DELETE_ON_ERROR\>\s*::\=\s*$" +elseif get(b:, 'make_flavor', s:make_flavor) == 'gnu' + \ start="^\.\(EXPORT_ALL_VARIABLES\|DELETE_ON_ERROR\|INTERMEDIATE\|KEEP_STATE\|LIBPATTERNS\|ONESHELL\|SECONDARY\)\>\s*:\{1,2}[^:=]"rs=e-1 syn match makeCommandError "^\s\+\S.*" contained syn region makeCommands contained start=";"hs=s+1 start="^\t" \ end="^[^\t#]"me=e-1,re=e-1 end="^$" @@ -74,17 +98,19 @@ syn region makeCommands contained start=";"hs=s+1 start="^\t" syn match makeCmdNextLine "\\\n."he=e-1 contained " some directives -syn match makePreCondit "^ *\(ifn\=\(eq\|def\)\>\|else\(\s\+ifn\=\(eq\|def\)\)\=\>\|endif\>\)" syn match makeInclude "^ *[-s]\=include\s.*$" -syn match makeStatement "^ *vpath" syn match makeExport "^ *\(export\|unexport\)\>" -syn match makeOverride "^ *override\>" -" Statements / Functions (GNU make) -syn match makeStatement contained "(\(abspath\|addprefix\|addsuffix\|and\|basename\|call\|dir\|error\|eval\|file\|filter-out\|filter\|findstring\|firstword\|flavor\|foreach\|guile\|if\|info\|join\|lastword\|notdir\|or\|origin\|patsubst\|realpath\|shell\|sort\|strip\|subst\|suffix\|value\|warning\|wildcard\|word\|wordlist\|words\)\>"ms=s+1 +if get(b:, 'make_flavor', s:make_flavor) == 'gnu' + " Statements / Functions (GNU make) + syn match makePreCondit "^ *\(ifn\=\(eq\|def\)\>\|else\(\s\+ifn\=\(eq\|def\)\)\=\>\|endif\>\)" + syn match makeStatement "^ *vpath\>" + syn match makeOverride "^ *override\>" + syn match makeStatement contained "[({]\(abspath\|addprefix\|addsuffix\|and\|basename\|call\|dir\|error\|eval\|file\|filter-out\|filter\|findstring\|firstword\|flavor\|foreach\|guile\|if\|info\|intcmp\|join\|lastword\|let\|notdir\|or\|origin\|patsubst\|realpath\|shell\|sort\|strip\|subst\|suffix\|value\|warning\|wildcard\|word\|wordlist\|words\)\>"ms=s+1 " Comment if !exists("make_no_comments") - if exists("b:make_microsoft") || exists("make_microsoft") + if get(b:, 'make_flavor', s:make_flavor) == 'microsoft' syn match makeComment "#.*" contains=@Spell,makeTodo else syn region makeComment start="#" end="^$" end="[^\\]$" keepend contains=@Spell,makeTodo diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim index ec15fadf28a791..0c010b120a372a 100644 --- a/test/old/testdir/test_filetype.vim +++ b/test/old/testdir/test_filetype.vim @@ -2851,15 +2851,48 @@ endfunc func Test_make_file() filetype on + " BSD Makefile + call writefile([''], 'BSDmakefile', 'D') + split BSDmakefile + call writefile(['.ifmake all', '.endif'], 'XMakefile.mak', 'D') + " GNU Makefile + call writefile([''], 'GNUmakefile', 'D') + split GNUmakefile + call writefile(['define foo', 'endef'], 'XMakefile.mak', 'D') + call writefile(['vim := $(wildcard *.vim)'], 'XMakefile.mak', 'D') " Microsoft Makefile call writefile(['# Makefile for Windows', '!if "$(VIMDLL)" == "yes"'], 'XMakefile.mak', 'D') + call assert_equal('microsoft', get(b:, 'make_flavor', '')) + " BSD or GNU call writefile(['# get the list of tests', 'include testdir/Make_all.mak'], 'XMakefile.mak', 'D') - call assert_equal(0, get(b:, 'make_microsoft', 0)) + call assert_notequal('microsoft', get(b:, 'make_flavor', '')) filetype off
[ "+ -- 1. filename", "+ if file_name == 'BSDmakefile' then", "+ vim.b.make_flavor = 'bsd'", "+ -- 2. user's setting", "+ \"make_microsoft is deprecated; try g:make_flavor = 'microsoft' instead\"", "+ )", "+ vim.b.make_flavor = 'microsoft'", "+ -- 3. try to detect a flavor from file content", "+ elseif", "+ or line:find('%$[({][a-z-]+%s+%S+') -- a function call, e.g. $(shell pwd)", "+\t\\ start=\"^\\.\\(SUFFIXES\\|PHONY\\|DEFAULT\\|PRECIOUS\\|IGNORE\\|SILENT\\|NOTPARALLEL\\|POSIX\\)\\>\\s*:\\{1,2}[^:=]\"rs=e-1", "+ syn match makeSpecTarget\t\"^\\.\\(EXPORT_ALL_VARIABLES\\|DELETE_ON_ERROR\\|INTERMEDIATE\\|KEEP_STATE\\|LIBPATTERNS\\|ONESHELL\\|SECONDARY\\)\\>\\s*::\\=\\s*$\"", "+ call writefile(['ifeq ($(foo),foo)', 'endif'], 'XMakefile.mak', 'D')", "- call assert_equal(1, get(b:, 'make_microsoft', 0))" ]
[ 65, 67, 68, 75, 81, 82, 83, 87, 93, 102, 158, 179, 238, 256 ]
{ "additions": 123, "author": "zeertzjq", "deletions": 27, "html_url": "https://github.com/neovim/neovim/pull/33498", "issue_id": 33498, "merged_at": "2025-04-16T23:13:05Z", "omission_probability": 0.1, "pr_number": 33498, "repo": "neovim/neovim", "title": "vim-patch:9.1.1307: make syntax does not reliably detect different flavors", "total_changes": 150 }
396
diff --git a/src/man/nvim.1 b/src/man/nvim.1 index 9b7680d0112cb2..82a06b4a11ebf1 100644 --- a/src/man/nvim.1 +++ b/src/man/nvim.1 @@ -30,18 +30,17 @@ Commands in .Nm begin with colon .Pq Sq \&: . -Type ":help subject" to get help on a specific subject. -Use <Tab> and CTRL-D to complete subjects (":help cmdline\-completion"). +Type \(lq:help subject\(rq to get help on a specific subject. +Use <Tab> and CTRL-D to complete subjects (\(lq:help cmdline-completion\(rq). .Pp -The "quickref" help section is a condensed reference of editor features: +The \(lqquickref\(rq help section is a condensed reference of editor features: .Dl :help quickref .Pp If you are new to Vim/Nvim, start with the 30-minute tutorial: .Dl :Tutor .Pp -After installing/updating Nvim, it's a good idea to run the self-check: +After installing/updating Nvim, it\(aqs a good idea to run the self-check: .Dl :checkhealth -.Pp .Bl -tag -width Fl .It Ar file ... File(s) to edit. @@ -72,7 +71,7 @@ Display the first error in .Ar errorfile . If .Ar errorfile -is omitted, the value of the 'errorfile' option is used (defaults to +is omitted, the value of the \(aqerrorfile\(aq option is used (defaults to .Cm errors.err ) . Further errors can be jumped to with the .Ic :cnext @@ -80,24 +79,25 @@ command. .Ic ":help quickfix" .It Fl - End of options. -Remaining arguments are treated as literal file names, including filenames starting with hyphen +Remaining arguments are treated as literal file names, including filenames +starting with hyphen .Pq Sq - . .It Fl e Ex mode, reading stdin as Ex commands. .Ic ":help Ex-mode" .It Fl E Ex mode, reading stdin as text. -.Ic :help Ex-mode +.Ic ":help Ex-mode" .It Fl es Silent (non-interactive) Ex mode, reading stdin as Ex commands. Useful for scripting because it does NOT start a UI, unlike .Fl e . -.Ic :help silent-mode +.Ic ":help silent-mode" .It Fl \&Es Silent (non-interactive) Ex mode, reading stdin as text. Useful for scripting because it does NOT start a UI, unlike .Fl E . -.Ic :help silent-mode +.Ic ":help silent-mode" .It Fl d Diff mode. Show the difference between two to eight files, similar to @@ -105,34 +105,34 @@ Show the difference between two to eight files, similar to .Ic ":help diff" .It Fl R Read-only mode. -Sets the 'readonly' option. +Sets the \(aqreadonly\(aq option. Implies .Fl n . Buffers can still be edited, but cannot be written to disk if already associated with a file. To overwrite a file, add an exclamation mark to the relevant Ex command, such as -.Ic :w! . +.Ic :w\&! . .Ic ":help 'readonly'" .It Fl m -Resets the 'write' option, to disable file modifications. +Resets the \(aqwrite\(aq option, to disable file modifications. Writing to a file is disabled, but buffers can still be modified. .It Fl M -Resets the 'write' and 'modifiable' options, to disable file and buffer -modifications. +Resets the \(aqwrite\(aq and \(aqmodifiable\(aq options, to disable file and +buffer modifications. .It Fl b Binary mode. .Ic ":help edit-binary" .It Fl A Arabic mode. -Sets the 'arabic' option. +Sets the \(aqarabic\(aq option. .It Fl H Hebrew mode. -Sets the 'hkmap' and 'rightleft' options. +Sets the \(aqhkmap\(aq and \(aqrightleft\(aq options. .It Fl V Ns Oo Ar N Oc Ns Op Ar file Verbose mode. Prints debug messages. .Ar N -is the 'verbose' level, defaults to +is the \(aqverbose\(aq level, defaults to .Cm 10 . If .Ar file @@ -143,10 +143,10 @@ instead of printing them. .It Fl D Vimscript debug mode. Started when executing the first command from a script. -:help debug-mode +.Ic ":help debug-mode" .It Fl n Disable the use of swap files. -Sets the 'updatecount' option to +Sets the \(aqupdatecount\(aq option to .Cm 0 . Can be useful for editing files on a slow medium. .It Fl r Op Ar file @@ -158,7 +158,7 @@ then list swap files with recovery information. Otherwise the swap file .Ar file is used to recover a crashed session. -The swap file has the same name as the file it's associated with, but with +The swap file has the same name as the file it\(aqs associated with, but with .Sq .swp appended. .Ic ":help recovery" @@ -193,11 +193,12 @@ is do not read or write a ShaDa file. .Ic ":help shada" .It Fl -noplugin -Skip loading plugins (by setting the 'noloadplugins' option). +Skip loading plugins (by setting the \(aqnoloadplugins\(aq option). Implied by .Cm -u NONE . .It Fl -clean -Start Nvim with "factory defaults" (no user config and plugins, no shada). +Start Nvim with \(lqfactory defaults\(rq (no user config and plugins, no +shada). .Ic ":help --clean" .It Fl o Ns Op Ar N Open @@ -248,7 +249,7 @@ and inside .Nm . .Ic ":help search-pattern" -.It \fB\+\fR\fI\,command\/\fR , Fl c Ar command +.It Cm + Ns Ar command , Fl c Ar command Execute .Ar command after reading the first file. @@ -280,7 +281,8 @@ stops processing of Nvim arguments. .It Fl S Op Ar session Execute .Ar session -after the first file argument has been read. If +after the first file argument has been read. +If .Ar session filename ends with .Pa .lua @@ -310,7 +312,7 @@ Append all typed characters to Can be used for creating a script to be used with .Fl s or -.Ic :source! . +.Ic :source\&! . .It Fl W Ar scriptout Like .Fl w , @@ -324,12 +326,15 @@ Can be used to diagnose slow startup times. Dump API metadata serialized to msgpack and exit. .It Fl -embed Use standard input and standard output as a msgpack-rpc channel. -:help --embed +.Ic ":help --embed" .It Fl -headless Do not start a UI. -When supplied with --embed this implies that the embedding application does not intend to (immediately) start a UI. -Also useful for "scraping" messages in a pipe. -:help --headless +When supplied with +.Cm --embed +this implies that the embedding application does not intend to (immediately) +start a UI. +Also useful for \(lqscraping\(rq messages in a pipe. +.Ic ":help --headless" .It Fl -listen Ar address Start RPC server on this pipe or TCP socket. .It Fl h , -help @@ -343,14 +348,15 @@ Print version information and exit. The name of sub-directories used within each XDG user directory. Defaults to .Cm nvim . -:help $NVIM_APPNAME +.Ic ":help $NVIM_APPNAME" .It Ev NVIM_LOG_FILE -Low-level log file, usually found at ~/.local/state/nvim/log. -:help $NVIM_LOG_FILE +Low-level log file, usually found at +.Pa ~/.local/state/nvim/log . +.Ic ":help $NVIM_LOG_FILE" .It Ev VIM Used to locate user files, such as init.vim. System-dependent. -:help $VIM +.Ic ":help $VIM" .It Ev VIMRUNTIME Used to locate runtime files (documentation, syntax highlighting, etc.). .It Ev XDG_CONFIG_HOME @@ -358,7 +364,7 @@ Path to the user-local configuration directory, see .Sx FILES . Defaults to .Pa ~/.config . -:help xdg +.Ic ":help xdg" .It Ev XDG_STATE_HOME Like .Ev XDG_CONFIG_HOME , @@ -366,7 +372,7 @@ but used to store data not generally edited by the user, namely swap, backup, and ShaDa files. Defaults to .Pa ~/.local/state . -:help xdg +.Ic ":help xdg" .It Ev XDG_DATA_HOME Like .Ev XDG_CONFIG_HOME , @@ -374,15 +380,16 @@ but used to store data not generally edited by the user, things like runtime files. Defaults to .Pa ~/.local/share . -:help xdg +.Ic ":help xdg" .It Ev VIMINIT Ex commands to be executed at startup. .Ic ":help VIMINIT" .It Ev SHELL -Used to initialize the 'shell' option, which decides the default shell used by -features like +Used to initialize the \(aqshell\(aq option, which decides the default shell +used by features like .Ic :terminal , -.Ic :! , and +.Ic :! , +and .Ic system() . .El .Sh FILES @@ -408,13 +415,13 @@ runtime directory. .El .Sh AUTHORS Nvim was started by -.An Thiago de Arruda . +.An "Thiago de Arruda" . Most of Vim was written by .An -nosplit -.An Bram Moolenaar . +.An "Bram Moolenaar" . Vim is based on Stevie, worked on by -.An Tim Thompson , -.An Tony Andrews , +.An "Tim Thompson" , +.An "Tony Andrews" , and -.An G.R. (Fred) Walter . +.An "G.R. (Fred) Walter" . .Ic ":help credits"
diff --git a/src/man/nvim.1 b/src/man/nvim.1 index 9b7680d0112cb2..82a06b4a11ebf1 100644 --- a/src/man/nvim.1 +++ b/src/man/nvim.1 @@ -30,18 +30,17 @@ Commands in .Nm begin with colon .Pq Sq \&: . -Use <Tab> and CTRL-D to complete subjects (":help cmdline\-completion"). +Use <Tab> and CTRL-D to complete subjects (\(lq:help cmdline-completion\(rq). -The "quickref" help section is a condensed reference of editor features: +The \(lqquickref\(rq help section is a condensed reference of editor features: .Dl :help quickref If you are new to Vim/Nvim, start with the 30-minute tutorial: .Dl :Tutor -After installing/updating Nvim, it's a good idea to run the self-check: +After installing/updating Nvim, it\(aqs a good idea to run the self-check: .Dl :checkhealth -.Pp .Bl -tag -width Fl .It Ar file ... File(s) to edit. @@ -72,7 +71,7 @@ Display the first error in .Ar errorfile . .Ar errorfile -is omitted, the value of the 'errorfile' option is used (defaults to +is omitted, the value of the \(aqerrorfile\(aq option is used (defaults to .Cm errors.err ) . Further errors can be jumped to with the .Ic :cnext @@ -80,24 +79,25 @@ command. .Ic ":help quickfix" .It Fl - End of options. -Remaining arguments are treated as literal file names, including filenames starting with hyphen +Remaining arguments are treated as literal file names, including filenames .Pq Sq - . .It Fl e Ex mode, reading stdin as Ex commands. .Ic ":help Ex-mode" .It Fl E Ex mode, reading stdin as text. -.Ic :help Ex-mode .It Fl es Silent (non-interactive) Ex mode, reading stdin as Ex commands. .Fl e . .It Fl \&Es Silent (non-interactive) Ex mode, reading stdin as text. .Fl E . .It Fl d Diff mode. Show the difference between two to eight files, similar to @@ -105,34 +105,34 @@ Show the difference between two to eight files, similar to .Ic ":help diff" .It Fl R Read-only mode. -Sets the 'readonly' option. +Sets the \(aqreadonly\(aq option. Implies .Fl n . Buffers can still be edited, but cannot be written to disk if already associated with a file. To overwrite a file, add an exclamation mark to the relevant Ex command, such as -.Ic :w! . +.Ic :w\&! . .Ic ":help 'readonly'" .It Fl m -Resets the 'write' option, to disable file modifications. +Resets the \(aqwrite\(aq option, to disable file modifications. Writing to a file is disabled, but buffers can still be modified. .It Fl M -Resets the 'write' and 'modifiable' options, to disable file and buffer -modifications. +Resets the \(aqwrite\(aq and \(aqmodifiable\(aq options, to disable file and +buffer modifications. .It Fl b Binary mode. .Ic ":help edit-binary" .It Fl A Arabic mode. -Sets the 'arabic' option. +Sets the \(aqarabic\(aq option. .It Fl H Hebrew mode. -Sets the 'hkmap' and 'rightleft' options. .It Fl V Ns Oo Ar N Oc Ns Op Ar file Verbose mode. Prints debug messages. .Ar N -is the 'verbose' level, defaults to +is the \(aqverbose\(aq level, defaults to .Cm 10 . @@ -143,10 +143,10 @@ instead of printing them. .It Fl D Vimscript debug mode. Started when executing the first command from a script. -:help debug-mode .It Fl n Disable the use of swap files. -Sets the 'updatecount' option to +Sets the \(aqupdatecount\(aq option to .Cm 0 . Can be useful for editing files on a slow medium. .It Fl r Op Ar file @@ -158,7 +158,7 @@ then list swap files with recovery information. Otherwise the swap file is used to recover a crashed session. -The swap file has the same name as the file it's associated with, but with +The swap file has the same name as the file it\(aqs associated with, but with .Sq .swp appended. .Ic ":help recovery" @@ -193,11 +193,12 @@ is do not read or write a ShaDa file. .Ic ":help shada" .It Fl -noplugin -Skip loading plugins (by setting the 'noloadplugins' option). +Skip loading plugins (by setting the \(aqnoloadplugins\(aq option). Implied by .Cm -u NONE . .It Fl -clean -Start Nvim with "factory defaults" (no user config and plugins, no shada). +shada). .Ic ":help --clean" .It Fl o Ns Op Ar N Open @@ -248,7 +249,7 @@ and inside .Nm . .Ic ":help search-pattern" -.It \fB\+\fR\fI\,command\/\fR , Fl c Ar command +.It Cm + Ns Ar command , Fl c Ar command .Ar command after reading the first file. @@ -280,7 +281,8 @@ stops processing of Nvim arguments. .It Fl S Op Ar session -after the first file argument has been read. If +after the first file argument has been read. +If filename ends with .Pa .lua @@ -310,7 +312,7 @@ Append all typed characters to Can be used for creating a script to be used with .Fl s or -.Ic :source! . +.Ic :source\&! . .It Fl W Ar scriptout .Fl w , @@ -324,12 +326,15 @@ Can be used to diagnose slow startup times. Dump API metadata serialized to msgpack and exit. .It Fl -embed Use standard input and standard output as a msgpack-rpc channel. -:help --embed +.Ic ":help --embed" .It Fl -headless Do not start a UI. -When supplied with --embed this implies that the embedding application does not intend to (immediately) start a UI. -Also useful for "scraping" messages in a pipe. -:help --headless +When supplied with +.Cm --embed +this implies that the embedding application does not intend to (immediately) +start a UI. +Also useful for \(lqscraping\(rq messages in a pipe. +.Ic ":help --headless" .It Fl -listen Ar address Start RPC server on this pipe or TCP socket. .It Fl h , -help @@ -343,14 +348,15 @@ Print version information and exit. The name of sub-directories used within each XDG user directory. .Cm nvim . -:help $NVIM_APPNAME +.Ic ":help $NVIM_APPNAME" .It Ev NVIM_LOG_FILE -Low-level log file, usually found at ~/.local/state/nvim/log. -:help $NVIM_LOG_FILE +Low-level log file, usually found at +.Pa ~/.local/state/nvim/log . +.Ic ":help $NVIM_LOG_FILE" .It Ev VIM Used to locate user files, such as init.vim. System-dependent. -:help $VIM +.Ic ":help $VIM" .It Ev VIMRUNTIME Used to locate runtime files (documentation, syntax highlighting, etc.). .It Ev XDG_CONFIG_HOME @@ -358,7 +364,7 @@ Path to the user-local configuration directory, see .Sx FILES . .Pa ~/.config . .It Ev XDG_STATE_HOME @@ -366,7 +372,7 @@ but used to store data not generally edited by the user, namely swap, backup, and ShaDa files. .Pa ~/.local/state . .It Ev XDG_DATA_HOME @@ -374,15 +380,16 @@ but used to store data not generally edited by the user, things like runtime files. .Pa ~/.local/share . .It Ev VIMINIT Ex commands to be executed at startup. .Ic ":help VIMINIT" .It Ev SHELL -Used to initialize the 'shell' option, which decides the default shell used by -features like +Used to initialize the \(aqshell\(aq option, which decides the default shell +used by features like .Ic :terminal , -.Ic :! , and +.Ic :! , .Ic system() . .Sh FILES @@ -408,13 +415,13 @@ runtime directory. .Sh AUTHORS Nvim was started by -.An Thiago de Arruda . +.An "Thiago de Arruda" . Most of Vim was written by .An -nosplit -.An Bram Moolenaar . +.An "Bram Moolenaar" . Vim is based on Stevie, worked on by -.An Tim Thompson , +.An "Tim Thompson" , +.An "Tony Andrews" , and -.An G.R. (Fred) Walter . +.An "G.R. (Fred) Walter" . .Ic ":help credits"
[ "-Type \":help subject\" to get help on a specific subject.", "+Type \\(lq:help subject\\(rq to get help on a specific subject.", "+starting with hyphen", "+.Ic \":help Ex-mode\"", "+Sets the \\(aqhkmap\\(aq and \\(aqrightleft\\(aq options.", "+.Ic \":help debug-mode\"", "+Start Nvim with \\(lqfactory defaults\\(rq (no user config and plugins, no", "+and", "-.An Tony Andrews ," ]
[ 8, 10, 42, 50, 99, 114, 141, 249, 265 ]
{ "additions": 52, "author": "e-kwsm", "deletions": 45, "html_url": "https://github.com/neovim/neovim/pull/33484", "issue_id": 33484, "merged_at": "2025-04-16T10:03:37Z", "omission_probability": 0.1, "pr_number": 33484, "repo": "neovim/neovim", "title": "docs(man): fix mandoc warnings and prettify", "total_changes": 97 }
397
diff --git a/CHANGELOG.md b/CHANGELOG.md index 33da56d9bfc58..9ac4e930b6d28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,50 @@ +<a name="20.0.0-next.8"></a> +# 20.0.0-next.8 (2025-04-23) +## Breaking Changes +### compiler +- 'in' in an expression now refers to the operator +### core +- `provideExperimentalZonelessChangeDetection` is + renamed to `provideZonelessChangeDetection` as it is now "Developer + Preview" rather than "Experimental". +### router +- The `RedirectFn` can now return `Observable` or + `Promise`. Any code that directly calls functions returning this type + may need to be adjusted to account for this. +- Several methods in the public API of the Router which + required writable arrays have now been updated to accept readonly + arrays when no mutations are done. +## Deprecations +### platform-server +- `@angular/platform-server/testing` + + Use e2e tests to verify SSR behavior instead. +### compiler +| Commit | Type | Description | +| -- | -- | -- | +| [1b8e7ab9fe](https://github.com/angular/angular/commit/1b8e7ab9fe46901979389b377be4232e11092260) | feat | support the `in` keyword in Binary expression ([#58432](https://github.com/angular/angular/pull/58432)) | +### core +| Commit | Type | Description | +| -- | -- | -- | +| [953c4b2580](https://github.com/angular/angular/commit/953c4b25808b357e78bf1cf6b2ef8b4a84ffaf49) | feat | Move zoneless change detection to dev preview ([#60748](https://github.com/angular/angular/pull/60748)) | +| [0ac949c266](https://github.com/angular/angular/commit/0ac949c266637ab723430ff17adb1af58b14fa0d) | fix | do not run change detection on global error events ([#60944](https://github.com/angular/angular/pull/60944)) | +| [0162ceb427](https://github.com/angular/angular/commit/0162ceb427243e065d2cd81042451d705838d090) | fix | inject migration should treat `@Attribute` as optional ([#60916](https://github.com/angular/angular/pull/60916)) | +### forms +| Commit | Type | Description | +| -- | -- | -- | +| [be995623cd](https://github.com/angular/angular/commit/be995623cd9604633384c8697dc0c1bf6066e756) | fix | make NgForm emit FormSubmittedEvent and FormResetEvent ([#60887](https://github.com/angular/angular/pull/60887)) | +### platform-server +| Commit | Type | Description | +| -- | -- | -- | +| [2240a21c97](https://github.com/angular/angular/commit/2240a21c9703f3b1945a37ebe86428a8daf40b36) | refactor | deprecate the testing entry point ([#60915](https://github.com/angular/angular/pull/60915)) | +### router +| Commit | Type | Description | +| -- | -- | -- | +| [62de7d930a](https://github.com/angular/angular/commit/62de7d930a5d2f3cc39b6bf38dedbe3e9d938842) | feat | add asynchronous redirects ([#60863](https://github.com/angular/angular/pull/60863)) | +| [2419060fef](https://github.com/angular/angular/commit/2419060fef4e59a5633c29bfd5d55e2d5a17dd00) | fix | relax required types on router commands to readonly array ([#60345](https://github.com/angular/angular/pull/60345)) | + +<!-- CHANGELOG SPLIT MARKER --> + <a name="19.2.8"></a> # 19.2.8 (2025-04-23) ### forms diff --git a/package.json b/package.json index 28c2432f79afd..127088bdbe206 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "20.0.0-next.7", + "version": "20.0.0-next.8", "private": true, "description": "Angular - a web framework for modern web apps", "homepage": "https://github.com/angular/angular",
diff --git a/CHANGELOG.md b/CHANGELOG.md index 33da56d9bfc58..9ac4e930b6d28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,50 @@ +<a name="20.0.0-next.8"></a> +# 20.0.0-next.8 (2025-04-23) +## Breaking Changes +- 'in' in an expression now refers to the operator +- `provideExperimentalZonelessChangeDetection` is + renamed to `provideZonelessChangeDetection` as it is now "Developer + Preview" rather than "Experimental". +- The `RedirectFn` can now return `Observable` or + `Promise`. Any code that directly calls functions returning this type + may need to be adjusted to account for this. +- Several methods in the public API of the Router which + required writable arrays have now been updated to accept readonly + arrays when no mutations are done. +## Deprecations +- `@angular/platform-server/testing` + + Use e2e tests to verify SSR behavior instead. +| [1b8e7ab9fe](https://github.com/angular/angular/commit/1b8e7ab9fe46901979389b377be4232e11092260) | feat | support the `in` keyword in Binary expression ([#58432](https://github.com/angular/angular/pull/58432)) | +| [953c4b2580](https://github.com/angular/angular/commit/953c4b25808b357e78bf1cf6b2ef8b4a84ffaf49) | feat | Move zoneless change detection to dev preview ([#60748](https://github.com/angular/angular/pull/60748)) | +| [0ac949c266](https://github.com/angular/angular/commit/0ac949c266637ab723430ff17adb1af58b14fa0d) | fix | do not run change detection on global error events ([#60944](https://github.com/angular/angular/pull/60944)) | +| [0162ceb427](https://github.com/angular/angular/commit/0162ceb427243e065d2cd81042451d705838d090) | fix | inject migration should treat `@Attribute` as optional ([#60916](https://github.com/angular/angular/pull/60916)) | +### forms +| [be995623cd](https://github.com/angular/angular/commit/be995623cd9604633384c8697dc0c1bf6066e756) | fix | make NgForm emit FormSubmittedEvent and FormResetEvent ([#60887](https://github.com/angular/angular/pull/60887)) | +| [2240a21c97](https://github.com/angular/angular/commit/2240a21c9703f3b1945a37ebe86428a8daf40b36) | refactor | deprecate the testing entry point ([#60915](https://github.com/angular/angular/pull/60915)) | +| [62de7d930a](https://github.com/angular/angular/commit/62de7d930a5d2f3cc39b6bf38dedbe3e9d938842) | feat | add asynchronous redirects ([#60863](https://github.com/angular/angular/pull/60863)) | +| [2419060fef](https://github.com/angular/angular/commit/2419060fef4e59a5633c29bfd5d55e2d5a17dd00) | fix | relax required types on router commands to readonly array ([#60345](https://github.com/angular/angular/pull/60345)) | +<!-- CHANGELOG SPLIT MARKER --> <a name="19.2.8"></a> # 19.2.8 (2025-04-23) ### forms diff --git a/package.json b/package.json index 28c2432f79afd..127088bdbe206 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "20.0.0-next.7", "private": true, "description": "Angular - a web framework for modern web apps", "homepage": "https://github.com/angular/angular",
[ "+ \"version\": \"20.0.0-next.8\"," ]
[ 63 ]
{ "additions": 48, "author": "pkozlowski-opensource", "deletions": 1, "html_url": "https://github.com/angular/angular/pull/60987", "issue_id": 60987, "merged_at": "2025-04-23T15:18:07Z", "omission_probability": 0.1, "pr_number": 60987, "repo": "angular/angular", "title": "Bump version to \"v20.0.0-next.8\" with changelog.", "total_changes": 49 }
398
diff --git a/CHANGELOG.md b/CHANGELOG.md index 90e875c61dc05..9e3f3c20e7c1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +<a name="19.2.8"></a> +# 19.2.8 (2025-04-23) +### forms +| Commit | Type | Description | +| -- | -- | -- | +| [ea4a211216](https://github.com/angular/angular/commit/ea4a21121681c78652f314c78c58390dca25f266) | fix | make NgForm emit FormSubmittedEvent and FormResetEvent ([#60887](https://github.com/angular/angular/pull/60887)) | + +<!-- CHANGELOG SPLIT MARKER --> + <a name="19.2.7"></a> # 19.2.7 (2025-04-16) ### common diff --git a/package.json b/package.json index b98df11c6e030..825608df55427 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "19.2.7", + "version": "19.2.8", "private": true, "description": "Angular - a web framework for modern web apps", "homepage": "https://github.com/angular/angular",
diff --git a/CHANGELOG.md b/CHANGELOG.md index 90e875c61dc05..9e3f3c20e7c1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +<a name="19.2.8"></a> +# 19.2.8 (2025-04-23) +### forms +| Commit | Type | Description | +| -- | -- | -- | +| [ea4a211216](https://github.com/angular/angular/commit/ea4a21121681c78652f314c78c58390dca25f266) | fix | make NgForm emit FormSubmittedEvent and FormResetEvent ([#60887](https://github.com/angular/angular/pull/60887)) | +<!-- CHANGELOG SPLIT MARKER --> <a name="19.2.7"></a> # 19.2.7 (2025-04-16) ### common diff --git a/package.json b/package.json index b98df11c6e030..825608df55427 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "19.2.7", + "version": "19.2.8", "private": true, "description": "Angular - a web framework for modern web apps", "homepage": "https://github.com/angular/angular",
[]
[]
{ "additions": 10, "author": "pkozlowski-opensource", "deletions": 1, "html_url": "https://github.com/angular/angular/pull/60985", "issue_id": 60985, "merged_at": "2025-04-23T15:11:58Z", "omission_probability": 0.1, "pr_number": 60985, "repo": "angular/angular", "title": "Bump version to \"v19.2.8\" with changelog.", "total_changes": 11 }
399
diff --git a/CHANGELOG.md b/CHANGELOG.md index 90e875c61dc05..9e3f3c20e7c1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +<a name="19.2.8"></a> +# 19.2.8 (2025-04-23) +### forms +| Commit | Type | Description | +| -- | -- | -- | +| [ea4a211216](https://github.com/angular/angular/commit/ea4a21121681c78652f314c78c58390dca25f266) | fix | make NgForm emit FormSubmittedEvent and FormResetEvent ([#60887](https://github.com/angular/angular/pull/60887)) | + +<!-- CHANGELOG SPLIT MARKER --> + <a name="19.2.7"></a> # 19.2.7 (2025-04-16) ### common diff --git a/package.json b/package.json index b98df11c6e030..825608df55427 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "19.2.7", + "version": "19.2.8", "private": true, "description": "Angular - a web framework for modern web apps", "homepage": "https://github.com/angular/angular",
diff --git a/CHANGELOG.md b/CHANGELOG.md index 90e875c61dc05..9e3f3c20e7c1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +<a name="19.2.8"></a> +# 19.2.8 (2025-04-23) +### forms +| -- | -- | -- | +| [ea4a211216](https://github.com/angular/angular/commit/ea4a21121681c78652f314c78c58390dca25f266) | fix | make NgForm emit FormSubmittedEvent and FormResetEvent ([#60887](https://github.com/angular/angular/pull/60887)) | +<!-- CHANGELOG SPLIT MARKER --> <a name="19.2.7"></a> # 19.2.7 (2025-04-16) ### common diff --git a/package.json b/package.json index b98df11c6e030..825608df55427 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-srcs", - "version": "19.2.7", + "version": "19.2.8", "private": true, "description": "Angular - a web framework for modern web apps", "homepage": "https://github.com/angular/angular",
[ "+| Commit | Type | Description |" ]
[ 8 ]
{ "additions": 10, "author": "pkozlowski-opensource", "deletions": 1, "html_url": "https://github.com/angular/angular/pull/60982", "issue_id": 60982, "merged_at": "2025-04-23T14:29:07Z", "omission_probability": 0.1, "pr_number": 60982, "repo": "angular/angular", "title": "Bump version to \"v19.2.8\" with changelog.", "total_changes": 11 }